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:
- 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.
- 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.
- 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
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
Nin this partition is completely handled; if I crash, resume reading atN." - 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:
- 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 amessage_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). - 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.
- 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). - Consistency target for
DB2: Eventual consistency within a few seconds is acceptable, providedDB2always converges toDB1's state and never permanently misses or double-applies an update.
Core system invariants
DB1stores at most one row permessage_id, enforced atomically by the database engine rather than application memory.- Partition offset
Nis committed only after every offset< Nin that partition has reached a final state (applied, deduplicated, or parked in a dead-letter topic). - Updating
DB1and recording the obligation to updateDB2happen inside one atomicDB1transaction. - Applying an event to
DB2multiple times or out of order produces the exact same final row as applying it once in order.
- 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 (
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 minutesTwo design lessons jump right out of this math: - Putting
message_id UNIQUEdirectly on the businessrecordstable costs ~50 bytes per row and avoids managing a separate 121 GB deduplication table. -DB1write throughput (20,000 inserts/s at peak), not Kafka network bandwidth (10 MB/s), is the bottleneck we must protect.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}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 companionprocessed_messages(message_id UUID PRIMARY KEY, created_at TIMESTAMPTZ)table partitioned by day and insert into it inside the exact sameDB1transaction as theUPDATE.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.
Deep dive 1: atomic deduplication under concurrent execution
Sources of duplicate and simultaneous execution
- 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. - 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.msloses its partition to a new instance, but when the paused zombie consumer wakes up, both instances briefly process the exact same message concurrently. - In-process timeout/retry or duplicate dispatch: a worker pool retries a slow task while the first thread is still blocked on I/O.
- 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 writingDB1also fails: if the worker sets the Redis key and crashes before committingDB1, redelivered attempts see the Redis key, skipDB1, and lose the write forever.Combining check and insert into one atomic
DB1statementBy placing
UNIQUE (message_id)onDB1.recordsand running atREAD COMMITTEDisolation (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
t3instead of committing, Thread B would wake up att4, see the lock released with no committed row, and proceed to insert bothrecordsandoutboxitself! 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. UnderREPEATABLE READ,SELECT_EXISTING_SQLwould reuse a snapshot taken before Thread A committed and returnNone. On MySQL/InnoDB, perform a plainINSERT, catch duplicate-key error1062, and treat it as"duplicate".)What partition-key routing solves—and where it falls short: Keying Kafka by
order_idand routing inside the consumer withhash(order_id) % 8ensures 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 theUNIQUEconstraint enforces correctness.- Crash before offset commit: a worker commits to
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-42is 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 adedup_hitsmetric, can passrecord_idto 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:- 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.
- 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
Xtells the broker "everything< Xis finished." If we committed104because103finished, and the server crashed a millisecond later, offset101would never be redelivered and would be lost forever. Instead, we commit the lowest unfinished offset (101above). If we crash now,101,102,103, and104replay;102and103hit ourUNIQUEindex 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
recordsand crashed before triggering downstream workflows? If a redelivery saw therecordsrow, returned"duplicate", and stopped, downstream workflows would never run! Two patterns eliminate that mid-flight gap:- Transactional outbox handoff (preferred, shown in
handleabove): downstream workflows consume from the outbox stream rather than being invoked in memory afterCOMMIT. Becauserecordsandoutboxcommit together in oneDB1transaction, there is no mid-flight gap—either both exist or neither exists. - Two-phase status column + sweeper (when downstream is a synchronous external RPC): insert
recordswithstatus = 'RECORDED', call the idempotent downstream RPC passingrecord_id/message_id, and thenUPDATE records SET status = 'DONE'. When a duplicate arrives, returning the existing row lets the worker checkrow.status: if it is still'RECORDED', the worker re-runs the downstream RPC! A background sweeper also scansWHERE status = 'RECORDED' AND created_at < now() - interval '2 minutes'so stuck work recovers even if Kafka never redelivers the message.
- Returning existing data /
Deep dive 3: asynchronous replication to DB2
Why sequential writes across two systems diverge on partial failure
Writing to
DB1and publishing to Kafka (or writing directly toDB2) 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 divergesCoupling DB1 state and outbound events via a transactional outbox
Because
handle()inserts bothrecordsandoutboxin a singleDB1transaction, the obligation to updateDB2is just as durable as theDB1record itself. A separate Outbox Relay delivers unpublished outbox rows toorders.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 newoutboxrows into Kafka in exact commit order without running extraSELECT/UPDATEqueries onDB1. - 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
DB1locks open!), and setspublished_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 NULLrather thanWHERE id > last_seen_id: PostgreSQL assignsBIGSERIALsequence numbers before commit, so Transaction 10 (id = 10) can commit after Transaction 11 (id = 11). Trackingid > 11would skipid = 10permanently, whereaspublished_at IS NULLnever misses a late-committing row.Making
DB2idempotent and out-of-order tolerantBecause 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 = 3arrives twice): the second execution sees3 < 3is false and updates zero rows. - Out-of-order delivery (
version = 4arrives before delayedversion = 3):version = 4writes; whenversion = 3arrives later,4 < 3is false so stale data never overwrites newer state. - (If events carry deltas like
"add $10"rather than full state + version,DB2instead insertsevent_idinto adb2_applied_events(event_id PRIMARY KEY)table in the sameDB2transaction as the balance increment.)
When is a distributed transaction (2PC) worth it? Two-phase commit (2PC / XA) coordinates a simultaneous lock-and-commit across
DB1andDB2so 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. BecauseDB2tolerates a few seconds of lag here, Outbox + idempotent upsert achieves guaranteed convergence with far higher throughput and availability.- Option A — Change Data Capture (CDC, preferred at scale): a CDC tool (such as Debezium) tails
Scaling, bottlenecks, and failure handling
Scaling and bottleneck mitigations
DB1write amplification and B-tree locality: at 20,000 inserts/s, random UUIDv4 values scatter page splits across themessage_idB-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
outboxby day (e.g.,outbox_2026_11_30) and drop daily partitions onceCOUNT(*) WHERE published_at IS NULL = 0and retention (e.g., 48 hours) has elapsed—DROP TABLEis instant and avoids PostgreSQLVACUUMoverhead. - 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) % Pand temporarily breaks per-order ordering. DB2catch-up headroom: batch 200–500 upserts perDB2round trip (UNNESTarrays in SQL) soDB2sustains >= 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-opKey alerts: partition consumer lag (in seconds), age of oldest
published_at IS NULLoutbox row (warn > 30 s, page > 2 min), DLQ message count (> 0),PayloadMismatchcount (> 0), and an end-to-end canary heartbeat measuringDB1 -> DB2replication delay.Summary of trade-offs
- Database
UNIQUEindex vs. app-level check / Redis lock: only a constraint insideDB1is 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
DB1availability whenDB2or 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)makesDB2idempotent and reorder-safe with a singleWHEREclause, whereas delta events (+5) require an explicitapplied_eventsdeduplication table onDB2.
- Database
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:
- Concurrent duplicate arrival (
msg-42,version = 3on Thread A and Thread B): Both threads runINSERT INTO records ... ON CONFLICT (message_id) DO NOTHING RETURNING idinside aDB1transaction.DB1's unique index lets Thread A grab the lock, insert both therecordsrow and anoutboxrow ("syncmsg-42toDB2") 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. - Out-of-order workers on offsets
100, 101, 102: Offset100("applied") and102("duplicate") finish while101is still running on another thread.OffsetTrackerinspects in-flight offsets{101}and commitsmin({101}) = 101—never103—so101cannot be lost on a crash. - Crash after
DB1commit: Because theoutboxrow committed inside the exact same transaction asrecords, downstream logic andDB2sync are already durably queued—there is no "stopped halfway" gap. - Duplicate relay delivery to
DB2: The Outbox Relay publishesmsg-42(version = 3) twice after a network retry.DB2runs an upsert (insert-or-update) withWHERE order_view.version < EXCLUDED.version: the first copy writesversion = 3, and the second sees3 < 3is false and safely does nothing.
Key trade-offs
- Database
UNIQUEconstraint vs. RedisSET NXlock. Enforcing deduplication via aUNIQUE (message_id)index insideDB1makes checking and writing a single atomic step with zero extra infrastructure. A RedisSET NXcheck is fast, but introduces a split-brain gap: if a worker sets the Redis key and crashes before committingDB1, redeliveries think the message is already done and drop the write permanently. - Natural-key column vs. separate deduplication table. Storing
message_id UNIQUEdirectly on the businessrecordstable keeps keys forever at ~50 bytes per row with zero cleanup jobs. A separateprocessed_messagestable supports commands that onlyUPDATEexisting 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 overlookedtry/exceptcan 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 maintainingOffsetTrackerso 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
outboxrow in the sameDB1commit guaranteesDB2eventually receives every committed change without couplingDB1uptime to Kafka orDB2. 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 whenDB2permits 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 onDB1, trading operational complexity (running Debezium) against a self-contained SQL lease poller. - Outbox vs. a second independent consumer group on the input topic. Having
DB2consumeorders.eventsdirectly avoids the outbox relay, but fails wheneverDB1enriches data, assigns IDs, or rejects invalid business transitions—makingDB1's outbox the single authoritative source of truth.
Common mistakes
- Application-level
SELECTfollowed byINSERT, 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 NOTHINGfollowed bySELECTunderREPEATABLE READisolation, where theSELECTreuses the pre-wait transaction snapshot, returnsNoneeven though the other thread just committed, and crashes onNone[0]. UseREAD COMMITTEDand guardexisting 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_idprevents 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 toDB1. - Calling downstream logic in memory after
DB1commits without recording completion state, so a crash right afterCOMMITcauses 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 pollWHERE published_at IS NULL. - Sending messages to the DLQ during a temporary database outage, turning a 2-minute
DB1restart 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 previouspoll()calls regardless of what worker threads are doing. If events execute synchronously inside the poll thread before the nextpoll(), crashes never drop events (unless exceptions are swallowed), though a crash right before the 5-second tick replays up to 5 seconds of already-committedDB1writes (~6,250 records per instance at 1,250 msg/s peak) as duplicates. With an asynchronous worker pool, however, the poll thread callspoll()again while workers are still writing earlier records—committing offsets that have not hitDB1yet—so a process crash, OOM kill, or unhandled DB error permanently drops every in-flight event. Disabling auto-commit and committingOffsetTracker.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 UNIQUEdirectly on the permanentrecordsrow 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 whoseoccurred_attimestamp predates the retention cutoff and enforce monotonicversionguards 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 businessmessage_idafter a restart. Likewise, Kafka transactions provide atomic "consume-transform-produce" strictly inside Kafka—DB1is an external PostgreSQL store outside Kafka's transaction coordinator. If a worker commits toDB1and crashes a millisecond before committing the Kafka offset, Kafka will redeliver the record toDB1on recovery, soDB1still requiresUNIQUE (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
DB2serve hour-old state—recent orders vanish from search/reporting views, summary totals disagree withDB1, and users may repeat actions assuming they failed. Catch this early with three signals: consumer lag in seconds onorders.db2-sync, age of the oldestpublished_at IS NULLoutbox row, and a synthetic canary heartbeat written toDB1every 10 seconds whose arrival delay is measured inDB2(warn at 60 seconds, page at 5 minutes). To recover, isolate the bottleneck (stalled relay, slowDB2index, or poison payload), scale out batchedDB2appliers (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 fromDB1or show a staleness banner; iforders.db2-syncretention expired before recovery, seedDB2from aDB1snapshot and replayorders.db2-syncfrom an earlier offset—version-guarded upserts safely turn the overlap into no-ops.
Follow-up questions
- Suppose periodic auto-commit is enabled on the Kafka consumer. Under what failure modes can events be permanently dropped versus reprocessed?
- What determines the minimum retention window for deduplication keys, and how does the system behave if a delayed retry arrives after key expiration?
- Can enabling Kafka's idempotent producer and transactional APIs replace deduplication inside the primary database? Explain why or why not.
- 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?
Similar questions
- Justifying Team Scope, Staffing Size, and Hidden System Complexity
- LFU Cache Simulation with Recency Tie-Breaking
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform
- Prior Authorization Status Engine, Clinical Worklists, and Digests