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.
Design a saga orchestration for a multi-service order workflow (for example: Orders, Payments, Inventory, Shipping). Specify the normal-step flow and the compensating actions for failures, how you ensure idempotency of each step, how the orchestrator persists saga state and recovers from crashes, and the retry/backoff strategy.
Sample Answer
Direct answer: For an order workflow spanning Orders, Payments, Inventory, and Shipping, I'd use an orchestrated saga: a dedicated orchestrator process calls each service in sequence, persists the saga's progress after every step so it can resume after a crash, and drives a reverse-order compensation sequence if any step fails, with every step (forward and compensating) designed to be safely retryable.
Structured elaboration
Normal-step flow.
- Create order (Orders service, local transaction, status = "pending").
- Reserve inventory (Inventory service; a reservation, not a final decrement, so it's cleanly reversible).
- Charge payment (Payments service).
- Confirm the reservation into a real decrement and mark shipping as "ready to ship" (Inventory + Shipping).
- Mark order "confirmed" (Orders service).
Compensating actions, defined per step, triggered in reverse order from wherever the failure occurred:
- Shipping not yet started at failure time: nothing to compensate there.
- Payment charged but inventory confirmation failed: refund the payment.
- Inventory reserved but payment failed: release the reservation.
- Order created but nothing else succeeded: cancel the order.
Persisting saga state. The orchestrator writes the saga's current step and status to its own durable store BEFORE calling the next service, keyed by a saga ID. On crash, the orchestrator (or a fresh instance) reads any saga rows that are "in progress" and resumes from the last recorded step, either continuing forward or, if the failure happened mid-flight, running the compensation sequence from wherever it got to. This state machine is exactly what lets the orchestrator be restarted safely without losing track of a saga.
Idempotency. Every call the orchestrator makes (both forward steps and compensations) is made with an idempotency key derived from (saga_id, step_name), so a retried call after a timeout doesn't double-charge, double-reserve, or double-refund. This matters especially on resume after a crash: the orchestrator can't always be sure whether its last call before the crash actually landed, so it must retry safely rather than skip or assume.
Retry/backoff strategy. Transient failures (timeouts, 5xx responses) get retried with exponential backoff and a bounded number of attempts before the step is treated as a hard failure that triggers compensation; a definitive rejection (e.g. payment declined, out of stock) triggers compensation immediately without retrying.
Worked example. Saga S-4471 reaches step 3 (charge payment), the orchestrator logs S-4471: step=payment, status=in_progress before calling Payments, then crashes before receiving the response. On restart, it reads that row, sees payment is in_progress, and re-issues the charge call with the SAME idempotency key it would have used originally; Payments either applies it for the first time or recognizes the duplicate key and returns the already-applied result, either way, exactly one charge happens. If Payments instead returns "declined," the orchestrator logs the failure and runs the reverse sequence: release the inventory reservation, cancel the order.
Trade-offs and pitfalls. The most common bug in this pattern is persisting saga state AFTER the service call instead of before, if the orchestrator crashes between calling a service and recording that it did, resuming can't tell whether the call landed and is forced to guess, which is exactly the ambiguity idempotency keys exist to make safe to retry through rather than avoid.
An application needs strongly consistent (linearizable) behavior for some operations and can tolerate eventual consistency for others within the same system. How would you design the APIs and data partitioning so clients can choose the right consistency level per operation, without causing data corruption or excessive complexity?
Sample Answer
Direct answer: To let clients choose consistency per operation, expose it explicitly in the API and data model, rather than baking one global choice into the whole service, tag each operation with its required consistency level, route strongly-consistent (linearizable) operations to a synchronously-coordinated path (a single-partition-owner or quorum write/read) and eventually-consistent ones to the cheaper, asynchronously-replicated path, and partition the underlying data so an operation's consistency need maps cleanly onto how it's stored and served.
Structured elaboration
API-level exposure. Rather than a single, undifferentiated GET/PUT, the API distinguishes operations by their consistency requirement, either through distinct endpoints (POST /orders/{id}/finalize implies strong consistency by its nature; GET /orders/{id}/status for casual polling can be served eventually-consistent) or an explicit parameter/header the client sets (Consistency: strong vs Consistency: eventual) for operations that could reasonably go either way depending on context.
Data partitioning to avoid corruption. The risk in mixing consistency levels isn't the READS, it's making sure a strongly-consistent WRITE and an eventually-consistent read of the SAME underlying data can't produce a genuinely corrupted result (as opposed to merely stale). The design partitions data so the strongly-consistent operations own a clear, authoritative write path (e.g. a single-partition-owner model, or a quorum write), and eventually-consistent reads are explicitly understood (by the client, via the API contract) to be a possibly-stale VIEW of that same authoritative data, not a second, independently-writable copy that could diverge and cause real corruption, only staleness, which is a fundamentally safer failure mode.
Routing. An internal routing layer directs strongly-consistent operations to the path that can actually provide that guarantee (a leader-only read/write, or a quorum-coordinated one), and eventually-consistent operations to a cheaper path (a local replica read, or an asynchronously-applied write), the client's declared consistency need drives which internal path handles the request, invisible to the client beyond the contract it opted into.
Versioning for compatibility. As the API evolves (e.g. adding a new consistency tier, like "bounded staleness" between full strong and full eventual), the consistency parameter/header needs its own versioning discipline so existing clients that only understand "strong" or "eventual" don't silently misinterpret a new tier as one they already know, an explicit, documented default (usually the SAFER, strongly-consistent option) for any client that doesn't specify a consistency preference at all avoids a client silently getting weaker guarantees than the service's default behavior.
Developer ergonomics. From the calling developer's point of view, the choice should be a simple, well-documented parameter or endpoint choice with clear guidance ("use finalize-order for anything that commits money or inventory; use order-status for a polling UI"), not a deep understanding of the underlying replication architecture, most application developers calling this API shouldn't need to reason about quorums or replication lag directly, the API's job is to translate their INTENT (I need this to be authoritative vs I'm fine with a quick, possibly-slightly-stale view) into the right internal behavior.
Worked example. finalize-order requires the caller to have already read a strongly-consistent inventory count (via a preceding strongly-consistent read the API forces as part of the flow) and commits atomically against the authoritative partition-owner, guaranteed no double-finalization even under concurrent requests. view-order-status (used by a status-polling UI) reads from the nearest, possibly-slightly-stale replica, fast and cheap, with an explicit as_of timestamp in the response so the UI can show "last updated Xs ago" rather than presenting the data as unconditionally current.
Trade-offs and pitfalls. The riskiest design mistake here is letting an EVENTUALLY-consistent read feed directly into a decision that then gets written WITHOUT going through the strongly-consistent write path's own validation, e.g. a client reading a stale "available" status and then calling finalize-order assuming that stale read is still accurate; the finalize operation itself must independently re-verify against the strongly-consistent source at write time, never trust a client-supplied eventually-consistent read as sufficient justification for a strongly-consistent action.
Design a collaborative real-time document editing service and choose a conflict-resolution strategy. Compare Operational Transformation (OT) and CRDT-based approaches on convergence guarantees, metadata growth, undo/redo complexity, latency of local edits, and support for offline editing at scale, and justify your choice.
Sample Answer
Direct answer: For a collaborative real-time document editor, I'd lean toward a CRDT-based approach over Operational Transformation for most new systems: CRDTs converge correctly with a simpler, more composable merge model and support offline/peer-to-peer editing naturally, while OT requires a central transformation server and more intricate correctness proofs, but OT has a longer production track record and can be more metadata-efficient for simple linear text.
Structured elaboration
Convergence guarantees. Both approaches aim for the same end goal, all replicas converge to the same document state despite concurrent edits, but they get there differently. CRDTs achieve this through mathematically provable merge properties (commutativity, associativity, idempotence) baked into the data structure itself; OT achieves it by transforming each incoming operation against every concurrently-applied operation it wasn't aware of, correctness depends on the TRANSFORMATION FUNCTIONS being correctly implemented for every pair of operation types, historically a significant source of subtle bugs (Google Wave's OT implementation, for instance, took considerable engineering effort to get right).
Metadata growth. Sequence CRDTs for text (like RGA or Logoot) typically attach a unique, ordered identifier to every character (or character-run), plus tombstones for deleted characters (needed so a concurrent operation referencing a deleted character's position can still be correctly placed), this metadata can significantly exceed the actual document content's size over a long editing history unless actively compacted. OT, by contrast, doesn't need to retain this kind of per-character identity metadata long-term, since transformation happens against a linear operation history rather than persistent structural identifiers, generally lighter-weight for the steady state, though OT servers do need to retain enough recent operation history to transform late-arriving concurrent edits.
Undo/redo complexity. Both are genuinely hard here, but for different reasons. In OT, undo means transforming the undo operation against everything that has happened since the original edit, which is exactly the same transformation-composition machinery already prone to subtle bugs elsewhere in the system. In CRDTs, undo of a specific edit typically means marking that edit's contribution for removal in a way that itself must merge correctly with everyone else's concurrent state, "selective undo" (undo MY edit specifically, not everyone's edits since) is a known hard problem in both models, without a clean, universally agreed-on solution in either.
Latency of local edits. Both support immediate LOCAL application of a user's own edit (optimistic local rendering, before confirmation from anywhere else), that's table stakes for a responsive editor and isn't a meaningful differentiator between the two; the difference shows up in how quickly and cheaply REMOTE edits can be correctly incorporated, CRDTs merge remote state/ops directly; OT typically routes through a central server that serializes and transforms operations, adding a network hop most implementations rely on for correctness.
Offline editing support. This is where CRDTs have a structural advantage: because merges are commutative and don't depend on a central authority to serialize operations, two devices can edit fully offline and merge directly with each other (or via any intermediary) whenever they reconnect, in any order, with the same guaranteed-correct result. Most production OT implementations assume a central server is reachable to transform operations against, making genuinely peer-to-peer, server-optional offline editing harder to support cleanly.
Recommendation and reasoning. A concrete version of this decision: building a Google-Docs-scale collaborative editor where low-latency local editing is the critical requirement and the team has limited SRE staffing to operate additional centralized infrastructure tips the recommendation further toward CRDTs specifically, since a CmRDT design avoids the central transformation server OT would otherwise require the team to build, harden, and keep available. For a NEW system generally, especially one that needs to support offline editing or a less centralized architecture, CRDTs are the stronger default: the correctness story is more composable and easier to reason about incrementally (add a new CRDT type without re-deriving transformation functions against every existing operation type), at the cost of needing active tombstone/metadata management. OT remains a reasonable choice specifically when the system is already centralized (a single authoritative server is a given architectural constraint anyway) and the team has deep existing OT expertise, or needs the tighter metadata footprint of OT for a very large, long-lived, heavily-edited document.
Trade-offs and pitfalls. A common mistake is treating this as purely a technical choice without weighing team expertise, a team with deep OT experience and a centralized architecture already in place may ship a correct OT-based editor faster and with fewer subtle bugs than the SAME team's first attempt at a CRDT-based one, "which is theoretically better" and "which will actually be correct in production, on this team's timeline" are different questions.
Explain the differences between Lamport clocks, vector clocks, and logical timestamps in general. For each, state what it can and cannot detect (ordering versus true concurrency) and walk through a brief example of how it's updated on send and receive events.
Sample Answer
Direct answer: Lamport clocks give you a total ordering consistent with causality (if A happened-before B, A's Lamport timestamp is smaller), but they CAN'T tell you whether two events are truly concurrent, two unrelated events can end up with different Lamport timestamps that make them look ordered even though neither actually caused the other. Vector clocks fix exactly this gap: they can tell you happened-before, happened-after, AND genuinely concurrent, at the cost of a counter per replica instead of a single number.
Structured elaboration
Lamport clocks: mechanism. Each process keeps a single integer counter. On a LOCAL event, increment the counter. On SENDING a message, attach the current counter value. On RECEIVING a message with timestamp T, set the local counter to max(local_counter, T) + 1. This guarantees: if event A causally precedes event B (a happens-before relationship via a chain of local events and messages), then timestamp(A) < timestamp(B). But the CONVERSE isn't guaranteed: timestamp(A) < timestamp(B) does NOT imply A happened before B, they might be completely unrelated events that just happened to get ordered that way by the counter mechanics.
Vector clocks: mechanism. As described for causality tracking, each process keeps a vector of counters, one per process, and comparison (element-wise) tells you happened-before, happened-after, or concurrent, unambiguously. This is strictly more information than a Lamport clock provides.
What each can and cannot detect.
| Can detect happened-before? | Can detect true concurrency? | Metadata overhead | |
|---|---|---|---|
| Lamport clock | Yes (via the ordering property) | No, false ordering can appear between unrelated events | One integer per event |
| Vector clock | Yes | Yes, this is exactly what element-wise incomparability signals | One integer PER PROCESS per event |
| Logical timestamps (general term) | Depends on the specific scheme | Depends on the specific scheme | Depends |
Worked example. Two independent processes P1 and P2 never communicate. P1's local Lamport counter reaches 5 after some local events; P2's, independently, reaches 3. If you now compare timestamp(P1's event) = 5 and timestamp(P2's event) = 3, it LOOKS like P2's event happened before P1's (smaller timestamp), but there's no actual causal relationship at all, they're on completely independent tracks. A vector clock comparing {P1:5, P2:0} against {P1:0, P2:3} correctly identifies these as concurrent (neither vector dominates), the Lamport clock's single integer has no way to express that.
Send/receive update walkthrough (Lamport). P1 has local counter 2 and sends a message; the message carries timestamp 3 (2, then incremented for the send event itself). P2 has local counter 1 when it receives this message; it computes max(1, 3) + 1 = 4 and sets its own counter to 4. Any subsequent event P2 does will carry a timestamp of at least 4, correctly reflecting that it happens after P1's send (which had timestamp 3), preserving the causal ordering property even though P2's OWN prior activity (counter 1) was much lower.
Send/receive update walkthrough (vector clock). Two processes, P1 and P2, start at {P1:0, P2:0}. P1 does a local event, incrementing its own entry: {P1:1, P2:0}, then sends a message carrying that vector. P2, before receiving it, does its own local event, incrementing its own entry: {P1:0, P2:1}. When P2 RECEIVES P1's message, it merges element-wise (max per entry: {P1: max(0,1)=1, P2: max(1,0)=1}) and then increments its own entry for the receive event itself, landing at {P1:1, P2:2}. Comparing P2's pre-receive vector {P1:0, P2:1} against P1's sent vector {P1:1, P2:0} shows neither dominates, correctly flagging P1's local event and P2's local event as concurrent, exactly the distinction a Lamport clock's single integer cannot make (a Lamport clock would just assign each an arbitrary-looking total order with no way to mark them as concurrent).
Trade-offs and pitfalls. Choosing Lamport clocks when you actually NEED to detect true concurrency (e.g. for conflict detection in a replicated data store) is a real design bug, not a simplification, since Lamport clocks will silently impose a false ordering on genuinely conflicting concurrent writes rather than flagging them as needing resolution. Lamport clocks are the right, cheaper choice specifically when all you need is a consistent total order for something like event logging or debugging causality chains, not for detecting write-write conflicts.
You operate a nightly ETL job that sometimes produces duplicate rows because upstream producers retry, and you cannot change the producers. Design a deduplication strategy purely in the warehouse layer. Describe an efficient approach (SQL or merge-based), indexing/partitioning choices, and how you would run this as an incremental job with minimal cost.
Sample Answer
Direct answer
When you cannot touch the producers, deduplication has to happen entirely on read or on write inside the warehouse: either a MERGE/upsert-based incremental load that collapses duplicates as it lands (the standard, lowest-cost approach), or a ROW_NUMBER()-based dedup view/materialization if the target table cannot support native upserts. Partition the target by load date (or the event's own natural time partition) and index/cluster by the dedup key, so both the incremental scan and the dedup window function touch only the relevant partition, not the whole table, keeping cost proportional to nightly volume rather than total historical volume.
Structured elaboration
Why MERGE-based incremental load is the default answer. The nightly job loads only new/changed source data into a staging area, then MERGEs staging into the target table keyed by the natural business key (with a tiebreak on a source timestamp or offset). MERGE's WHEN MATCHED THEN UPDATE / WHEN NOT MATCHED THEN INSERT means a retried-producer duplicate landing in staging simply updates the same target row (harmlessly, to the same or a newer value) rather than creating a second row. This confines the cost of deduplication to the SIZE OF THE NIGHTLY DELTA, not the whole table, since only staging (the new data) participates in the merge's join.
When a native MERGE is not available. Some warehouse engines or table formats support MERGE natively (Snowflake, BigQuery, Postgres via ON CONFLICT, Delta/Iceberg); if the target does not, a ROW_NUMBER() OVER (PARTITION BY dedup_key ORDER BY tiebreak_column DESC) window function, filtered to rn = 1, run against a NEWLY INSERTED, append-only staging table and materialized as the query result, achieves the same effect at read time or via a periodic full-materialization job.
Indexing/partitioning choices. Partition the target table by the record's own natural time dimension (event date, not load date, if they can differ, since a late-arriving record should land in ITS correct historical partition, not today's), so the MERGE's join only scans partitions actually touched by the current batch. Index (or cluster/sort-key, depending on engine) on the dedup key within each partition, so the join's lookup is efficient rather than a full partition scan per key.
Running this as an incremental job with minimal cost. Load only what changed since the last successful run (tracked via a watermark: the max source timestamp or offset processed by the last run, not "everything," which is the actual cost driver most naive nightly-full-reload jobs get wrong). Stage that delta in a small, transient table, MERGE it into the target, and drop the staging table. The MERGE's cost then scales with delta size (a small fraction of total table size for a healthy incremental pipeline), not total table size, which is what makes this affordable to run nightly indefinitely as the table grows.
Worked example
A transactions table has 500 million historical rows, growing by roughly 2 million rows/night, with an upstream retry rate that produces roughly 1.5% duplicate rows in each night's raw delta (30,000 duplicate rows out of 2,030,000 raw rows landing in staging on a typical night):
A naive full-table dedup (running ROW_NUMBER() over the entire 500-million-row table every night) would cost a full-table scan and sort every single night, growing more expensive as the table grows, roughly O(total rows×log(total rows)) for the sort, dominated by total table size regardless of how few duplicates actually exist that night. The incremental MERGE approach instead costs roughly O(Δ×log(Δ)) for staging plus an indexed lookup per row against the target (roughly O(Δ×log(target partition size)) if the partition/index narrows the target side of the join), where Δ≈2,030,000, several orders of magnitude cheaper than touching all 500 million rows, and this cost stays roughly CONSTANT per night as the total table grows, since Δ (nightly volume) does not grow with historical size, only with traffic.
Trade-offs and pitfalls
- Common mistake: re-running a full-table dedup "just to be safe" instead of trusting the incremental MERGE. This defeats the entire cost argument above; if there is a genuine concern about drift (some historical duplicate that predates the incremental approach), run a ONE-TIME full cleanup, then rely on the incremental MERGE going forward, rather than paying the full-table cost every night indefinitely.
- Common mistake: partitioning by load date when the source can deliver late-arriving historical data. A late record for last week's event lands in TODAY's load-date partition under naive load-date partitioning, meaning a query scoped to "last week" misses it; partitioning by the record's own event-time field (with the incremental job able to write into a past partition) avoids this, at the cost of the incremental job potentially touching more than just "today's" partition on a given run.
- The watermark itself needs to be crash-safe. If the "max timestamp processed" watermark is updated before the
MERGEis confirmed committed, a crash between watermark-update and merge-commit can cause the NEXT run to skip data that was never actually merged, the same checkpoint-before-durable-write hazard that shows up in streaming systems too, here applied to a batch ETL context instead. - This design's cost advantage assumes the dedup key has reasonably good selectivity/index behavior. If the warehouse's specific engine does not support an efficient indexed join for the
MERGE(some columnar engines optimize full scans over indexed point lookups), the partition-pruning discipline above matters even more, since partition elimination, not per-row indexing, becomes the main lever for keeping cost proportional to delta size.
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.