Designing an Idempotent Multi-Threaded Kafka Consumer with Cross-Database Sync

Medium · System Design · Software Engineer · Technical Screen

Prompt

An asynchronous backend worker service reads event messages from a Kafka topic. Each consumed event persists a row into a primary database, which triggers subsequent internal workflows; no external caller blocks waiting for a synchronous reply. Because delivery is at-least-once and consumers run multi-threaded worker pools, the exact same event can be redelivered or executed by multiple threads simultaneously.

Design this consumer pipeline around three progressive requirements:

  1. Atomic deduplication under concurrency: Explain how duplicate and simultaneous executions arise in a Kafka consumer group, why application-level read-before-write checks and partition-key routing alone cannot prevent race conditions, and how to guarantee each logical event mutates state once even when two threads race on the same payload.
  2. Conflict handling, offset progression, and mid-flight crashes: When a thread attempts to persist an event and discovers the row is already committed, evaluate raising a duplicate-key exception versus returning the stored record. Detail how Kafka partition offsets advance safely when worker threads finish out of order, and how your pipeline recovers if a prior worker crashed immediately after committing the primary row before triggering downstream steps.
  3. Asynchronous replication to a secondary store: Every processed event must also propagate asynchronously to a secondary database. Show why back-to-back writes across separate storage systems diverge under partial failures, how to couple outbound replication events atomically to the primary commit (including when broker publishing fails), how the secondary store handles duplicate or reordered updates, and when a distributed transaction would or would not be justified.

Scope & Expectations

  • Clarify event identity guarantees, concurrency vectors (thread pools, partition rebalances, producer retries), downstream handoff boundaries, and acceptable replication lag for the secondary store.
  • Enforce single-effect persistence atomically at the database layer rather than relying on racy in-memory or cache checks.
  • Specify clean duplicate-return semantics, contiguous offset-watermark commits across concurrent workers, and crash-safe handoffs to downstream logic.
  • Ensure eventual convergence of the secondary database across broker and process outages using atomic commit coupling and idempotent, reorder-safe writes.

