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 comprehensive test strategy to verify the correctness of a CRDT-based collaborative editor at scale. What testing techniques would you use to catch subtle merge bugs and regressions before they reach production?
Sample Answer
Direct answer: Verifying a CRDT-based collaborative editor at scale needs unit tests for individual merge functions' mathematical properties, property-based/fuzz testing that generates random concurrent operation sequences and asserts convergence, model-based tests that check the implementation against a simplified reference model, distributed integration tests with real network conditions, and performance/stress tests specifically targeting metadata growth and merge cost under sustained heavy editing.
Structured elaboration
Unit testing merge properties directly. For each CRDT type used, write targeted tests asserting commutativity (merge(A,B) == merge(B,A) for many generated pairs), associativity (merge(merge(A,B),C) == merge(A,merge(B,C))), and idempotence (merge(A,A) == A), these are the exact properties correctness depends on, and testing them directly, with many randomized inputs, catches a large class of implementation bugs cheaply, before ever running a full distributed scenario.
Property-based / fuzz testing for convergence. Generate random sequences of concurrent operations (from multiple simulated "replicas"), apply them to independent replica instances in different (randomized) orders, and assert that ALL replicas converge to the identical final state regardless of the order or timing of application, this is the CORE property a CRDT promises, and property-based testing (generating many random scenarios rather than a handful of hand-picked ones) is specifically well-suited to catching edge cases a human test-writer wouldn't think to construct by hand.
Model-based tests for convergence. Maintain a simplified REFERENCE implementation (even a naive, centrally-serialized one that's obviously correct but doesn't need to scale) alongside the real distributed CRDT implementation; for the same randomly-generated operation sequence, assert the real implementation's converged result matches the reference model's result, this catches SEMANTIC bugs (the CRDT converges, consistently, to the WRONG answer) that a pure convergence check (all replicas agree with EACH OTHER) wouldn't catch on its own.
Distributed integration tests. Run the actual system across multiple real (or realistically simulated) nodes with injected network conditions, partitions, message delay, reordering, and duplicate delivery, and assert correctness holds under all of them; this is what catches bugs specific to the DELIVERY assumptions a CmRDT (operation-based) implementation makes (e.g. "operations commute given reliable delivery" is only as good as the delivery layer actually being reliable in the implementation, not just in theory).
Performance and stress testing. Specifically target metadata growth (simulate a long editing session with many concurrent edits and measure tombstone/vector-clock growth over time, not just correctness) and merge cost at scale (measure merge latency as document size and edit-history length grow, since a merge function that's correct but becomes prohibitively slow at realistic document sizes is a real production failure even though it never produces a wrong answer).
Detecting subtle merge bugs and regressions. The combination above is deliberately layered: unit tests catch obvious property violations cheaply and fast; fuzz/property-based tests catch edge cases in operation ORDERING and timing that unit tests with fixed inputs would miss; model-based comparison catches SEMANTIC correctness bugs that a pure "do all replicas agree with each other" convergence check would miss (all replicas could converge together on a WRONG answer); distributed integration tests catch bugs specific to REAL network behavior (delay, loss, duplication) that in-process tests can't exercise; and stress tests catch DEGRADATION (still correct, but too slow or too much metadata) that pure correctness tests never look for.
Worked example. A fuzz test generates 50 random concurrent operations (adds, deletes, moves) applied by 4 simulated replicas in randomized delivery order, including deliberately duplicated and delayed deliveries; after full convergence, it asserts (a) all 4 replicas' final document states are byte-identical to each other (convergence), AND (b) that state matches what a simple reference implementation (applying the same LOGICAL edits, but centrally serialized with no concurrency) would produce (semantic correctness). Running this with many different random seeds over a CI pipeline surfaced a bug where a specific interleaving of a delete and a concurrent move of the same element produced a document that converged consistently across replicas but was missing content the reference model retained, a real bug invisible to a convergence-only check.
Trade-offs and pitfalls. Testing ONLY for cross-replica convergence (all replicas agree with each other) without a reference-model comparison is a common testing gap that misses an entire class of bugs, consistent-but-wrong results, which is arguably worse than an obvious crash, since it ships silently.
Design an audit trail for sagas that proves, for any transaction ID, whether the saga completed successfully or was compensated. It must preserve operation ordering and causality, allow efficient queries by transaction ID, minimize storage overhead, and satisfy retention requirements for auditors.
Sample Answer
Direct answer: An audit trail for sagas needs an append-only, transaction-ID-keyed log of every state transition (each step started, completed, or compensated, with a timestamp and enough context to explain why), indexed for efficient lookup by transaction ID, with retention and access controls appropriate for an audit record, and, for regulated contexts, some form of tamper-evidence so the log itself can be trusted.
Structured elaboration
Data model. One append-only table (or event stream) keyed by saga_id, with rows like (saga_id, step_name, event_type, timestamp, actor, details), where event_type is one of started, completed, failed, compensating, compensated. Ordering matters: the rows for a given saga_id, read in timestamp order, ARE the causal history of that transaction; nothing is ever updated or deleted, only appended.
Efficient query by transaction ID. Index on saga_id (and secondarily on timestamp for time-range queries, e.g. "show me all sagas that were compensating between 2 and 3am"). Since the primary access pattern is "show me the full history of transaction X," a saga_id-partitioned or saga_id-indexed store (a relational table with that as a clustered/indexed key, or an event store partitioned by saga ID) keeps that lookup cheap even at high volume.
Minimizing storage overhead. Audit rows are typically small (a handful of fields), so overhead mostly comes from volume over time; older, fully-resolved sagas can be moved to cheaper cold storage (still queryable, just not on the hot path) once they're past the age where operators need fast access, while retention policy (how long records must be kept) is driven by whatever regulatory or business requirement applies, not by storage cost alone.
Replay, rollback, and diagnosis tooling. Beyond passive storage, operators need tooling built on top of this log: given a saga_id, reconstruct its full timeline for debugging; for a saga stuck mid-flight, show exactly which step it's stuck on and what the last attempted action was; support a manual "force compensate" or "force retry" action that itself gets logged (who did it, when, why) so operator intervention is part of the same audit trail, not an unlogged side channel.
Tamper-evidence for regulated audit needs. Where the audit log itself needs to be provably unaltered (financial or compliance contexts), techniques include hash-chaining each entry to the previous one (so any retroactive edit breaks the chain and is detectable), periodically anchoring a hash of the log to an external, harder-to-tamper-with store, or using an append-only storage layer that enforces immutability at the infrastructure level (write-once storage, or a database with row-level immutability guarantees) rather than relying on application code to never issue an UPDATE.
Cross-service distributed tracing. For sagas whose steps genuinely execute in different services, correlating the saga's audit log with each service's own request logs via a shared correlation ID (the saga_id, propagated through every service call) lets an operator reconstruct the full cross-service picture, not just "the orchestrator's view" but the actual sequence of calls and responses across every participant, useful when the bug is in a participant's handling of a step rather than in the orchestrator's sequencing logic.
Worked example. An operator investigating why saga S-8821 never completed queries the audit log by saga_id: started(order) at 10:00:00, completed(order) at 10:00:01, started(payment) at 10:00:02, then nothing for two hours. The gap itself is the diagnostic signal, no completed or failed event for the payment step means it's genuinely stuck (as opposed to compensated, which would show explicit compensation events), and cross-referencing the Payment service's own logs by the same saga_id correlation token shows its call actually errored with a timeout that was never retried, a bug in the retry logic, not in the saga design itself.
Trade-offs and pitfalls. Logging only the FINAL outcome of each step (skipping intermediate started/in_progress events) is a common shortcut that destroys exactly the diagnostic value described in the worked example: without the started timestamp, you can't distinguish "this step is still running" from "this step never started," which is the difference between a slow saga and a broken one.
Explain how vector clocks detect concurrent updates in an eventually-consistent key-value store. Give a small example where two nodes concurrently update the same key and produce divergent versions, and contrast that with last-write-wins (LWW) conflict resolution: where is LWW acceptable, and where does it cause data loss?
Sample Answer
Direct answer: A vector clock is a per-replica counter vector that lets a distributed system detect when two updates happened concurrently (neither caused the other) rather than one clearly happening after the other, which last-write-wins (LWW) can't distinguish at all, it just picks whichever write has the later timestamp, even if that timestamp is wrong due to clock skew.
Structured elaboration
How a vector clock works. Each replica keeps a vector of counters, one per replica in the system, e.g. {A: 0, B: 0} for a two-replica system. When replica A processes a local update, it increments its OWN entry: {A: 1, B: 0}. When A sends this update to replica B, B merges the incoming vector with its own (taking the element-wise max) and increments its own entry for the local receive event. Comparing two vectors tells you their relationship: if every entry in vector V1 is <= the corresponding entry in V2 (and at least one is strictly less), V1 happened-before V2. If neither vector dominates the other (some entries higher in V1, others higher in V2), the two updates are CONCURRENT, neither caused the other, and there's a real conflict to resolve.
Worked example. Two replicas, A and B, both start with a key's vector clock at {A:0, B:0}.
- Replica A updates the key locally: its clock becomes
{A:1, B:0}. - Before A's update reaches B, replica B ALSO updates the same key locally (independently): its clock becomes
{A:0, B:1}. - When these two updates are compared (e.g. during replication or a read that sees both), neither
{A:1, B:0}nor{A:0, B:1}dominates the other, A's entry is higher in the first, B's is higher in the second. This is detected as a genuine concurrent conflict: two updates happened without either replica having seen the other's change first.
Contrast with last-write-wins. LWW attaches a wall-clock timestamp to each write and, on conflict, simply keeps whichever timestamp is later, discarding the other write entirely. In the example above, LWW would compare A's and B's write timestamps and silently drop one of the two updates, with NO signal that a conflict even happened, and worse, if the two replicas' clocks are skewed (a common reality, NTP, Network Time Protocol, drift, VM pauses), the "later" timestamp might not even correspond to the update that actually happened more recently in real time.
Where LWW is acceptable. Low-stakes data where losing a concurrent update silently is an acceptable cost, and where the data model doesn't naturally support merging (a single scalar field with no sensible "combine both" semantic, e.g. a user's display name, there's no meaningful way to "merge" two different names, so picking one, even somewhat arbitrarily, is a reasonable trade for simplicity).
Where LWW causes real data loss. Anything where BOTH concurrent updates carry information that matters and shouldn't be silently dropped: a shopping cart where two devices concurrently add different items (LWW would keep only one device's additions), a counter (incrementing from two replicas concurrently under LWW loses one increment entirely, rather than correctly summing both), or any financial or inventory field where silently discarding a concurrent update is a correctness bug, not a UX nuisance.
Trade-offs and pitfalls. Vector clocks tell you a conflict EXISTS, they don't tell you how to RESOLVE it, that's a separate design decision (merge the two values, prompt the user, apply a domain-specific rule). This is the single most important nuance to state explicitly: reaching for vector clocks alone doesn't solve conflict resolution, it's the detection mechanism, not the resolution mechanism.
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.
Explain monotonic reads and monotonic writes and how they differ. Describe how you would design automated tests that programmatically verify a distributed store meets monotonic reads and monotonic writes properties under injected failures (partitions, delays). Outline test harness components and example assertions.
Sample Answer
Direct answer: Monotonic reads means a client never sees data go backward in time across successive reads (each read is at least as current as the last one it saw); monotonic writes means a client's own writes are applied in the order it issued them, even if they land on different nodes. Both are properties about a SINGLE client's own sequence, not about how fast the whole system converges. Testing them means deliberately injecting the conditions that would violate them (routing successive reads to different, differently-lagging replicas; sending writes with induced delay/reordering) and asserting the guarantee holds despite that.
Structured elaboration
Monotonic reads, precisely. If client C reads value V1 at time T1, then reads again at T2 > T1, the second read must return V1 or something NEWER, never something OLDER, even if the second read happens to be served by a different, more-lagging replica than the first. Without this, a user could refresh a page and see data revert, confusing regardless of eventual correctness.
Monotonic writes, precisely. If client C issues write W1 then write W2, the system guarantees W1 is applied before W2 EVERYWHERE, even if W1 and W2 are processed by different nodes and could otherwise race. Without this, W2 could be visible while W1 is still pending (or never lands, if a naive "last write wins" scheme picks W1 as later due to clock skew), an out-of-order result from the client's own perspective.
Test design
Injected failures/conditions. Partitions (temporarily cut connectivity between specific replicas to control which one a client's next request gets routed to and how stale it is), induced delay (deliberately slow down message delivery for one of a client's writes to test whether the system still enforces the intended order), and controlled replica staleness (a test replica deliberately held back from applying recent writes, to serve as a "known-stale" target for a monotonic-reads assertion).
Automated assertions.
- For monotonic reads: perform read R1, record its version/timestamp; force the NEXT read to be routed to a replica with LOWER known freshness than what R1 returned; assert the second read either returns data at least as fresh as R1 (correct: the routing layer detected the staleness and either waited or redirected) or the test explicitly confirms the system PREVENTS routing to that stale replica for this client's session in the first place.
- For monotonic writes: issue W1, then immediately issue W2 with W1 deliberately delayed at the network layer so it could arrive at its target AFTER W2 does; assert that after both eventually land, a read reflects W1 applied before W2 (i.e. the system enforced ordering rather than applying whichever arrived first).
Test harness components. A controllable network-simulation layer (able to inject delay, partition, or reordering between specific client-to-replica or replica-to-replica links), a way to pin a specific test read to a specific, known-state replica (bypassing normal load-balancing for the test), and an assertion library that compares returned data against expected VERSION/ordering, not just content, since two reads could have the "same" content while still violating a freshness guarantee if the test doesn't check versions explicitly.
Worked example. Test: client writes profile update W1 (bio = "A"), the test harness delays W1's replication to replica R2 by 5 seconds; client immediately writes W2 (bio = "B") which, without monotonic-write enforcement, could reach R2 (via a different path) before the delayed W1. The harness then forces a read from R2 and asserts the final visible bio is "B" (both applied, in the correct order) not "A" (only W1 applied, arriving late and incorrectly overwriting W2 due to naive last-write-wins on arrival time rather than causal order). The passing assertion confirms the system used causal/session ordering (e.g. a per-client sequence number) rather than raw arrival-time ordering.
Trade-offs and pitfalls. A common testing gap is asserting only on the FINAL converged state (eventually, W1 and W2 both apply and content looks right) without checking the INTERMEDIATE observable behavior a real client session would see, monotonic guarantees are specifically about what's visible ALONG THE WAY, not just the eventual steady state, so tests need to assert on reads taken DURING the injected delay/partition window, not only after everything settles.
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.