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.
You need a repair system capable of rewinding and reapplying events across replicas to fix a logical bug introduced in the event-processing code. Design the mechanism to snapshot state, replay events in a safe order, ensure idempotence during reapply, and minimize user-visible disruption. Provide rollback and verification steps.
Sample Answer
Direct answer: Rewinding and safely reapplying events to fix a bug that was introduced by buggy event-processing code requires snapshotting state before the reapply, replaying events in a deterministic, verifiable order, ensuring the reapply logic is itself idempotent (since a reapply attempt might itself need to be retried), and minimizing user-visible disruption by doing the repair on a copy or in a way that doesn't block live traffic.
Structured elaboration
Snapshot before touching anything. Before starting any repair, capture a full snapshot of the current (buggy) state, this is both your rollback point if the repair itself goes wrong, and your baseline for verifying the repair actually fixed what it was supposed to fix (diff the pre- and post-repair state against expectations).
Determine the correct replay starting point. Identify the earliest point where the buggy logic could have produced incorrect results (typically, the deployment time of the bug, or earlier if the bug could have affected historical processing retroactively), and confirm the FIXED event-processing logic is what will be used for the replay, replaying with the same buggy code obviously reproduces the same bug.
Replay in a safe order. Events must be replayed in the same relative order they were originally processed (per aggregate/entity, at minimum; global ordering isn't usually necessary), out-of-order replay can produce a DIFFERENT, also-incorrect result even with correct processing logic, since many state transitions are order-dependent.
Idempotence during reapply. The replay process itself needs to be safe to interrupt and resume: if the repair job crashes partway through, restarting it should not double-apply events already reprocessed. This typically means tracking a replay checkpoint (a per-entity or per-partition high-water mark of what's already been redone) and being able to resume from there, exactly the same idempotency discipline used elsewhere in this topic, applied to a repair job instead of live traffic.
Minimizing user-visible disruption. Where possible, run the replay against a SEPARATE copy of the state (a shadow store) first, validate the result there, and only then cut over (or apply the diff) to the live system in a controlled way, rather than replaying directly against production data while it's serving live traffic, which risks exposing partially-repaired, inconsistent state to users mid-repair.
Verification. After the replay, compare the repaired state against independent expectations (a known-correct sample, an invariant check like "total conserved" for a financial domain, or a diff against what the CORRECT logic would have produced from scratch on a subset), before considering the repair complete and before removing the snapshot taken at the start.
Worked example. A bug in an inventory-adjustment event processor was double-counting a specific event type for three weeks before being caught. Repair: snapshot current inventory state; identify the affected event types and the time window; build a shadow copy of the inventory read-model and replay ALL events from before the bug window using the now-fixed processor logic; verify the shadow copy's totals against a small set of manually-audited SKUs known to be correct; once verified, apply the diff between the shadow copy and the live (buggy) state as a single, logged, auditable correction to production, rather than replacing the live state wholesale (which would risk losing any legitimate changes that happened AFTER the replay's snapshot point but before the correction is applied).
Trade-offs and pitfalls. Replaying directly against the live, currently-serving state (skipping the shadow-copy step) is the highest-risk shortcut here: any bug in the REPLAY logic itself (not just the original processing bug) is now live and user-visible immediately, with no isolated environment to catch it first.
Architect a transactional outbox pattern for reliably publishing domain events when committing a write to the primary database. Include the outbox table schema, the reader design (and how you'd compare a polling reader against a change-data-capture-based reader), ordering guarantees, idempotency handling on the consumer side, and how you would scale the reader for high throughput.
Sample Answer
Direct answer: A production-grade transactional outbox service has three pieces: the application's database with an outbox table written in the same local transaction as the business change, a relay/reader that publishes unpublished rows to the broker (polling or CDC-based, CDC meaning change-data-capture), and enough retry/dedup discipline on both sides that the whole thing delivers at-least-once without ever silently losing an event.
Structured elaboration
Outbox table schema. At minimum: id (primary key, also usable as an idempotency/dedup token), aggregate_id (what business entity this event is about, often used as the broker partition key to preserve per-entity ordering), event_type, payload (serialized event body), created_at, and published (boolean, or a published_at timestamp, null until published). An index on (published, created_at) supports the "give me the oldest unpublished rows" query the reader needs.
Reader design: polling vs streaming. A polling reader periodically queries for published = false rows, simple to build and reason about, but adds latency bounded by the poll interval and puts a steady, small query load on the database. A CDC-based (streaming) reader instead taps the database's write-ahead log or replication stream (e.g. via Debezium) to be notified of new outbox rows as they're written, giving near-real-time delivery with no polling load, at the cost of running and operating CDC infrastructure and a slightly more complex failure story (the CDC connector itself can fall behind or need to resume from a checkpoint).
Ordering guarantees. If per-entity ordering matters (e.g. all events for order 501 must be delivered in the order they were created), the reader must publish using aggregate_id as the partition/routing key, so a partitioned broker (like Kafka) preserves order within that key even while allowing parallelism across different keys. Global ordering across all entities is usually not worth the throughput cost and isn't needed by most consumers.
Idempotency handling on the consumer side. Since the relay guarantees only at-least-once delivery, every event's payload includes a stable ID (the outbox row's id, or a domain-level event ID) that consumers use to deduplicate, typically via a small "seen event IDs" store with a bounded retention window matched to how long redelivery could realistically be delayed.
Scaling the reader for high throughput. A single polling reader eventually becomes a bottleneck; horizontal scaling requires either sharding the outbox table (e.g. by a hash of aggregate_id) with one reader instance per shard, or, for a CDC-based reader, letting the CDC connector's own partitioning handle parallelism. Batching reads and publishes (rather than one row per query/publish round-trip) is usually the first and cheapest throughput lever before reaching for sharding.
Worked example. An orders platform doing 2,000 writes/sec needs its outbox reader to keep pace. A single polling reader batching 200 rows per poll every 200ms caps out at 200 / 0.2s = 1,000 rows/sec, below the required rate regardless of how the rest of the system is tuned. Moving to a CDC-based reader (Debezium tailing the outbox table's WAL, write-ahead log) removes the poll-interval ceiling entirely, since new rows are picked up as they're written to the log rather than on a fixed cadence, at the cost of adding a Kafka Connect cluster and its own on-call burden that didn't exist with the simpler polling design; the actual sustained throughput and delivery latency the CDC path achieves would need to be measured against the real database's write-ahead log volume and Kafka Connect's own configured parallelism, not assumed from the pattern alone.
Trade-offs and pitfalls. Teams often under-invest in the outbox table's own cleanup: published rows accumulate forever unless there's a retention/archival job, which eventually degrades both the outbox query performance and, for CDC-based readers, the size of the write-ahead log the CDC connector has to process on any resume-from-checkpoint scenario.
When is eventual reconciliation (periodic jobs to reconcile and fix inconsistencies) acceptable versus requiring strong transactional boundaries? Provide decision criteria (RPO/RTO, regulatory constraints, user impact) and concrete examples where reconciliation is appropriate and where it is not.
Sample Answer
Direct answer: Periodic eventual-reconciliation jobs are appropriate when a brief, bounded window of inconsistency is genuinely tolerable and the cost of detecting and fixing drift after the fact is lower than the cost of preventing it upfront; strong transactional boundaries are required when the business, regulatory, or user-impact cost of even a brief inconsistency is high enough that prevention is worth its latency and availability cost.
Structured elaboration
Decision criteria.
- RPO (recovery point objective) / RTO (recovery time objective)-style tolerance: how much divergence, and for how long, can the business actually tolerate before it becomes a real problem? A system that can tolerate "wrong for up to 5 minutes, self-corrects" is a strong candidate for eventual reconciliation; one that can't tolerate ANY window of visible inconsistency needs prevention (strong transactions) instead.
- Regulatory constraints: some domains have an explicit compliance requirement for certain data to be immediately and provably consistent (financial ledger entries in some jurisdictions, access-control changes with security implications), for these, eventual reconciliation isn't a technical trade-off you're free to make, the requirement itself rules it out regardless of engineering preference.
- User impact of the DETECTED-AND-FIXED window: even if reconciliation genuinely fixes drift, what does the user experience DURING the window before it's fixed? A stale analytics number nobody's watching in real time is low-impact; a stale permission grant a user is actively relying on is a real, if temporary, security or correctness gap even though it self-corrects.
Where eventual reconciliation is appropriate. Denormalized read views (search indexes, cached aggregates, materialized views) that are DERIVED from an authoritative source, since the authoritative data was never actually wrong, only its derived copy is temporarily behind, and periodic reconciliation (or the read-repair/anti-entropy mechanisms discussed elsewhere in this topic) is a proven, well-understood pattern for exactly this case. Cross-system data that's inherently eventually propagated anyway (e.g. syncing to a downstream analytics warehouse), where a periodic reconciliation job is really just formalizing and monitoring a delay that already exists structurally, not introducing new risk.
Where strong transactional boundaries are required instead. Anything where a user or another system could ACT on the inconsistent state before reconciliation catches it, in a way that causes real, hard-to-reverse harm (double-spending, granting access that should have already been revoked, confirming an order against inventory that's actually unavailable). Anything with an explicit regulatory requirement for immediate consistency, regardless of the technical cost.
Worked example: appropriate case. A search index that's rebuilt from the authoritative product catalog via periodic reconciliation (nightly full diff, plus a faster incremental sync every few minutes) is a good fit, users searching might occasionally see a slightly outdated product description for a few minutes, low-cost, self-correcting, and the authoritative catalog itself (used for the actual purchase flow) was never at risk.
Worked example: inappropriate case. Using periodic reconciliation (rather than a strong transactional boundary) for propagating an ACCESS REVOCATION across services would mean a user whose access was just revoked could continue acting with their old permissions for however long the reconciliation window is, a real, if temporary, security gap that a "we'll catch it in the next reconciliation pass" approach doesn't adequately address, this needs either a synchronous, strongly-consistent revocation path, or at minimum a MUCH tighter, actively-monitored propagation SLA than a casual periodic-reconciliation pattern would typically provide.
Trade-offs and pitfalls. The recurring mistake is applying "eventual reconciliation is fine, we'll catch it later" as a blanket default across an entire system without separately evaluating each specific data flow against these criteria, some flows in the same system (like the search-index example) are genuinely fine with it, while others (like access revocation) are not, and treating them uniformly under one policy either over-engineers the low-risk cases or, more dangerously, under-protects the high-risk ones.
Explain how event sourcing with CQRS can be applied to manage consistency in a microservices architecture. Discuss what it genuinely buys you and what it costs you operationally, and where you'd recommend adopting this pattern versus not.
Sample Answer
Direct answer: Event sourcing stores every state-changing event as the system of record (instead of just current state), and CQRS (command query responsibility segregation) splits the write model (which processes commands and appends events) from one or more read models (which are built by replaying or projecting those events). Together they help manage consistency in a microservices architecture by making every state change an explicit, replayable fact, at the cost of read models that are only eventually consistent with the write side and real added tooling complexity.
Structured elaboration
How it helps with consistency. Every change is captured as an immutable event, so a service's full history is reconstructable by replaying its events, this gives you auditability for free (you can always answer "how did we get to this state, and when") and traceability across services (correlating events by a shared ID reconstructs a cross-service causal history, similar in spirit to a saga's audit trail, but as a first-class storage model rather than a bolt-on log). Because commands are handled by appending an event rather than mutating shared state in place, a service's write side avoids a whole class of update-in-place race conditions, concurrent commands against the same aggregate are naturally serialized by appending to that aggregate's own event stream.
Read-model staleness. The read side (a projection or materialized view built by consuming the event stream) is, by construction, built asynchronously from the events, so it lags behind the write side by however long projection takes, this IS the standard "read-your-writes" gap you'd need to solve explicitly with a session guarantee (or accept as user-visible eventual consistency) if your UI needs to immediately reflect a just-made change.
Tooling complexity. You need infrastructure for the event store itself (append-only, ordered per-aggregate, queryable for replay), for building and maintaining projections (and rebuilding them when a projection's logic changes, since you may need to replay the FULL event history to regenerate a read model correctly), and for handling event schema evolution over time as your domain model changes, all real, ongoing engineering investment beyond what a conventional CRUD service needs.
Where this pattern is a good recommendation. Domains that already need a full audit trail or the ability to answer "what did this look like at time T" (financial ledgers, compliance-heavy domains, anything with dispute resolution requiring historical reconstruction), or domains with complex temporal business logic that's naturally expressed as a sequence of events rather than a single current-state row.
Where it's usually the wrong recommendation. Simple CRUD-shaped services with no real need for history or complex read-side views, the tooling and staleness costs aren't repaid by anything the domain actually needs. It's also a poor fit for teams without existing operational experience running event stores and projection pipelines, since debugging a broken projection or reasoning about an event-schema migration has a real learning curve.
Worked example. An order-management service adopts event sourcing: every state change (OrderCreated, ItemAdded, PaymentApplied, OrderShipped) is appended to that order's event stream. A "current order status" read model is a projection consuming these events; an "order history timeline" view (useful for customer support and audits) is a SECOND projection over the exact same event stream, no extra write-side work needed to support it, since it's just a different way of folding the same facts. When the team later needs a new read model (e.g. "orders at risk of SLA breach"), they build a new projection consuming the existing event history, no changes to the write side.
Trade-offs and pitfalls. Teams sometimes adopt event sourcing purely to get "an audit log" without needing the read-model flexibility or historical-reconstruction capability it actually provides, in which case a simpler append-only audit table alongside a conventional current-state model gets most of the auditability benefit without the projection-rebuild and schema-evolution overhead.
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.
Unlock Full Question Bank
Get access to all 49 Data Consistency and Distributed Transactions interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.