Data Consistency and Distributed Transactions Questions
Maintaining correctness of state across services and replicas: eventual consistency, conflict resolution (last-write-wins, CRDTs, vector clocks), the saga pattern, two-phase commit, and idempotency keys for exactly-once effects. Covers when to trade strict consistency for availability and how to reason about read-your-writes and monotonic guarantees. Focuses on the application/service layer rather than storage-engine internals.
Given this naive message handler pseudocode: 'def handle_message(msg): try: db.execute("INSERT INTO processed_messages(id) VALUES (%s)", msg.id) except UniqueViolation: return process_already_done(); process_side_effects(msg)', identify race conditions or failure modes that could still cause duplicate side effects or lost processing. Propose corrected code-level fixes using SQL constraints, explicit transactions, status fields, or the transactional outbox pattern and provide corrected Python/SQL pseudocode.
Sample Answer
Direct answer: The naive handler has a race condition: it inserts into processed_messages and only calls process_side_effects AFTER that insert succeeds, but if the process crashes between the successful insert and the side effect actually completing, a retry of the same message will see the unique-violation, treat the message as already handled, call process_already_done(), and the real side effect may never have completed, silently dropping it. The fix is to make the dedup-record insert and the side effect happen together, atomically, using a status field and (where possible) a single transaction, rather than treating "recorded" and "processed" as the same moment.
Structured elaboration. The naive code's implicit assumption is: if the row exists, the side effect definitely ran. That's false the moment you allow ANY window between the insert and the side effect completing, a crash, a slow side effect, or even just normal concurrent execution can violate it.
# NAIVE (buggy) version, for reference:
# def handle_message(msg):
# try:
# db.execute("INSERT INTO processed_messages(id) VALUES (%s)", msg.id)
# except UniqueViolation:
# return process_already_done()
# process_side_effects(msg) # <-- if this crashes or fails, the row already
# # exists, so a retry thinks it's done. Lost work.
import enum
class Status(enum.Enum):
IN_PROGRESS = "in_progress"
DONE = "done"
def handle_message_fixed(msg, db, process_side_effects):
"""Corrected: the dedup record tracks IN_PROGRESS vs DONE, and the
side effect is only skipped if it actually completed."""
with db.transaction() as tx:
row = tx.execute(
"SELECT status FROM processed_messages WHERE id = %s FOR UPDATE",
(msg.id,),
).fetchone()
if row is None:
tx.execute(
"INSERT INTO processed_messages(id, status) VALUES (%s, %s)",
(msg.id, Status.IN_PROGRESS.value),
)
elif row["status"] == Status.DONE.value:
return "already_done" # genuinely already completed; safe to skip
# else: row exists but status is IN_PROGRESS -- a previous attempt
# started and didn't finish (crashed). We fall through and RETRY the
# side effect rather than skipping it.
# Side effect runs OUTSIDE the row lock (it may be slow / call external
# systems) but the side effect itself must be idempotent, since this
# code path can genuinely run it more than once under concurrent retries.
process_side_effects(msg)
db.execute(
"UPDATE processed_messages SET status = %s WHERE id = %s",
(Status.DONE.value, msg.id),
)
return "processed"
Why this fixes the race. The dedup record now has two states, not one: IN_PROGRESS (a previous attempt started but we don't know if it finished) and DONE (it genuinely completed). A retry that finds IN_PROGRESS re-attempts the side effect instead of assuming it's done, closing the exact gap the naive version left open. process_side_effects must still be written idempotently (e.g. using its own external idempotency key if it calls a third-party API), because this fix can genuinely invoke it twice under concurrent retries, it converts "silently skip real work" (data loss) into "possibly redo safe, idempotent work" (which is the correct trade to make).
Transactionally-safe alternative: outbox pattern. If the side effect IS itself a database write (not an external call), the cleanest fix is to make it part of the SAME transaction as the dedup insert (a single atomic unit, no window at all), or to route the side effect through a transactional outbox: write the dedup row and an outbox event in one transaction, and let a separate relay perform the actual external call, which by design already handles the "did it actually go out" ambiguity via at-least-once delivery plus consumer-side idempotency.
Trade-offs and pitfalls. The SELECT ... FOR UPDATE introduces row-level lock contention if the same msg.id is retried concurrently from multiple workers, acceptable for most workloads since duplicate message IDs are rare in the retry case, but worth flagging as a scalability consideration for very high-duplicate-rate workloads.
Implement (or sketch) a simplified transactional outbox poller in Python pseudocode that: 1) runs as a separate process, 2) reads pending outbox rows atomically, 3) publishes messages to Kafka, and 4) marks rows as published in a durable way. Include error handling for partial publishes, retries, idempotency considerations, and how the poller coordinates with application transactions.
Sample Answer
Direct answer: A transactional outbox poller is a standalone process that periodically reads unpublished rows from the outbox table, publishes each to the message broker, and marks it published only after a successful publish, with enough error handling to guarantee at-least-once delivery even across its own crashes.
Structured elaboration. The poller's own loop must tolerate crashing at any point without losing or silently dropping a row: it reads a batch of unpublished rows, attempts to publish each, and only marks a row published after the broker confirms receipt. If the process dies mid-batch, the unmarked rows are simply picked up again on the next poll, that's the at-least-once guarantee, and it's why downstream consumers must dedupe.
import time
import logging
logger = logging.getLogger("outbox_poller")
class OutboxPoller:
def __init__(self, db, broker, batch_size=100, poll_interval_s=0.5):
self.db = db # exposes fetch_unpublished(limit) / mark_published(ids)
self.broker = broker # exposes publish(topic, key, payload) -> raises on failure
self.batch_size = batch_size
self.poll_interval_s = poll_interval_s
def run_forever(self):
while True:
self.poll_once()
time.sleep(self.poll_interval_s)
def poll_once(self):
rows = self.db.fetch_unpublished(limit=self.batch_size)
if not rows:
return 0
published_ids = []
for row in rows:
try:
self.broker.publish(
topic=row["event_type"],
key=str(row["aggregate_id"]),
payload=row["payload"],
)
published_ids.append(row["id"])
except Exception:
logger.exception("publish failed for outbox row %s; will retry next poll", row["id"])
# Deliberately do NOT mark this row published, and do NOT raise:
# one bad row must not block the rest of the batch, and it will
# be retried on the next poll_once() call.
continue
if published_ids:
# Marking published is itself a single DB write; if THIS crashes after
# some rows were already published to the broker, those rows get
# re-published on the next poll -- at-least-once, by design.
self.db.mark_published(published_ids)
return len(published_ids)
Handling partial publishes. If the process crashes after self.broker.publish(...) succeeds for row 7 in a batch of 10, but before mark_published is called for the batch, all 10 rows (including the 7 already-published ones) remain marked unpublished and get retried on the next poll. This is intentional: re-publishing an already-delivered event is safe PROVIDED consumers dedupe, whereas losing an event silently is not recoverable. The design always fails toward "publish again," never toward "might skip."
Idempotency considerations. The payload carries a stable event identifier (e.g. row["id"] or a domain event ID) so consumers can deduplicate on it; the poller itself doesn't need its own idempotency key beyond the outbox row's primary key, since "publish this row's content" is naturally idempotent from the broker's point of view (publishing twice just means the topic has two identical-content messages, harmless if the consumer dedupes).
How the poller coordinates with application transactions. The poller never participates in the application's write transaction; it only reads rows that a completed, committed transaction has already written. This separation is what makes the pattern simple: the poller doesn't need to know anything about the business logic that created the row, only how to read, publish, and mark.
Trade-offs and pitfalls. A subtle bug is publishing and marking published in a way that ISN'T resilient to a crash between the two, exactly why this code marks a whole successfully-published batch AFTER all its publishes complete, rather than marking each row published immediately after its own publish call inside the loop (which would still be correct here, but tighter batching of the DB write reduces write amplification at the cost of a slightly larger re-publish window on crash, a real trade-off worth naming explicitly rather than picking silently).
Compare last-writer-wins (LWW) conflict resolution against CRDTs for achieving eventual consistency. In what scenarios is LWW acceptable, and when do CRDTs become the better fit? What operational costs does adopting CRDTs add (metadata growth, merge cost)?
Sample Answer
Direct answer: LWW is acceptable for fields where losing one of two concurrent updates silently is a genuinely fine outcome, typically single-valued fields with no natural merge semantic; CRDTs become the better fit once you need EVERY concurrent update's information to survive the merge, at the real cost of extra implementation complexity and ongoing metadata management that LWW doesn't require.
Structured elaboration
Decision criteria. Ask, for the specific field or data type in question: does losing one of two concurrent writes represent real information loss a user or the business would care about? If no (the field is naturally "replace with newest," like a status flag or a cached external value), LWW is the simpler, sufficient choice. If yes (both concurrent writes carry information that should survive, like a counter, a set of tags, or collaborative document content), you need something that can actually MERGE both updates rather than pick one, which is what CRDTs are designed for.
Recommended approach by scenario.
- Collaborative document edits: CRDTs (specifically a sequence CRDT for the text itself), since LWW at any granularity coarser than individual characters would discard entire concurrent edits, exactly the failure this domain can't tolerate.
- Offline mobile updates to a simple status field (e.g. "is this task marked complete"): LWW is often fine here, since a boolean "complete" flag genuinely has a "replace with the latest state" semantic, there's no meaningful way to "merge" two different completion states, one has to win, and losing the earlier one is the intended behavior, not a bug.
- Offline mobile updates to a LIST of items (tags, cart contents): CRDT (OR-Set), for the same reason argued in the shopping-cart example elsewhere in this topic, concurrent additions from different devices need to all survive.
Operational cost of adopting CRDTs. CRDTs require modeling your data as CRDT-compatible types (which sometimes means restructuring a field that was a simple scalar into a CRDT-native shape), implementing or adopting a CRDT library correctly (subtle correctness bugs are easy to introduce, see the CRDT test-strategy discussion elsewhere in this topic), and managing metadata growth over time (tombstones, per-replica vectors) that a plain LWW-timestamped field never accumulates. This is real, ongoing engineering investment, not a one-time setup cost, worth weighing explicitly against the value of not losing concurrent updates for a specific field.
Merge cost comparison. LWW's "merge" is a single timestamp comparison, O(1), trivial. A CRDT merge, depending on type, ranges from cheap (a G-Counter's element-wise max) to more involved (a sequence CRDT's structural merge, which can be non-trivial for large documents with long edit histories), a real performance consideration at scale that LWW simply doesn't have to think about.
Worked example. A team building a multi-device note-taking app initially applied LWW to the WHOLE note object (title + body + tags combined). Users editing the same note from two devices while both were briefly offline (a common case: editing on a phone during a commute, then opening a laptop before the phone had synced) would lose one device's entire set of edits. The team's fix: keep LWW for the title (a single-valued field where "replace with latest" is genuinely fine, and users rarely have GENUINE conflicting title edits from two devices), but move the body to an operational sequence CRDT (needed to make character-level concurrent edits, not just whole-note replacement, actually merge) and tags to an OR-Set. This targeted, per-field decision (rather than a blanket choice either way) resolved the actual complaint (lost body content) without over-engineering the title field, which never needed CRDT machinery.
Trade-offs and pitfalls. Adopting CRDTs uniformly across an entire object "to be safe," rather than deciding per-field based on the criteria above, is a common over-engineering response to a real LWW data-loss incident, it solves the problem but at unnecessary implementation and metadata cost for fields that never needed it.
Design an algorithm to compact vector clocks or CRDT deltas in a long-running distributed system so their metadata doesn't grow unbounded, while preserving eventual convergence. What heuristics would you use, what trade-offs do they introduce in causality precision, and how would you recover or reconcile after a compaction?
Sample Answer
Direct answer: Compacting vector clocks or CRDT deltas without unbounded metadata growth means pruning entries for replicas or clients that haven't contributed recently, snapshotting the current merged state periodically so old deltas can be discarded, or replacing full history-tracking with a bounded summary (like a Merkle-tree digest or a periodic checkpoint) that trades some precision in causality tracking for a hard bound on metadata size.
Structured elaboration
Why unbounded growth happens. A vector clock's size grows with the number of DISTINCT node/client IDs that have ever contributed to a piece of data's history; in a system with many ephemeral clients (mobile devices that connect briefly, short-lived worker processes), that set never shrinks under a naive implementation, every client that ever touched the data leaves a permanent entry. CRDT deltas have an analogous problem: an op-based CRDT that never compacts its operation log, or a state-based CRDT whose metadata (tombstones for deleted elements, per-replica counters) accumulates without bound, grows linearly with total historical activity rather than with current, live state.
Time-based eviction. Prune vector-clock entries (or CRDT tombstones) for a node that hasn't contributed an update within some window (e.g. 90 days), on the reasoning that a node silent for that long is very unlikely to suddenly resurface with an old, unmerged update that still needs precise causal placement. The risk this introduces: if a pruned node DOES resurface with a genuinely old update, the system can no longer precisely place it in causal history relative to everything that happened since, it gets treated more conservatively (e.g. as concurrent with everything, or requiring a full reconciliation pass) rather than correctly ordered.
Snapshotting. Periodically (e.g. daily, or after N operations), compute the fully-merged current state and take that AS the new baseline, discarding the individual deltas/operations that led to it. Anything before the snapshot no longer needs individual per-operation metadata, only the snapshot itself, which is a fixed, bounded size regardless of how much history preceded it. The trade-off: you lose the ability to answer fine-grained "what was the exact sequence of changes" questions for anything before the snapshot, acceptable for most systems where only the CURRENT convergent state matters, not the full audit history.
Hash-based summaries (Merkle trees). Instead of tracking exact causal metadata per key, periodically compute a Merkle tree (or similar hierarchical hash structure) over ranges of keys; comparing two replicas' Merkle trees quickly identifies WHICH ranges differ (via hash mismatch) without needing per-key vector clocks for keys that HAVEN'T diverged, useful for anti-entropy reconciliation at scale, where most keys agree between replicas and only a small subset needs detailed, per-key metadata to resolve.
Trade-off in losing precision. Every one of these techniques trades exact, unbounded-precision causality tracking for a bounded metadata footprint; the shared risk is FALSE CONCURRENCY DETECTION, an update that's actually causally related to something in the pruned/snapshotted history gets treated as if it had no prior context, potentially triggering an unnecessary conflict-resolution step (harmless but wasteful) or, in a worse case, missing a genuine causal ordering the system should have preserved.
Worked example. A collaborative-document CRDT accumulates tombstones for every deleted character over the document's lifetime, after a year of edits, tombstone metadata can dwarf the actual live content. The system snapshots the document's current state (the surviving, non-deleted content) every night, discarding tombstones for anything deleted before the snapshot point (since there's no remaining live content that could still conflict with an already-deleted character from before the snapshot), while keeping fresh tombstones for anything deleted since, to still correctly handle a late-arriving concurrent edit from just before the snapshot.
Recovery and reconciliation after compaction. A replica that reconnects after being offline longer than the retention window (with updates the system can no longer precisely causally place) is handled by falling back to a full state comparison against the current snapshot rather than trying to replay individual deltas, effectively treating it as a fresh join with a reconciliation pass, rather than a normal incremental merge, a graceful but more expensive degraded path reserved for the rare case of a very-late reconnect.
For a high-throughput streaming ETL ingesting user events, what metadata would you record to enable efficient deduplication of events within a time window? Explain how fields such as event_id, user_id, event_time, ingestion_time, and partition offsets are used during processing, and the retention implications of keeping that metadata. Then list the common deduplication approaches available (producer-side dedupe, consumer-side dedupe using state, dedupe tables or upserts, watermark/window compaction) and give one advantage and one drawback of each.
Sample Answer
Direct answer
To deduplicate streaming events efficiently you need a compact key, event_id (or a stable natural key), plus enough context to bound how long you must remember it: event_time (when it happened), ingestion_time (when your pipeline saw it), user_id or another partition key, and the source partition offset (to resume correctly after a restart). The retention window for that metadata should track your event-time watermark, typically bounded by the maximum out-of-order lateness you tolerate, not kept forever. Four dedup approaches exist at different points in the pipeline: producer-side dedupe, consumer-side dedupe using state, dedupe tables or upserts, and watermark/window compaction; each trades off where the work happens and how much state it needs.
Structured elaboration
What each metadata field is for:
event_id: the stable identity of the logical event. This is the dedup key. It must be assigned once, upstream, and preserved through every retry or replay; a UUID generated fresh on each retry defeats the purpose (mirrors the idempotency-key discipline).user_id(or another natural partition key): lets you shard dedup state per key instead of maintaining one global structure, and lets you bound state size per partition rather than globally.event_time: the business timestamp of when the event actually occurred. This is what watermarks and windowing operate on, and what "same time window" means for compaction.ingestion_time: when the pipeline observed the event. Used to detect abnormal ingestion delay and to distinguish "arrived late but is old" from "arrived late and is actually a new, recent event."- Partition offsets (e.g. Kafka partition + offset): the resume point. After a consumer restart, replaying from the last committed offset can redeliver events already processed; offsets let you reason about exactly which range might be duplicated, narrowing what you need to re-check instead of rescanning everything.
Retention implications. Every dedup approach that keeps state (a seen-IDs set, a dedup table, windowed state) must bound that state, or memory/storage grows without limit. The bound is set by the watermark: once you declare "no event older than event_time T will arrive," you can safely forget dedup state for windows entirely older than T. Choosing too short a window lets late duplicates slip through unnoticed; choosing too long a window wastes memory holding state for windows that will never see another duplicate.
Four deduplication approaches:
| Approach | Advantage | Drawback |
|---|---|---|
| Producer-side dedupe (producer assigns a stable ID and the broker/idempotent producer API rejects a resend within its own dedup window) | Cheapest: eliminates the duplicate before it enters the pipeline at all, no downstream state needed | Only covers producer-to-broker retries; a duplicate reintroduced further downstream (a second producer instance, a replay job) is invisible to it |
Consumer-side dedupe using state (the consumer keeps a set or a compacted state store of seen event_ids per key, checked before processing) | Catches duplicates regardless of where upstream they originated; works even if the producer has no dedup guarantee | Consumer must maintain and bound the state (memory or an external store like RocksDB-backed state or Redis); adds a lookup on every event |
Dedupe tables or upserts (write to the sink keyed by event_id, letting an INSERT ... ON CONFLICT or MERGE collapse duplicates at write time) | Correctness lives in the sink, so any number of upstream retries converge to one row; no in-flight dedup state needed | Only works if the sink supports a native keyed upsert; does not prevent redundant processing work before the write, just its effect |
| Watermark/window compaction (buffer events per window, drop or merge repeats of the same key inside the window once the watermark passes, then finalize) | Bounds dedup state to "current watermark window," giving a hard memory ceiling independent of total event volume | Introduces latency (must wait for the watermark before finalizing) and cannot catch a duplicate that arrives after the window has already closed and been forgotten |
Worked example
A user-events stream runs at 20,000 events/sec, and the pipeline tolerates events arriving up to 10 minutes late (the watermark lag). Using consumer-side dedupe with a hash set of event_id keyed per 10-minute window:
At a 36-byte UUID string per event_id (or 16 bytes if stored as a raw UUID, plus hash-set overhead, call it roughly 50 bytes per entry with typical hash-set bookkeeping overhead):
If two windows must be open concurrently (the current one plus a grace-period window for late arrivals), that is roughly 1.1 GiB of dedup state, which is a real, plannable memory budget, not an afterthought. This is exactly why the retention window (the watermark lag, 10 minutes here) is a deliberate engineering choice: doubling it to 20 minutes doubles this number to roughly 2.2 GiB in-flight, while halving it to 5 minutes halves it, at the cost of dropping legitimately late (but real) events as unrecoverable duplicates-of-nothing once the window closes. Consumer-side dedup stores and compacted topics map directly onto this row: a log-compacted topic keyed by event_id is a durable, disk-backed version of the same consumer-side dedup state, trading the in-memory 572 MiB budget above for compaction-cycle latency and broker-side storage, at higher throughput headroom and lower operational risk of losing state on a consumer restart.
Trade-offs and pitfalls
- Layering approaches is normal. Producer-side dedupe removes the cheap, common case (retried sends) before it costs any consumer-side work; consumer-side or sink-side dedupe is still needed as the backstop for the cases producer-side dedupe cannot see (replays, multiple producers, cross-pipeline joins).
- Common mistake: deduplicating on the wrong key. Using a payload hash instead of
event_idtreats two textually-identical-but-distinct real events (e.g., a user clicking the same button twice, one second apart) as duplicates, silently dropping real data. The dedup key must identify the logical event, not just match its content. - Common mistake: forgetting that offsets reset on partition reassignment. If consumer group rebalancing moves a partition to a new consumer instance, dedup state that lived only in that consumer's local memory is lost, and a config that resumes "from committed offset" can redeliver a range the old instance already deduplicated. Externalizing dedup state (a shared store or the sink's own upsert) survives rebalances; purely local in-memory state does not.
- Common mistake: sizing retention from "how long till I forget" instead of "how late can a real duplicate legitimately arrive." The watermark should be derived from measured upstream latency distributions (e.g. P99 producer-to-broker delay), not picked as a round number.
Unlock Full Question Bank
Get access to all Data Consistency and Distributed Transactions interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.