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.
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.
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.
You are on-call: users report duplicate charges even though requests include idempotency keys. Provide a prioritized debugging checklist to find the root cause: logs/traces to inspect, DB constraints, idempotency key collisions or TTL expiry, races in key insertion, message replay sources, third-party gateway callbacks, and immediate remediation steps.
Sample Answer
Direct answer: With duplicate charges despite idempotency keys being present, the systematic debugging path is: confirm the SAME key was actually reused across the duplicate charges (not two different keys for what the client thought was one action), check for a race between concurrent requests with that key, check for a TTL (time-to-live) that expired and let a "retry" outlive the dedup record, and check whether the duplication happened upstream (client generating a new key per retry) or downstream (the payment gateway itself, or a message replay bypassing the key check).
Structured elaboration
Step 1: confirm it's actually the same idempotency key. Pull the logs/traces for both charges and compare their idempotency keys directly. If they're DIFFERENT keys, the bug isn't in the idempotency mechanism at all, it's in the CLIENT generating a new key per retry instead of reusing one, the single most common root cause of "idempotency keys didn't work" reports. This check should be first because it redirects the entire investigation if it's true.
Step 2: rule out an idempotency-key collision. Separately from a race, check whether the key itself has enough entropy and uniqueness, was it a properly generated UUID/random token, or was it derived from mutable or low-cardinality business fields (customer ID plus rounded timestamp, for example) that two DIFFERENT orders could plausibly produce the same value for? Also check whether an internal layer (a datastore column, a cache key, a hashing step) truncates or re-hashes the client's key in a way that could map two distinct client keys onto the same stored dedup record. A genuine collision more often shows up as a MISSED charge (the second, different order gets silently treated as a duplicate of the first) rather than a duplicate one, so it's a less likely direct cause here, but it's cheap to rule out early because its fix (widen the key's entropy, stop truncating/re-hashing it internally) is entirely different from a race or TTL fix.
Step 3: check for a key-insertion race. If it IS the same key, check whether both charge attempts' timestamps are close enough together to suggest they raced: did the second request's dedup-check run BEFORE the first request's transaction committed? This points to a missing or incorrectly-scoped database constraint (the unique-key insert and the charge creation weren't actually in the same atomic transaction), or a check-then-act pattern in application code instead of relying on the database's own uniqueness enforcement.
Step 4: check TTL and expiry. If the two charges are far apart in time (hours or more), check whether the idempotency-key record had already been cleaned up (expired past its TTL) by the time the "retry" arrived, an overly aggressive cleanup job can inadvertently let a legitimate late retry through as if it were a brand-new request. This is a config/policy bug, not a logic bug, worth distinguishing because the fix (adjust the TTL) is different from a code fix.
Step 5: check for replay sources. If the request path involves a message queue or webhook relay upstream of the idempotency check, confirm whether the SAME idempotency key made it into two separate messages (a bug in whatever's producing those messages) versus the idempotency-key check itself being bypassed on a replayed message (e.g. if replay happens at a layer that doesn't go through the same dedup code path as normal requests).
Step 6: check third-party gateway callbacks. If the payment gateway itself sends a callback/webhook confirming the charge, and that webhook is ALSO wired to trigger some local state change, verify the webhook handler is idempotent independently, a duplicate WEBHOOK delivery (common; most gateways explicitly warn about this) can cause a duplicate downstream effect even if the original charge request itself was correctly deduplicated.
Immediate remediation. Once the specific duplicate charges are confirmed (via the gateway's own transaction records, not just internal logs, since internal logs could themselves be the buggy layer), refund the duplicate charge and notify the affected customer proactively rather than waiting for them to notice, and flag the affected account for a manual review pass to catch any other duplicates from the same root-cause window.
Worked example. Investigation reveals: same idempotency key on both charges (step 1 clean), timestamps 4 hours apart (step 2 not applicable, too far apart to be a race), and the TTL policy is configured to clean up keys after 1 hour (step 3 hit). The retry, which happened after a genuinely long client-side outage, arrived after the key had already been purged, and was processed as if it were a brand-new request. Fix: extend the TTL to a value that comfortably covers realistic retry windows (informed by actual client retry-timeout configuration), and add a safety check that flags (rather than silently allowing) a charge request whose amount and customer exactly match a recently-expired key, as a defense-in-depth measure.
Trade-offs and pitfalls. Jumping straight to "the idempotency implementation is broken" without first confirming step 1 (same key, actually reused) wastes investigation time on the wrong layer; the debugging order above is deliberately structured to rule out the cheapest, most common causes first.
Design API semantics and a contract to allow clients to retry complex 'create-with-side-effects' operations safely (for example: create-order that triggers inventory reservation and payment). Define idempotency key structure, client responsibilities, server guarantees (at-most-once vs idempotent-create), visibility of side-effects to users, and error semantics.
Sample Answer
Direct answer: For a create-with-side-effects operation like create-order (which triggers inventory reservation and payment), the API contract needs a client-generated idempotency key that scopes the ENTIRE multi-step operation, not just the first HTTP call, so a client retry after a timeout re-resolves to the same underlying order and side effects rather than triggering a second one; the server tracks the operation's progress against that key and returns a consistent result regardless of how many times the client retries.
Structured elaboration
Idempotency key structure. The client generates a key once per logical intent (e.g. a UUID generated when the "place order" button is clicked, reused on every retry of that same click, never regenerated on retry). The server stores this key alongside the operation's current state and final result once known, exactly the shape used for a single-endpoint idempotent write, but here the "operation" spans multiple internal steps (order creation, inventory reservation, payment) rather than a single database write.
Client responsibilities. Generate the key once and persist it (e.g. in local state) before the first attempt, reuse the SAME key on every retry of the same logical action, and never reuse a key for a genuinely different order (e.g. a second, separate purchase needs its own key).
Server guarantees: idempotent-create vs at-most-once. The contract promises idempotent-create semantics: retrying with the same key is guaranteed to return the result of the FIRST successful attempt (or the current in-progress status), never trigger a second inventory reservation or a second charge, this is stronger than plain at-most-once (which would just refuse to retry at all) and is what actually lets clients retry safely after an ambiguous failure like a timeout.
Visibility of side effects to users. Because the operation spans multiple steps that don't all complete instantly, the API returns a status field alongside the order/operation ID: pending (steps still in flight), completed (all steps succeeded), or failed (a step failed and compensations, if any, have run). A client polling on the same idempotency key (or the returned operation ID) gets a consistent, current view rather than each poll re-triggering work.
Error semantics. A definitive rejection (e.g. inventory genuinely unavailable) returns a failed status with a reason, and the idempotency key is now permanently associated with that failed outcome, a retry with the SAME key returns the same failure rather than re-attempting (since re-attempting the same operation with the same inputs would fail again anyway); a genuinely NEW attempt requires a new key, communicating the client's intent to try again as a fresh action, which matters if the failure was due to a transient condition the client wants to retry past.
Worked example. Client calls POST /orders with Idempotency-Key: 8f3c... and the order payload. The server hasn't seen this key before, so it starts the underlying saga (create order, reserve inventory, charge payment), stores status: pending against the key, and returns 202 Accepted with an operation ID. A network blip means the client never sees this response, and retries the SAME POST /orders call with the SAME idempotency key. The server recognizes the key, sees the saga is still pending, and returns the current status (again 202, same operation ID) WITHOUT starting a second saga. The client can now poll GET /orders/{operation_id} (itself naturally idempotent, a read) until it sees completed or failed.
Trade-offs and pitfalls. A common design mistake is treating the idempotency key as scoping only the first HTTP request rather than the whole underlying operation, if the key is discarded once the initial 202 response is sent, a later retry re-triggers the ENTIRE saga from scratch, defeating the purpose. The key must remain valid and checked for the full lifetime of the operation it protects, not just the initial acknowledgment.
Design a multi-region user profile service that must support 100M users, 50k profile updates per second globally, and 1M reads per second. Requirements: users see their own updates immediately (read-your-writes) within a region, other users see updates eventually (within a bounded window), and 99th-percentile read latency stays low per region. Sketch the high-level architecture, replication strategy, and how you provide the read-your-writes guarantee without strong global coordination.
Sample Answer
Direct answer: At 100M users and 50k updates/sec, you need per-user data partitioned by region with a "home region" per user for writes, asynchronous cross-region replication for eventual global visibility, and a session-scoped mechanism (sticky routing to the user's home region, or a causal token) so each user sees their own updates immediately without requiring global synchronous coordination.
Structured elaboration
Partitioning and write routing. Each user is assigned a home region (based on signup location or explicit preference), and writes for that user's profile are always directed there, giving each user's writes a single, consistent, low-latency write path with no cross-region coordination needed per write. This is what makes 50k writes/sec globally distributed and still individually cheap: it's 50k INDEPENDENT single-region writes, not 50k globally-coordinated ones.
Cross-region replication. Each region's writes replicate asynchronously to every other region (a standard multi-region replication topology, e.g. a change stream fanning out from each region's primary store to the others). This is what provides "eventually visible to other users" within the required bound (here, one minute), the replication pipeline's own throughput and lag characteristics need to comfortably clear that bound under peak load, with monitoring on actual observed lag, not just a theoretical budget.
Read-your-writes without global coordination. Since the user's OWN writes always land in their home region, and their own subsequent reads can be routed to that SAME home region (sticky, based on the user's identity, not their current network location) for some bound (or indefinitely), the user always sees their own latest update, at native single-region latency, no waiting for cross-region replication for their OWN view. Other users reading this profile from a different region see it once replication catches up, within the required window, satisfying "others see it eventually within 1 minute" without that requirement touching the write or same-user-read path at all.
Achieving sub-50ms P99 read latency per region. Reads (for other users viewing a profile, not the owner's own reads) are served from the LOCAL region's replica, so they never cross a region boundary, keeping latency to local-network/local-disk numbers rather than being bounded by cross-region round-trip time (which alone would often exceed 50ms). This is only possible because the read doesn't need to be perfectly fresh, it needs to be fresh within a minute, which the async replication path already provides.
Handling the home-region-unavailable case. If a user's home region has an outage, either the user experiences degraded write availability (a real, honest trade-off of this design, since the write path is intentionally NOT cross-region-coordinated) or the system fails over the user's home-region assignment to another region (a more complex, operationally significant decision that itself needs careful handling to avoid conflicting writes from the old and new home regions during the transition).
Worked example. User in Region A updates their bio. The write commits to Region A's primary (their home region) as a purely local operation, with no cross-region network hop on the critical path, so its latency is bounded by local disk/network characteristics rather than by inter-region round-trip time, the same reasoning that keeps the P99 read latency for other users' LOCAL reads low. The response confirms success, and if the user immediately reloads their own profile, that read is also routed to Region A (sticky by user identity), showing the update instantly, own-write visibility achieved with zero cross-region dependency. Meanwhile the change replicates asynchronously to Regions B and C; a different user in Region B viewing this profile sees the OLD bio for however long replication takes (comfortably under the 1-minute bound under normal load, monitored explicitly for tail cases during regional replication backlogs).
Trade-offs and pitfalls. A common design mistake at this scale is routing the OWNER's reads based on their CURRENT network location rather than their home region (e.g. "nearest region" routing applied uniformly to all reads), which breaks read-your-writes the moment a user travels or is routed to a different region than the one their write landed in, own-write reads need identity-based (not network-proximity-based) routing specifically for this reason.
Unlock Full Question Bank
Get access to all 46 Data Consistency and Distributed Transactions interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.