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.
Compare two-phase commit (2PC) and the saga pattern as approaches to coordinating a transaction that spans multiple services. Explain how each handles atomicity, availability, and isolation, and describe the kinds of business workflows where sagas are preferred over 2PC (and vice versa).
Sample Answer
Direct answer: 2PC gives you real atomicity and isolation across services at the cost of availability: every participant holds locks and blocks for the whole round-trip, and a coordinator failure can leave things stuck. Sagas give up that atomicity and isolation in exchange for availability: each step commits immediately and independently, and failures are corrected afterward with compensating actions rather than prevented upfront. Sagas are generally preferred for long-running, cross-service business workflows; 2PC (or a consensus-backed variant of it) is preferred when you genuinely need all-or-nothing atomicity over a short, bounded set of operations and can tolerate the availability cost.
Structured elaboration
Atomicity. 2PC is genuinely atomic: either every participant commits or every participant aborts, and no external observer ever sees a partial result, because nothing is applied until every vote is in. A saga is NOT atomic in that sense: each local transaction commits on its own, so a later step failing means the earlier steps' effects are visible until a compensation reverses them. The system passes through real intermediate states.
Isolation. 2PC participants hold locks from PREPARE through the final decision, so concurrent transactions touching the same data are serialized against each other for that whole window. Sagas provide no such isolation: two sagas can interleave their steps, so a saga step might read a state that a concurrent, not-yet-compensated saga has already changed (dirty reads/write-skew-like anomalies at the application level). This is why saga designs often need extra defenses (semantic locks, versioning, or designing steps to be commutative) to avoid anomalies 2PC would have prevented for free.
Availability. 2PC's blocking failure mode (a coordinator crash stranding in-doubt participants holding locks) is a direct availability cost that scales with how long the transaction takes and how many services are involved. Sagas never hold cross-service locks, so a slow or failed step degrades gracefully: earlier steps' work stays visible and gets compensated, rather than the whole system freezing.
When sagas are preferred over 2PC
- Long-running workflows (minutes to days: order fulfillment, travel booking) where holding locks the whole time is operationally unacceptable.
- Workflows that legitimately cross organizational or technology boundaries (different databases, sometimes different companies via APIs) where a shared 2PC coordinator isn't even possible.
- High-throughput systems where the extra round-trip and lock contention of 2PC would be a bottleneck.
- Cases where a business-level "undo" (refund, cancellation, apology) is an acceptable and well-understood outcome, most commerce and booking flows fit this.
When 2PC (or a consensus-backed equivalent) is still preferred
- Short, bounded operations across a small number of participants you fully control (e.g. a coordinator process and its own set of shards), where the blocking window is small and predictable.
- Cases with no sane compensating action, e.g. "send an email" can't be un-sent, so if a step is genuinely irreversible, a saga's whole safety model breaks down for that step and you need either strict ordering (do reversible steps first, irreversible steps last) or real atomicity upfront.
- Financial or regulatory contexts where a visible, even temporary, partial state is unacceptable regardless of eventual correction.
Trade-offs and pitfalls. The most common mistake in an interview answer here is treating this as "sagas are strictly better because they scale," without acknowledging that sagas give up something real: they push the correctness burden from the protocol onto every individual step's compensating-action design, and a badly designed compensation (one that isn't semantically correct, or that assumes an operation is reversible when it isn't) is a much harder bug to catch than a 2PC coordinator crash, because it corrupts business state rather than just blocking.
Describe how you would design retries and backoff for calls to an external service in the middle of a multi-step distributed transaction (for example, a payment gateway call inside a checkout flow). How do you decide what's safe to retry, classify a failure as transient versus permanent, and handle partial progress if the step can't be completed?
Sample Answer
Direct answer: Inside a multi-step distributed transaction, you decide what's safe to retry by checking whether the step is naturally idempotent or has been made so with a key, classify a failure as transient (retry) versus permanent (fail fast and compensate) based on the error signal the external service gives you, and handle partial progress by tracking exactly which sub-steps of that call actually completed so a retry doesn't redo already-finished work.
Structured elaboration
What's safe to retry. A call is safe to retry automatically only if it's idempotent, either naturally (a read, or a write keyed so re-sending it has no additional effect) or made so via an idempotency key the external system honors. A call with no idempotency support and no natural idempotence (e.g. "increment a counter" with no dedup) is NOT safe to retry blindly; retrying it requires first checking whether the original call actually landed (a status lookup) before deciding to resend.
Classifying transient vs permanent errors. Transient: timeouts, connection resets, 5xx responses, explicit rate-limit responses (429) with a Retry-After hint, these represent conditions likely to resolve on their own or with backoff. Permanent: 4xx responses indicating the request itself is invalid or will never succeed as-is (card declined, invalid account, business-rule rejection), retrying these without changing anything just wastes time and, worse, can mask the real failure from whoever needs to act on it. The classification has to be driven by the specific error signal the external service returns, not by a generic "retry everything a few times" policy, since retrying a permanent failure delays the compensating action that should be running instead.
Handling partial progress. A single "step" in a saga sometimes wraps a multi-part external call (e.g. "charge card" might internally involve authorization, then capture). If a timeout happens between the authorization succeeding and the capture completing, a naive retry that just re-calls the whole "charge" operation risks a double-authorization or worse. The step needs to track its own sub-state (e.g. "authorized, capture pending") so a retry resumes from where it actually got to, rather than restarting from scratch, this typically means the step itself needs to expose (or the caller needs to track) more granular state than just "succeeded or failed."
Exponential backoff with jitter. Retries space out with exponentially increasing delay (e.g. 100ms, 200ms, 400ms...) plus random jitter, to avoid many concurrent retries synchronizing and hammering the external service right after it recovers from an outage (a "thundering herd"). A bounded maximum number of attempts (or total elapsed time) caps how long the saga waits before giving up and triggering compensation instead.
Circuit breakers. If a downstream external service is failing consistently (not just one flaky request), a circuit breaker trips after a threshold of recent failures and stops sending requests to it for a cooldown period, failing fast (and triggering compensation sooner) rather than letting every in-flight saga individually retry against a service that's clearly down, and giving the failing service room to recover instead of adding retry load on top of whatever's already wrong.
Worked example. A saga's payment step calls a gateway with idempotency key S-772-payment. First attempt times out (transient, no definitive response). The saga retries with the SAME key after a short backoff; the gateway recognizes the duplicate key and returns the ORIGINAL result (it had actually succeeded server-side the first time), so exactly one charge occurred despite the retry. On a second scenario, the same call returns a definitive 402 card_declined, classified as permanent, no retry is attempted; the saga immediately proceeds to its compensating actions (release the inventory hold, cancel the order) rather than wasting time retrying a charge that will never succeed with the same card.
Trade-offs and pitfalls. Retrying a call that ISN'T actually idempotent, because it "usually works fine," is the most common source of double-charge and double-side-effect bugs in production sagas; the retry policy has to be scoped per-step based on that step's actual idempotency guarantee, not applied uniformly as a blanket policy across the whole saga.
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.
An enterprise needs eventual consistency between service A and service B using events. Design an idempotent event processing and reconciliation strategy that guarantees convergence and supports replays, while preserving ordering where necessary.
Sample Answer
Direct answer: To make eventual consistency between service A and B idempotent and reconciliation-friendly, service A publishes events with a stable event ID (or a monotonic sequence number per entity), service B's consumer deduplicates on that ID before applying any change, and a periodic reconciliation job independently compares A's and B's views to catch and repair anything that slipped through despite the idempotency guarantees.
Structured elaboration
Idempotent event processing on the consumer side. Every event from A carries a stable identifier; B's consumer checks (atomically, alongside applying the event) whether that ID has already been processed, using the same "dedup record plus the actual state change in one transaction" discipline as any idempotent write. This is what makes at-least-once delivery (which any reasonable messaging setup between A and B will actually provide) safe: redelivery is a no-op rather than a duplicate application.
Preserving ordering where necessary. If events for the same entity must be applied in order (e.g. "created" before "updated" before "deleted"), B's consumer needs either a strictly-ordered delivery channel per entity (partition by entity ID) or an explicit sequence number in each event that B checks against the last-applied sequence for that entity, rejecting or buffering an out-of-order arrival rather than applying it prematurely.
Supporting replays. Because B's state can, despite everything, still drift from A's (a bug, an extended outage, a schema-migration mistake), the design should support REPLAYING A's full event history into B from scratch (or from a checkpoint) to rebuild B's view, which requires A to retain (or be able to regenerate) its event history for at least as long as any realistic replay window, and requires B's apply logic to be safe to run repeatedly over the same events (which it already is, by the idempotency design above).
Reconciliation as the safety net, not the primary mechanism. A periodic job independently compares A's and B's data (via checksums, row counts, or a full diff on a schedule appropriate to the data's size and criticality) and either auto-repairs small, well-understood divergences or flags larger ones for human review. This is deliberately a SEPARATE mechanism from the event-driven sync path, its job is to catch failures of that path (a dropped event no retry ever recovered, a bug in the consumer's apply logic), not to be the primary way B stays in sync (that would defeat the point of event-driven propagation in the first place).
Worked example. Service A (an Orders service) publishes OrderUpdated{order_id, sequence, payload} events. Service B (a search index) consumes them, checking (order_id, sequence) against the last sequence it applied for that order, skipping (as an idempotent no-op) any event with a sequence it's already seen or older, and buffering (briefly) any event that arrives out of order, applying it once the gap is filled or timing it out into a "request full replay for this order_id" fallback if the gap doesn't close. Nightly, a reconciliation job compares a sample (or full set, for smaller datasets) of orders between A's source of truth and B's index, flagging any order where B's data doesn't match A's for investigation, this is how the team discovered a bug where B's consumer was silently dropping events during a brief scaling event, well before any customer noticed stale search results.
Trade-offs and pitfalls. Skipping the reconciliation job because "the event pipeline is reliable" is a common and risky shortcut, event-driven consistency mechanisms fail in ways that are often invisible until reconciliation (or a customer complaint) surfaces them, since a missed event usually produces no error, just quietly stale data.
Explain the two-phase commit (2PC) protocol in detail: the coordinator and participant roles, the prepare and commit phases, and how durable logs are used to survive a crash. Enumerate the key failure modes (coordinator crash, participant crash, network partition) and describe the typical participant responses to each.
Sample Answer
Direct answer: Two-phase commit (2PC) is a protocol that lets a coordinator get a set of participants to agree on committing or aborting a single transaction atomically, even though each participant only controls its own local resource. It works in two rounds: first the coordinator asks everyone if they're ready (prepare), then it tells everyone the outcome (commit or abort).
Structured elaboration
Roles. One process is the coordinator (initiates and drives the protocol); the rest are participants (each owns one local resource manager, e.g. a database shard or a service's own datastore).
Phase 1: Prepare. The coordinator sends a PREPARE message to every participant. Each participant does whatever work is needed to be able to commit (validates constraints, acquires locks, writes its intended changes to a durable, not-yet-visible log record) and replies VOTE_YES if it can guarantee it will be able to commit later, or VOTE_NO if it can't. Voting yes is a promise: from that point the participant may not unilaterally abort.
Phase 2: Commit/Abort. If every participant voted yes, the coordinator durably logs "commit" and sends COMMIT to everyone; each participant applies its prepared changes and acknowledges. If any participant voted no (or timed out), the coordinator durably logs "abort" and sends ABORT; participants roll back and release the locks they took in phase 1.
Durable logging. Both the coordinator and each participant write their decision to a durable log before sending the next message. This is what makes the protocol able to survive a crash and resume where it left off, rather than just picking an arbitrary outcome.
Worked example. A transfer needs to debit account A on shard 1 and credit account B on shard 2.
- Coordinator sends
PREPAREto shard 1 and shard 2. - Shard 1 checks A has sufficient balance, takes a row lock on A, writes an intent record ("debit A by $50, pending"), and votes yes. Shard 2 does the analogous check for the credit and votes yes.
- Coordinator sees two yes votes, writes "transaction T commits" to its own durable log, then sends
COMMITto both shards. - Each shard applies its prepared change and releases the lock, then acknowledges. The coordinator can now discard its log record for T.
If shard 2 had instead found a constraint violation and voted no, the coordinator would log "abort" and tell shard 1 to roll back its debit, leaving both accounts unchanged.
sequenceDiagram
participant C as Coordinator
participant P1 as Participant 1
participant P2 as Participant 2
Note over C,P2: Phase 1: Prepare
C->>P1: PREPARE
C->>P2: PREPARE
P1-->>C: VOTE_YES
P2-->>C: VOTE_YES
Note over C: Durably log "commit"
Note over C,P2: Phase 2: Commit
C->>P1: COMMIT
C->>P2: COMMIT
P1-->>C: ACK
P2-->>C: ACK
Note over C: Discard log record
Failure modes and typical mitigations
- Participant crash before voting: the coordinator times out waiting for that vote and aborts the whole transaction (safe: nothing was promised yet).
- Participant crash after voting yes, before receiving the decision: on recovery the participant reads its own log, sees it voted yes but doesn't know the outcome, and must ask the coordinator (or another participant) what was decided. Until it gets an answer it is stuck holding its locks: this is the core "in-doubt" state.
- Coordinator crash after collecting votes but before all participants get the decision: the surviving participants that already voted yes are now blocked indefinitely, holding their locks, because only the coordinator's log has the real decision. In production this is mitigated by making the coordinator itself durable and quickly recoverable (its log survives the crash and a restarted coordinator resumes from it), and sometimes by coordinator replication so a standby can take over without waiting for the original to come back.
- Network partition between coordinator and a participant: looks identical to a crash from the participant's point of view, so the same in-doubt blocking applies until connectivity (or an operator) resolves it.
Unlock Full Question Bank
Get access to all 41 Data Consistency and Distributed Transactions interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.