Step-by-step walkthrough

  1. Clarify requirements, terms, and core invariants

    Before designing the pipeline, let's define four foundational terms in plain English so every piece of the problem is crystal clear:

    • Kafka topic and partition: a topic is an append-only stream of messages split into numbered lanes called partitions, where messages inside a single partition sit at sequential integer positions (0, 1, 2, ...) called offsets.
    • Consumer offset commit: a bookmark saved by the consumer group saying "every message before offset N in this partition is completely handled; if I crash, resume reading at N."
    • At-least-once delivery: Kafka's standard guarantee where messages are never silently dropped, which means crashes, network retries, or partition handoffs can deliver the same message two or more times.
    • Idempotency: the property that processing the exact same business event once, twice, or ten times leaves all databases and downstream systems in the exact same state as processing it once.

    Next, let's clarify four key design dimensions and lock in explicit assumptions:

    1. Stable unique identifier: Yes. Every message carries a message_id (UUID) generated once by the producer when the business event occurs and reused across any producer retries or application resends. If an upstream producer lacks a message_id, we derive a deterministic key from immutable business fields—such as (source_service, order_id, event_type, version)—never from a send timestamp or the Kafka offset (because a producer resend lands at a brand-new Kafka offset).
    2. How concurrency happens: All three sources occur in production, so our design must handle all of them: (a) an in-process worker thread pool inside one consumer, (b) overlapping old and new consumers during a partition rebalance, and (c) duplicate publishes of the same event at different offsets.
    3. Who reads the result: No external caller blocks waiting for an HTTP response. Processing writes a record to the primary database (DB1), triggers downstream business logic, and asynchronously syncs a second database (DB2).
    4. Consistency target for DB2: Eventual consistency within a few seconds is acceptable, provided DB2 always converges to DB1's state and never permanently misses or double-applies an update.

    Core system invariants

    1. DB1 stores at most one row per message_id, enforced atomically by the database engine rather than application memory.
    2. Partition offset N is committed only after every offset < N in that partition has reached a final state (applied, deduplicated, or parked in a dead-letter topic).
    3. Updating DB1 and recording the obligation to update DB2 happen inside one atomic DB1 transaction.
    4. Applying an event to DB2 multiple times or out of order produces the exact same final row as applying it once in order.
  2. Back-of-the-envelope sizing

    Concrete numbers show where bottlenecks live and how big deduplication storage becomes:

    Workload assumptions
      Average traffic:        2,000 msg/s (~1 KB payload) -> ~2 MB/s
      Peak traffic:          10,000 msg/s (~1 KB payload) -> ~10 MB/s
      Kafka topic:           32 partitions, partition key = order_id
    
    Consumer and worker sizing
      1 DB1 transaction (insert record + insert outbox + commit): ~4 ms round-trip
      Throughput per worker thread:   1,000 ms / 4 ms = 250 msg/s
      Busy workers needed at peak:    10,000 / 250 = 40 workers
      Provisioned fleet:              8 consumer instances x 8 worker threads = 64 workers
                                      (16,000 msg/s capacity -> 60% headroom over peak)
      Partitions per instance:        32 / 8 = 4 partitions; cap 500 in-flight records/partition
    
    DB1 write load at peak
      10,000 tx/s x 2 rows (records + outbox) = 20,000 row inserts/s  <-- primary bottleneck
    
    Expected duplicates on crash
      Peak rate per instance:         10,000 / 8 = 1,250 msg/s
      With 1-second offset commits:   ~1,250 uncommitted finished msgs + up to 4 x 500 = 2,000 in-flight
                                      -> ~3,250 replayed messages when one instance crashes at peak
    
    Idempotency storage
      Option A (UNIQUE column on records table): 16 B UUID + ~35 B B-tree entry = ~50 B/row, kept with row
      Option B (separate 7-day dedup table):     2,000 msg/s x 86,400 s x 7 d = 1.21B rows x ~100 B = ~121 GB
    
    DB2 catch-up capacity
      DB2 batched upsert capacity:    10,000 events/s
      1 hour of DB2 lag at average:   2,000 x 3,600 = 7.2M queued events
      Drain time at average load:     7.2M / (10,000 - 2,000 net catch-up/s) = 900 s = 15 minutes
    

    Two design lessons jump right out of this math: - Putting message_id UNIQUE directly on the business records table costs ~50 bytes per row and avoids managing a separate 121 GB deduplication table. - DB1 write throughput (20,000 inserts/s at peak), not Kafka network bandwidth (10 MB/s), is the bottleneck we must protect.

  3. Message contract and internal interfaces

    Separating the partition routing key from the idempotency key keeps ordering and deduplication independent:

    1. Incoming Kafka record (topic: orders.events)
       key:   order_id          (routes all events for one order to the same partition in order)
       value: {
         "message_id": "uuid-set-once-by-producer",
         "order_id":   "ord_9812",
         "amount":     4500,
         "version":    3,
         "occurred_at": "2026-11-30T12:00:00Z"
       }
    
    2. Consumer worker interface
       handle(conn, message) -> ("applied", record_id) | ("duplicate", record_id)
         Raises PayloadMismatch if an existing row has the same message_id but different business data.
    
    3. Offset watermark tracker
       OffsetTracker.assign(partition, epoch)
       OffsetTracker.dispatched(partition, epoch, offset)   # called on poll thread in offset order
       OffsetTracker.finished(partition, epoch, offset)     # called on worker thread when done
       OffsetTracker.safe_to_commit() -> dict[partition, next_offset]
    
    4. Outbox sync event (topic: orders.db2-sync)
       key:   order_id
       value: {"event_id": message_id, "order_id": "ord_9812", "amount": 4500, "version": 3}
    
  4. Data model across DB1 and DB2

    DB1 (PostgreSQL — source of truth)
      records (
        id            BIGSERIAL PRIMARY KEY,
        message_id    UUID NOT NULL UNIQUE,      -- atomic deduplication claim
        order_id      TEXT NOT NULL,
        amount        BIGINT NOT NULL,
        version       BIGINT NOT NULL,
        content_hash  TEXT NOT NULL,             -- SHA-256 of canonical business payload
        status        TEXT NOT NULL DEFAULT 'RECORDED', -- 'RECORDED' -> 'DONE' if external step exists
        created_at    TIMESTAMPTZ NOT NULL DEFAULT now()
      )
    
      outbox (
        id            BIGSERIAL PRIMARY KEY,
        event_id      UUID NOT NULL UNIQUE,      -- equals message_id
        aggregate_id  TEXT NOT NULL,             -- equals order_id (used as Kafka partition key)
        payload       JSONB NOT NULL,
        created_at    TIMESTAMPTZ NOT NULL DEFAULT now(),
        lease_until   TIMESTAMPTZ NULL,          -- prevents two polling relays grabbing same row
        published_at  TIMESTAMPTZ NULL           -- NULL until confirmed by Kafka broker
      )
      -- Partial index keeps relay scans fast even when millions of historical rows exist:
      CREATE INDEX outbox_unpublished_idx ON outbox (id) WHERE published_at IS NULL;
    
    DB2 (Asynchronous read/analytics store)
      order_view (
        order_id      TEXT PRIMARY KEY,
        amount        BIGINT NOT NULL,
        version       BIGINT NOT NULL,           -- guards against duplicate and out-of-order events
        updated_at    TIMESTAMPTZ NOT NULL
      )
    

    If a consumer's business action updates an existing row instead of inserting a new one (for example, UPDATE accounts SET balance = balance - 100), add a companion processed_messages(message_id UUID PRIMARY KEY, created_at TIMESTAMPTZ) table partitioned by day and insert into it inside the exact same DB1 transaction as the UPDATE.

  5. High-level architecture

      Producers (assign message_id once)
             |
             v
      Kafka: orders.events (32 partitions, key = order_id)
             |
             v
      +-------------------------------------------------------------------------------+
      | Consumer Instance (8 instances, 4 partitions each)                            |
      |                                                                               |
      |  [Poll Thread]                                                                |
      |   1. Polls batch; pauses partition if >= 500 records in flight (backpressure) |
      |   2. Registers offset in OffsetTracker.dispatched(partition, epoch, offset)   |
      |   3. Routes record to worker[hash(order_id) % 8] to preserve per-order order  |
      |   4. Every 1 s: commits OffsetTracker.safe_to_commit() to Kafka               |
      |         |                                             ^                       |
      |         v                                             | finished(...)         |
      |  [Worker Pool: 8 threads]                             |                       |
      |   process_one() -> handle(conn, msg) -----------------+                       |
      +---------|---------------------------------------------------------------------+
                |
                | Single DB1 ACID transaction:
                |   1. INSERT INTO records ... ON CONFLICT (message_id) DO NOTHING
                |   2. If inserted: INSERT INTO outbox ... (schedules downstream + DB2)
                v
      +--------------------+       WAL / Polling      +---------------+
      | DB1                | -----------------------> | Outbox Relay  |
      | records + outbox   |    (Debezium CDC or      |               |
      +--------------------+     lease poller)        +-------+-------+
                                                              |
                +---------------------------------------------+
                |                                             |
                v                                             v
      Downstream consumers                       Kafka: orders.db2-sync (key = order_id)
      (triggered from outbox topic)                           |
                                                              v
      Dead-Letter Topic (DLQ)                    +------------------------+
      (parks corrupt/poison payloads             | DB2 Applier            |
       with alerts so partitions                 | Upsert where           | ---> [ DB2 ]
       never stall)                              | stored.ver < event.ver |
                                                 +------------------------+
    

    A dead-letter queue (DLQ) is a side topic where permanently invalid ("poison") messages—such as malformed JSON—are set aside for inspection so they do not block healthy messages behind them.

  6. Deep dive 1: atomic deduplication under concurrent execution

    Sources of duplicate and simultaneous execution

    1. Crash before offset commit: a worker commits to DB1, then the process crashes before the 1-second offset commit runs. On restart, Kafka redelivers the message.
    2. Consumer rebalance overlap (zombie consumer): a rebalance is when Kafka reassigns partitions across consumer instances (for example, during a deploy or a long garbage-collection pause). An instance that paused longer than max.poll.interval.ms loses its partition to a new instance, but when the paused zombie consumer wakes up, both instances briefly process the exact same message concurrently.
    3. In-process timeout/retry or duplicate dispatch: a worker pool retries a slow task while the first thread is still blocked on I/O.
    4. Producer retry or upstream resend: if an upstream producer or relay retries without broker-level deduplication, Kafka appends a second copy at a brand-new offset.

    Why application-level read-before-write fails

    Suppose two threads run SELECT id FROM records WHERE message_id = ? and insert if nothing comes back:

    Time   Thread A (msg-42)                       Thread B (msg-42, concurrent)
    ----   -------------------------------------   -------------------------------------
    t1     SELECT ... WHERE message_id = 'msg-42'
           -> 0 rows
    t2                                             SELECT ... WHERE message_id = 'msg-42'
                                                   -> 0 rows
    t3     INSERT INTO records ...                 INSERT INTO records ...
           -> Without UNIQUE constraint: TWO duplicate rows committed!
           -> With UNIQUE constraint: Thread B crashes with unhandled UniqueViolation!
    

    Checking Redis (SET msg-42 1 NX) before writing DB1 also fails: if the worker sets the Redis key and crashes before committing DB1, redelivered attempts see the Redis key, skip DB1, and lose the write forever.

    Combining check and insert into one atomic DB1 statement

    By placing UNIQUE (message_id) on DB1.records and running at READ COMMITTED isolation (PostgreSQL's default, where each statement sees data committed before that statement began), the database index serializes concurrent threads automatically:

    Time   Thread A (msg-42)                       Thread B (msg-42, same millisecond)
    ----   -------------------------------------   -------------------------------------
    t1     BEGIN;
           INSERT INTO records ... ON CONFLICT DO NOTHING RETURNING id;
           (acquires row/index lock on 'msg-42')
    t2                                             BEGIN;
                                                   INSERT INTO records ... ON CONFLICT DO NOTHING RETURNING id;
                                                   (sees uncommitted 'msg-42' -> WAITS on Thread A's lock)
    t3     INSERT INTO outbox ...;
           COMMIT; (releases lock)
    t4                                             (wakes up: sees Thread A committed!)
                                                   ON CONFLICT DO NOTHING fires -> returns 0 rows
                                                   SELECT id, content_hash ... -> verifies payload, returns ("duplicate", id)
                                                   COMMIT;
    

    And if Thread A had crashed and rolled back at t3 instead of committing, Thread B would wake up at t4, see the lock released with no committed row, and proceed to insert both records and outbox itself! Neither thread can ever double-insert or drop the event.

    import hashlib
    import json
    
    INSERT_RECORD_SQL = """
        INSERT INTO records (message_id, order_id, amount, version, content_hash)
        VALUES (%(message_id)s, %(order_id)s, %(amount)s, %(version)s, %(content_hash)s)
        ON CONFLICT (message_id) DO NOTHING
        RETURNING id
    """
    
    SELECT_EXISTING_SQL = """
        SELECT id, content_hash
        FROM records
        WHERE message_id = %(message_id)s
    """
    
    INSERT_OUTBOX_SQL = """
        INSERT INTO outbox (event_id, aggregate_id, payload)
        VALUES (%(message_id)s, %(order_id)s, %(payload)s)
    """
    
    
    class PayloadMismatch(Exception):
        """Raised when two messages share a message_id but carry different business data."""
    
    
    def handle(conn, message: dict) -> tuple[str, int]:
        """Atomically apply message at most once (requires READ COMMITTED isolation)."""
        # Canonicalize only immutable business fields so a new send_timestamp does not change the hash.
        canonical_payload = json.dumps(
            {
                "order_id": message["order_id"],
                "amount": message["amount"],
                "version": message["version"],
            },
            sort_keys=True,
        )
        params = {
            "message_id": message["message_id"],
            "order_id": message["order_id"],
            "amount": message["amount"],
            "version": message["version"],
            "payload": canonical_payload,
            "content_hash": hashlib.sha256(canonical_payload.encode("utf-8")).hexdigest(),
        }
    
        with conn.transaction():
            inserted = conn.execute(INSERT_RECORD_SQL, params).fetchone()
            if inserted is not None:
                # We won the atomic claim: schedule downstream + DB2 sync in the same commit.
                record_id = inserted[0]
                conn.execute(INSERT_OUTBOX_SQL, params)
                return ("applied", record_id)
    
            # Another thread already committed this message_id; verify its payload matches.
            existing = conn.execute(SELECT_EXISTING_SQL, params).fetchone()
            if existing is not None and existing[1] != params["content_hash"]:
                raise PayloadMismatch(f"Conflicting payload for message_id={message['message_id']}")
            existing_id = existing[0] if existing is not None else -1
            return ("duplicate", existing_id)
    

    (Note on isolation levels: keep this transaction at READ COMMITTED. Under REPEATABLE READ, SELECT_EXISTING_SQL would reuse a snapshot taken before Thread A committed and return None. On MySQL/InnoDB, perform a plain INSERT, catch duplicate-key error 1062, and treat it as "duplicate".)

    What partition-key routing solves—and where it falls short: Keying Kafka by order_id and routing inside the consumer with hash(order_id) % 8 ensures that in steady state, events for one order run sequentially on one thread with zero lock contention. However, routing alone cannot prevent zombie overlap during rebalances, crash replays, or duplicate producer sends—so key routing optimizes ordering and lock contention, while the UNIQUE constraint enforces correctness.

  7. Deep dive 2: conflict semantics, watermark offset commits, and mid-flight crashes

    Returning stored state vs. raising a conflict exception

    When Thread B discovers the row already exists, the business goal ("ensure msg-42 is recorded") has succeeded, not failed. Comparing the two designs:

    • Returning existing data / ("duplicate", record_id) (preferred): the caller treats "duplicate" as a normal completion, increments a dedup_hits metric, can pass record_id to any idempotent recovery check, and marks the Kafka offset finished.
    • Throwing DuplicateKeyException: functionally equivalent only if caught immediately inside the worker and mapped to completion. If that exception escapes to a generic retry wrapper, the consumer stalls:
      1. If uncaught in the poll/worker loop, the consumer crashes, restarts at the last committed offset, hits the same duplicate row, and enters an infinite crash loop—the partition offset stops advancing completely.
      2. If caught by a naive retry-then-DLQ middleware, it wastes retries and dumps a successful message into the dead-letter queue.

    Committing offsets safely when workers finish out of order

    With 8 worker threads, fast messages can finish ahead of earlier, slower messages in the same partition:

    Partition 3 offsets:   [ 100 ]   [ 101 ]   [ 102 ]   [ 103 ]   [ 104 ]
    Worker status:          DONE     RUNNING    DONE      DONE     RUNNING
                                        ^
                          Safe commit watermark = 101 (NOT 104!)
    

    In Kafka, committing offset X tells the broker "everything < X is finished." If we committed 104 because 103 finished, and the server crashed a millisecond later, offset 101 would never be redelivered and would be lost forever. Instead, we commit the lowest unfinished offset (101 above). If we crash now, 101, 102, 103, and 104 replay; 102 and 103 hit our UNIQUE index and safely no-op as "duplicate".

    import threading
    import time
    
    
    class OffsetTracker:
        """Tracks contiguous completed offsets per partition across out-of-order workers."""
    
        def __init__(self):
            self._lock = threading.Lock()
            # partition -> assignment epoch (increments on rebalance to ignore stale workers)
            self._epoch: dict[int, int] = {}
            # partition -> set of offsets handed to workers that have not finished yet
            self._in_flight: dict[int, set[int]] = {}
            # partition -> 1 + highest offset handed out in the current epoch
            self._next_offset: dict[int, int] = {}
    
        def assign(self, partition: int, epoch: int) -> None:
            with self._lock:
                self._epoch[partition] = epoch
                self._in_flight[partition] = set()
                self._next_offset.pop(partition, None)
    
        def dispatched(self, partition: int, epoch: int, offset: int) -> None:
            """Called on the single poll thread BEFORE submitting the record to a worker."""
            with self._lock:
                if self._epoch.get(partition) != epoch:
                    return
                self._in_flight[partition].add(offset)
                prev_next = self._next_offset.get(partition, 0)
                self._next_offset[partition] = max(prev_next, offset + 1)
    
        def finished(self, partition: int, epoch: int, offset: int) -> None:
            """Called by worker threads for every final outcome (applied, duplicate, or DLQ)."""
            with self._lock:
                # Ignore late completions from a partition epoch that was already revoked.
                if self._epoch.get(partition) != epoch:
                    return
                self._in_flight[partition].discard(offset)
    
        def safe_to_commit(self) -> dict[int, int]:
            """Return {partition: first_unfinished_offset} ready for Kafka commitSync/Async."""
            with self._lock:
                committable = {}
                for partition, pending in self._in_flight.items():
                    if pending:
                        committable[partition] = min(pending)
                    elif partition in self._next_offset:
                        committable[partition] = self._next_offset[partition]
                return committable
    
        def revoke(self, partition: int) -> None:
            with self._lock:
                self._epoch.pop(partition, None)
                self._in_flight.pop(partition, None)
                self._next_offset.pop(partition, None)
    
    
    def process_one(record, epoch: int, db_pool, tracker: OffsetTracker, dlq_producer, TransientDBError: type) -> None:
        """Worker entry point: retries transient DB outages; marks final outcomes finished."""
        backoff_s = 0.1
        while True:
            try:
                message = json.loads(record.value)
                with db_pool.connection() as conn:
                    # Both ("applied", id) and ("duplicate", id) mean DB1 + outbox are durable.
                    handle(conn, message)
                break
            except (ValueError, KeyError, PayloadMismatch):
                # Poison message: retrying will never fix bad JSON or mismatched payload.
                dlq_producer.send(record)
                break
            except TransientDBError:
                # DB1 temporarily unreachable: do NOT advance offset or flood DLQ; retry with backoff.
                time.sleep(backoff_s)
                backoff_s = min(backoff_s * 2.0, 30.0)
    
        tracker.finished(record.partition, epoch, record.offset)
    

    Recovering if an earlier worker crashed mid-pipeline

    What if Thread 1 inserted into records and crashed before triggering downstream workflows? If a redelivery saw the records row, returned "duplicate", and stopped, downstream workflows would never run! Two patterns eliminate that mid-flight gap:

    1. Transactional outbox handoff (preferred, shown in handle above): downstream workflows consume from the outbox stream rather than being invoked in memory after COMMIT. Because records and outbox commit together in one DB1 transaction, there is no mid-flight gap—either both exist or neither exists.
    2. Two-phase status column + sweeper (when downstream is a synchronous external RPC): insert records with status = 'RECORDED', call the idempotent downstream RPC passing record_id / message_id, and then UPDATE records SET status = 'DONE'. When a duplicate arrives, returning the existing row lets the worker check row.status: if it is still 'RECORDED', the worker re-runs the downstream RPC! A background sweeper also scans WHERE status = 'RECORDED' AND created_at < now() - interval '2 minutes' so stuck work recovers even if Kafka never redelivers the message.
  8. Deep dive 3: asynchronous replication to DB2

    Why sequential writes across two systems diverge on partial failure

    Writing to DB1 and publishing to Kafka (or writing directly to DB2) as two separate network calls has no safe ordering:

    Attempted sequence                      Failure point                     Broken state left behind
    --------------------------------------  --------------------------------  ---------------------------------------
    1. Commit DB1 -> 2. Publish to Kafka    Broker timeout or crash before 2  DB1 updated; DB2 misses update forever
    1. Publish to Kafka -> 2. Commit DB1    DB1 constraint/deadlock rollback  DB2 gets phantom update DB1 rolled back
    1. Commit DB1 -> 2. In-memory retries   Process killed or OOM during 2    Same as row 1: DB2 permanently diverges
    

    Coupling DB1 state and outbound events via a transactional outbox

    Because handle() inserts both records and outbox in a single DB1 transaction, the obligation to update DB2 is just as durable as the DB1 record itself. A separate Outbox Relay delivers unpublished outbox rows to orders.db2-sync (key = order_id) at least once:

    • Option A — Change Data Capture (CDC, preferred at scale): a CDC tool (such as Debezium) tails DB1's write-ahead log (WAL)—the append-only transaction log PostgreSQL writes on every commit—and streams new outbox rows into Kafka in exact commit order without running extra SELECT/UPDATE queries on DB1.
    • Option B — Lease-claim polling relay (zero extra infrastructure): a background worker claims a batch of unpublished rows using a short 10-second lease in Transaction 1, publishes to Kafka outside any database transaction (so a slow Kafka broker never holds DB1 locks open!), and sets published_at = now() in Transaction 2:
    -- Step 1 (fast DB tx): claim up to 500 rows for shard k without holding locks during network I/O
    UPDATE outbox
    SET lease_until = now() + interval '10 seconds'
    WHERE id IN (
        SELECT id FROM outbox
        WHERE published_at IS NULL
          AND (lease_until IS NULL OR lease_until < now())
          AND mod(abs(hashtext(aggregate_id)), 4) = :shard_id
        ORDER BY id
        LIMIT 500
        FOR UPDATE SKIP LOCKED
    )
    RETURNING id, event_id, aggregate_id, payload;
    
    -- Step 2 (no DB tx held): publish batch to Kafka topic orders.db2-sync (key = aggregate_id) and await acks.
    -- If publishing fails or times out, do nothing: lease_until expires in 10 s and the next cycle retries!
    
    -- Step 3 (fast DB tx): mark confirmed rows published
    UPDATE outbox SET published_at = now() WHERE id = ANY(:acked_ids);
    

    Notice why we filter on published_at IS NULL rather than WHERE id > last_seen_id: PostgreSQL assigns BIGSERIAL sequence numbers before commit, so Transaction 10 (id = 10) can commit after Transaction 11 (id = 11). Tracking id > 11 would skip id = 10 permanently, whereas published_at IS NULL never misses a late-committing row.

    Making DB2 idempotent and out-of-order tolerant

    Because the relay guarantees at-least-once delivery (if it crashes between Step 2 and Step 3, those rows publish again after the 10-second lease expires), DB2's applier uses a version-guarded upsert (an atomic "insert if missing, else update"):

    INSERT INTO order_view (order_id, amount, version, updated_at)
    VALUES (:order_id, :amount, :version, now())
    ON CONFLICT (order_id) DO UPDATE
    SET amount     = EXCLUDED.amount,
        version    = EXCLUDED.version,
        updated_at = now()
    WHERE order_view.version < EXCLUDED.version;
    
    • Duplicate delivery (version = 3 arrives twice): the second execution sees 3 < 3 is false and updates zero rows.
    • Out-of-order delivery (version = 4 arrives before delayed version = 3): version = 4 writes; when version = 3 arrives later, 4 < 3 is false so stale data never overwrites newer state.
    • (If events carry deltas like "add $10" rather than full state + version, DB2 instead inserts event_id into a db2_applied_events(event_id PRIMARY KEY) table in the same DB2 transaction as the balance increment.)

    When is a distributed transaction (2PC) worth it? Two-phase commit (2PC / XA) coordinates a simultaneous lock-and-commit across DB1 and DB2 so readers never observe lag between them. However, 2PC adds synchronous cross-database round trips on every message, drops availability to the product of both databases' uptimes, holds locks if the coordinator crashes mid-prepare, and cannot span arbitrary NoSQL/search stores cleanly. Because DB2 tolerates a few seconds of lag here, Outbox + idempotent upsert achieves guaranteed convergence with far higher throughput and availability.

  9. Scaling, bottlenecks, and failure handling

    Scaling and bottleneck mitigations

    • DB1 write amplification and B-tree locality: at 20,000 inserts/s, random UUIDv4 values scatter page splits across the message_id B-tree index once it exceeds RAM. Having producers generate time-ordered UUIDv7 identifiers keeps index inserts localized at the right edge of the B-tree.
    • Outbox table bloat: partition outbox by day (e.g., outbox_2026_11_30) and drop daily partitions once COUNT(*) WHERE published_at IS NULL = 0 and retention (e.g., 48 hours) has elapsed—DROP TABLE is instant and avoids PostgreSQL VACUUM overhead.
    • Scaling consumers beyond 32 threads: a single consumer group supports at most 1 instance per partition (32), while our 8-thread in-process worker pool decouples DB connection concurrency (64) from partition count. Over-partition topics up front if 5–10× growth is expected, since adding partitions later changes hash(order_id) % P and temporarily breaks per-order ordering.
    • DB2 catch-up headroom: batch 200–500 upserts per DB2 round trip (UNNEST arrays in SQL) so DB2 sustains >= 15,000–20,000 events/s, ensuring backlogs drain even during peak traffic.

    End-to-end failure matrix

    Failure scenario                              System response & why data stays consistent
    --------------------------------------------  ------------------------------------------------------------------
    Worker crashes after DB1 commit, before       Kafka replays from safe_to_commit(); UNIQUE(message_id) returns
      offset commit                                 ("duplicate", id), outbox row is already safe -> offset advances
    Two threads process same message at once      DB1 unique index blocks second thread until first commits, then
                                                    DO NOTHING returns 0 rows -> single DB1 + outbox write
    Zombie consumer keeps running after rebalance Offset commits from stale generation rejected by Kafka; any zombie
                                                    DB1 writes serialize safely against UNIQUE(message_id)
    DB1 down or network partition                 Workers sleep with exponential backoff; OffsetTracker watermark
                                                    halts; poll loop pauses partitions at 500 in-flight; 0 data lost
    Malformed JSON or PayloadMismatch             Sent to DLQ with alert; offset marked finished so queue moves on
    Publish to orders.db2-sync fails              Outbox row's published_at stays NULL; relay retries automatically
    Relay crashes after Kafka ack, before DB mark Event published twice to orders.db2-sync; DB2 version < EXCLUDED
                                                    guard turns second copy into a harmless no-op
    

    Key alerts: partition consumer lag (in seconds), age of oldest published_at IS NULL outbox row (warn > 30 s, page > 2 min), DLQ message count (> 0), PayloadMismatch count (> 0), and an end-to-end canary heartbeat measuring DB1 -> DB2 replication delay.

  10. Summary of trade-offs

    • Database UNIQUE index vs. app-level check / Redis lock: only a constraint inside DB1 is atomic with the business write and crash-safe; external caches leave crash gaps between marking "done" and committing data.
    • Returning "duplicate" vs. throwing on conflict: treating duplicates as an expected completion prevents accidental retry storms, DLQ pollution, and stalled partition offsets.
    • Watermark offset commits (min(pending)) vs. auto-commit / max-offset commit: watermark tracking slightly increases harmless crash replays in exchange for zero dropped messages across concurrent worker threads.
    • Transactional outbox vs. dual writes vs. 2PC: the outbox prevents split-brain divergence without sacrificing DB1 availability when DB2 or Kafka blips, trading seconds of eventual lag against 2PC's lock contention.
    • CDC WAL tailing vs. lease-polled outbox: CDC eliminates polling queries and preserves strict commit order at the operational cost of running Debezium/Kafka Connect; lease polling needs zero extra infrastructure for moderate throughput.
    • Versioned state events vs. delta events: carrying (state, version) makes DB2 idempotent and reorder-safe with a single WHERE clause, whereas delta events (+5) require an explicit applied_events deduplication table on DB2.

Intuition & how it works

Imagine a busy bank back-office where numbered payment vouchers arrive on a conveyor belt, several clerks work side by side to record vouchers into the main ledger (DB1), and a courier must also copy every recorded payment into a reporting ledger across town (DB2). Occasionally, photocopies of the exact same voucher msg-42 land in two clerks' hands at the exact same millisecond, or a clerk gets interrupted mid-task. Our goal is idempotency—guaranteeing that processing the same voucher once, twice, or ten times produces the exact same result in both ledgers as processing it once.

The obvious design fails at every seam. If two clerks first run SELECT to check whether msg-42 exists and then INSERT, both see "missing" at the same instant and write duplicate records; if the second clerk throws an unhandled error on conflict, the conveyor belt stalls behind msg-42 forever. If clerks mark the conveyor belt's bookmark (consumer offset) at the highest finished voucher number while an earlier, slower voucher is still being processed, a crash permanently skips that unfinished voucher. And if a clerk commits DB1 and then tries to send a network message to DB2 in memory, a server crash between those two steps leaves DB2 out of sync forever.

Here is how our design handles a concrete 4-event trace safely:

  1. Concurrent duplicate arrival (msg-42, version = 3 on Thread A and Thread B): Both threads run INSERT INTO records ... ON CONFLICT (message_id) DO NOTHING RETURNING id inside a DB1 transaction. DB1's unique index lets Thread A grab the lock, insert both the records row and an outbox row ("sync msg-42 to DB2") in one atomic commit, and return "applied". Thread B waits on the index lock until Thread A commits, gets zero rows back, returns "duplicate" (a success, not an error!), and marks its offset finished.
  2. Out-of-order workers on offsets 100, 101, 102: Offset 100 ("applied") and 102 ("duplicate") finish while 101 is still running on another thread. OffsetTracker inspects in-flight offsets {101} and commits min({101}) = 101—never 103—so 101 cannot be lost on a crash.
  3. Crash after DB1 commit: Because the outbox row committed inside the exact same transaction as records, downstream logic and DB2 sync are already durably queued—there is no "stopped halfway" gap.
  4. Duplicate relay delivery to DB2: The Outbox Relay publishes msg-42 (version = 3) twice after a network retry. DB2 runs an upsert (insert-or-update) with WHERE order_view.version < EXCLUDED.version: the first copy writes version = 3, and the second sees 3 < 3 is false and safely does nothing.

Key trade-offs

  • Database UNIQUE constraint vs. Redis SET NX lock. Enforcing deduplication via a UNIQUE (message_id) index inside DB1 makes checking and writing a single atomic step with zero extra infrastructure. A Redis SET NX check is fast, but introduces a split-brain gap: if a worker sets the Redis key and crashes before committing DB1, redeliveries think the message is already done and drop the write permanently.
  • Natural-key column vs. separate deduplication table. Storing message_id UNIQUE directly on the business records table keeps keys forever at ~50 bytes per row with zero cleanup jobs. A separate processed_messages table supports commands that only UPDATE existing rows, but grows to ~121 GB per week at 2,000 msg/s and requires partitioned retention cleanup.
  • Returning "duplicate" vs. throwing an exception. Both preserve data integrity if caught right at the SQL call, but returning "duplicate" (or the existing row) makes completion the default path so an overlooked try/except can never stall partition offsets or dump already-succeeded messages into a dead-letter queue (DLQ) (a side topic for permanently invalid messages).
  • In-process worker pool vs. single-threaded partition loop. A key-routed worker pool (hash(order_id) % 8) decouples database I/O concurrency from partition count while preserving per-order ordering, at the cost of maintaining OffsetTracker so out-of-order completions only commit contiguous prefixes. Single-threaded polling is simpler, but one slow query stalls the whole partition.
  • Transactional outbox vs. dual writes vs. two-phase commit (2PC). Writing an outbox row in the same DB1 commit guarantees DB2 eventually receives every committed change without coupling DB1 uptime to Kafka or DB2. Dual writes lose data on partial crashes, while two-phase commit (2PC)—locking both databases simultaneously until a coordinator tells both to commit—adds heavy latency, blocks on coordinator failures, and is unnecessary when DB2 permits seconds of lag.
  • Change Data Capture (CDC) vs. lease-polled relay. Change Data Capture (CDC) reads DB1's write-ahead log (WAL) (its internal commit log) to publish outbox events in strict commit order with almost zero query load on DB1, trading operational complexity (running Debezium) against a self-contained SQL lease poller.
  • Outbox vs. a second independent consumer group on the input topic. Having DB2 consume orders.events directly avoids the outbox relay, but fails whenever DB1 enriches data, assigns IDs, or rejects invalid business transitions—making DB1's outbox the single authoritative source of truth.

Common mistakes

  • Application-level SELECT followed by INSERT, allowing two concurrent threads to both observe "row not found" and either write duplicates or crash with unhandled unique-key errors.
  • Running INSERT ... ON CONFLICT DO NOTHING followed by SELECT under REPEATABLE READ isolation, where the SELECT reuses the pre-wait transaction snapshot, returns None even though the other thread just committed, and crashes on None[0]. Use READ COMMITTED and guard existing is not None.
  • Using (topic, partition, offset) as the idempotency key, which catches consumer redeliveries of the same Kafka record but misses producer resends that land at a brand-new offset.
  • Assuming keying partitions by order_id prevents all concurrency, forgetting that during a consumer group rebalance (partition handoff), a paused zombie consumer and its replacement briefly process the same partition at the same moment.
  • Committing the highest completed offset (max) instead of the lowest unfinished offset (min(in_flight)), silently losing slower messages still running on other worker threads if the consumer crashes.
  • Enabling automatic timer-based offset commits alongside a worker pool, which commits offsets as soon as poll() hands them to memory—before workers finish writing to DB1.
  • Calling downstream logic in memory after DB1 commits without recording completion state, so a crash right after COMMIT causes redeliveries to stop at "duplicate" and skip downstream execution forever.
  • Polling an outbox table with WHERE id > last_seen_id, which permanently skips rows whose auto-increment ID was allocated earlier by a transaction that committed slightly later. Always poll WHERE published_at IS NULL.
  • Sending messages to the DLQ during a temporary database outage, turning a 2-minute DB1 restart into millions of dead-lettered messages instead of pausing partitions and retrying with backoff.

Follow-up questions

  • Suppose periodic auto-commit is enabled on the Kafka consumer. Under what failure modes can events be permanently dropped versus reprocessed? With Kafka's timer auto-commit (enable.auto.commit=true, default 5-second interval), poll() commits every offset returned by previous poll() calls regardless of what worker threads are doing. If events execute synchronously inside the poll thread before the next poll(), crashes never drop events (unless exceptions are swallowed), though a crash right before the 5-second tick replays up to 5 seconds of already-committed DB1 writes (~6,250 records per instance at 1,250 msg/s peak) as duplicates. With an asynchronous worker pool, however, the poll thread calls poll() again while workers are still writing earlier records—committing offsets that have not hit DB1 yet—so a process crash, OOM kill, or unhandled DB error permanently drops every in-flight event. Disabling auto-commit and committing OffsetTracker.safe_to_commit() eliminates that loss window.
  • What determines the minimum retention window for deduplication keys, and how does the system behave if a delayed retry arrives after key expiration? Deduplication keys must outlive every pathway capable of replaying an event: the Kafka topic's retention period (default 7 days, since an operator could rewind offsets), plus upstream producer/outbox retry windows and manual DLQ replay windows. Keeping message_id UNIQUE directly on the permanent records row retains keys indefinitely and eliminates expiration risk altogether. If a separate deduplication table purges keys after 7 days and a 10-day-old retry arrives, the database treats it as unseen and applies its side effect a second time; to guard against late stragglers, reject or quarantine events whose occurred_at timestamp predates the retention cutoff and enforce monotonic version guards on mutable business rows.
  • Can enabling Kafka's idempotent producer and transactional APIs replace deduplication inside the primary database? Explain why or why not. No. Kafka's idempotent producer (enable.idempotence=true) only deduplicates network-level batch retries within a single producer session using broker sequence numbers; it cannot stop an upstream service from emitting a second record carrying the same business message_id after a restart. Likewise, Kafka transactions provide atomic "consume-transform-produce" strictly inside Kafka—DB1 is an external PostgreSQL store outside Kafka's transaction coordinator. If a worker commits to DB1 and crashes a millisecond before committing the Kafka offset, Kafka will redeliver the record to DB1 on recovery, so DB1 still requires UNIQUE (message_id).
  • If replication to the secondary database falls sixty minutes behind the primary store, what user-facing symptoms appear, and how would you alert on and drain the backlog? Dashboards and read APIs backed by DB2 serve hour-old state—recent orders vanish from search/reporting views, summary totals disagree with DB1, and users may repeat actions assuming they failed. Catch this early with three signals: consumer lag in seconds on orders.db2-sync, age of the oldest published_at IS NULL outbox row, and a synthetic canary heartbeat written to DB1 every 10 seconds whose arrival delay is measured in DB2 (warn at 60 seconds, page at 5 minutes). To recover, isolate the bottleneck (stalled relay, slow DB2 index, or poison payload), scale out batched DB2 appliers (at 10,000 events/s capacity against 2,000/s incoming load, a 60-minute backlog of 7.2M events drains in 900 seconds = 15 minutes), and temporarily serve freshness-critical reads from DB1 or show a staleness banner; if orders.db2-sync retention expired before recovery, seed DB2 from a DB1 snapshot and replay orders.db2-sync from an earlier offset—version-guarded upserts safely turn the overlap into no-ops.

Follow-up questions

Similar questions

More Alibaba interview questions

All 3 Alibaba questions →