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.
Explain how distributed deadlocks can arise when multiple 2PC coordinators interact with overlapping resource managers. Propose an approach to detect and resolve this class of deadlock in production.
Sample Answer
Direct answer: Distributed deadlocks between multiple 2PC coordinators happen the same way single-node deadlocks do, two or more transactions each hold a lock the other needs, and neither will release until it gets the other, except now the "who's waiting for whom" graph spans coordinators and machines, so no single node can see the whole picture. The standard approaches are a distributed wait-for graph (or timeouts as a cheaper approximation), and lock ordering or timeouts to break the cycle once detected.
Structured elaboration
How it arises. Suppose transaction T1, coordinated by coordinator A, has prepared on resource manager R1 (holding R1's lock) and is now trying to prepare on R2, which is currently locked by transaction T2, coordinated by coordinator B, which is in turn waiting to prepare on R1. Neither T1 nor T2 can proceed: T1 waits on R2 (held by T2), T2 waits on R1 (held by T1). This is a classic deadlock cycle, but no single resource manager, and no single coordinator, can see the whole cycle: R1 only knows it's locked by T1 and that T2 is asking for it; R2 only knows the symmetric fact. You need a mechanism that can assemble the global picture.
Distributed wait-for graphs. Each resource manager reports its local "who's waiting for whom" edges (transaction X is waiting for a lock held by transaction Y) to a detector, which can be centralized or run as a periodic gossip/aggregation protocol across nodes. The detector unions these local edges into a global graph and looks for cycles. When it finds one, it picks a victim (commonly, the transaction that started most recently, or the one that's done the least work, to minimize wasted effort) and forces that transaction to abort, breaking the cycle. This gives precise detection but costs continuous communication overhead and adds complexity: the graph itself can be stale or incomplete under network partitions, occasionally causing false negatives (a real deadlock not detected promptly) or requiring careful handling to avoid false positives.
Timeout-based detection (used far more often in practice). Instead of building and analyzing a global graph, each participant gives up and aborts if it hasn't gotten a lock, or hasn't heard back from the coordinator, within some bounded time. This doesn't PROVE a deadlock exists, a legitimately slow network could trigger the same timeout, but it's vastly simpler to build and operate, and the cost of a false-positive abort (retrying a transaction that wasn't actually deadlocked) is usually much lower than the cost of running a distributed graph-detection protocol continuously.
Lease renewal and preemption. For locks held across a network round-trip (as 2PC's prepared-but-not-yet-decided locks are), attaching a lease (a time-bounded validity) to each lock means a coordinator that's crashed or partitioned automatically loses its hold once the lease expires, rather than requiring active deadlock detection at all; a competing transaction can then acquire the lock once the lease lapses. This trades a small window of "the original holder might still be alive and get preempted" for avoiding the deadlock-detection machinery entirely. Some designs go further with explicit preemption: a higher-priority transaction can force a lower-priority one to release, provided the loser's work can be safely rolled back (which prepared-but-uncommitted 2PC state generally supports, since nothing has been externally observed yet).
Worked example. Two account-transfer transactions run concurrently: T1 debits account A (shard 1) then credits account B (shard 2); T2 debits account B (shard 2) then credits account A (shard 1). If both prepare their first step before attempting their second, T1 holds shard 1's lock on A and waits for shard 2's lock on B; T2 holds shard 2's lock on B and waits for shard 1's lock on A. Classic deadlock. A wait-for-graph detector spanning shard 1 and shard 2's lock managers would see both edges and abort one transaction (say T2, as the later starter), letting T1 complete and then retrying T2. The same outcome is reached more simply if both locks were leased for, say, 5 seconds: whichever transaction's lease expires first gets preempted, and the other proceeds.
Trade-offs and pitfalls. Lock ORDERING (always acquire locks in a consistent global order, e.g. by account ID) prevents this class of deadlock entirely rather than detecting and recovering from it, and is usually the first thing to check for before reaching for a detection mechanism: in the worked example, if both transactions always locked the lower account ID first, the cycle could never form. Detection-based approaches are for cases where a consistent lock order genuinely isn't achievable (e.g. the resources being locked aren't known upfront).
Design a mechanism to provide 'read-your-writes' consistency to end users when reads are served through API proxies, caches, or CDNs. What approaches could you use, and what are the latency, cache-hit-rate, and availability trade-offs between them?
Sample Answer
Direct answer: When reads go through proxies, caches, or CDNs (content delivery networks) that may be stale relative to the origin, read-your-writes needs an explicit mechanism to either route a client's post-write reads to a sufficiently fresh source, or to make the client's next read wait until the cache has caught up; the main approaches are sticky routing to a known-fresh node, a client-carried version token the read path checks against, cache invalidation on write, and directing specific reads to the origin when freshness is required.
Structured elaboration
The core problem. A cache or CDN's whole value proposition is serving reads without hitting the origin every time, which is fundamentally in tension with "always show me my own latest write immediately." Any solution has to selectively bypass or catch up the cache specifically for the writer's own subsequent reads, without giving up caching's benefit for everyone else's reads.
Sticky sessions to the origin (or a fresh-enough replica). For a bounded window after a write, route that specific client's reads directly to the origin (or a replica known to be current), bypassing the cache/CDN entirely. Simple to reason about, but doesn't scale gracefully if a large fraction of traffic is write-then-immediately-read, since it defeats caching exactly when caching would otherwise help most (right after a popular item changes).
Client-side version tokens. The write response includes a version/timestamp; subsequent reads from that client carry that token; the cache or edge layer either serves a cached response only if its own known freshness meets or exceeds the token (otherwise falling through to the origin), or the token is used to select a specific, sufficiently fresh cache tier. This scales better than blanket sticky routing since it only bypasses the cache for reads that actually need to reflect a specific recent write, not for the writer's unrelated reads.
Write-through cache invalidation. On write, actively invalidate (or update) the cached copy synchronously as part of the write path, so the NEXT read from anyone (not just the writer) sees the new value, rather than waiting for a TTL (time-to-live)-based expiry. This helps everyone, not just the writer, but adds latency to the write path (the write isn't "done" until the invalidation propagates) and doesn't fully solve the problem for a globally distributed CDN where invalidation propagation itself takes time.
Directed origin reads. Simplest and most conservative: for a specific, small set of operations where read-your-writes truly matters (e.g. "show me the order I just placed"), always read from the origin for that specific query shape, accepting the cache-bypass cost only where the guarantee is actually needed, rather than building general infrastructure for it.
Trade-offs comparison
| Approach | Latency impact | Cache-hit-rate impact | Availability impact |
|---|---|---|---|
| Sticky routing to origin | Adds origin round-trip for the writer's reads | None for other users; can be significant for the writer if sustained | Origin becomes a dependency for the sticky window |
| Version tokens | Adds a fallback-to-origin cost only when the cache is actually stale relative to the token | Minimal, most reads still hit cache | Same as above, but only when actually needed |
| Write-through invalidation | Adds latency to every WRITE, not reads | Improves freshness for everyone, not just the writer | Write path now depends on invalidation succeeding |
| Directed origin reads | Origin round-trip for that specific query only | No impact on other cached queries | Localized to the specific operation |
Worked example. A social app serves post content through a CDN with a 60-second TTL. A user posts a comment and immediately navigates to the thread view; without any mitigation, they might not see their own comment for up to 60 seconds. The team implements client-side version tokens: the post-comment response includes a token; the thread-view request includes it; the edge layer checks whether its cached copy's version is at least that recent, if not, it fetches from origin (a rare case, since 60 seconds is short and most navigations happen quickly after posting, so this only adds origin load for the specific just-posted case, not broadly).
Trade-offs and pitfalls. Choosing write-through invalidation globally "to be safe" when only a narrow set of reads actually needs read-your-writes is a common over-engineering mistake, it adds write-path latency and complexity system-wide to solve a problem that a narrower, directed-read or token-based approach would have handled with far less blast radius.
Design the UX and engineering approach to expose eventually-consistent data to end users while minimizing confusion and incorrect actions. Walk through a concrete example: what should the interface actually show while the data might still be catching up, and what should the ACTING user's own experience look like versus everyone else's?
Sample Answer
Direct answer: Expose eventually-consistent data to users by combining read-your-writes for the user's own actions (so their own changes always look correct to them), causal or version metadata carried through the UI so the client can detect and gracefully handle stale reads, and explicit UI reconciliation (a subtle "updating..." indicator or a merge prompt) rather than either hiding staleness entirely or confusing the user with an unexplained flicker.
Structured elaboration
Read-your-writes as the baseline. Whatever else the design does, the ACTING user should always see their own action reflected immediately, this alone eliminates the most common and most confusing eventual-consistency symptom (a user does something and it looks like it didn't work). Implemented via the mechanisms discussed elsewhere in this topic (sticky routing, version tokens).
Causal/version metadata. Every piece of eventually-consistent data the UI displays carries a version or timestamp the client can use, both to detect when a NEWER version has become available (prompting a lightweight refresh rather than the user having to guess something changed) and to avoid the UI regressing to an OLDER value if a later request happens to be served by a more-stale replica (a monotonic-reads violation from the user's point of view, and a real UX bug if not guarded against).
UI reconciliation patterns. Rather than silently showing possibly-stale data as if it were definitely current, or blocking the UI until a strongly-consistent read completes (defeating the purpose of using eventual consistency in the first place), the interface signals uncertainty appropriately to the situation: a subtle "syncing..." indicator for data that's expected to catch up within a second or two, an explicit "this may not reflect the latest changes" note for longer-lag scenarios, or, for genuinely conflicting concurrent edits, a merge-conflict prompt letting the user see and choose between divergent versions.
Order-status example, concretely. An order-status page shows "Processing" immediately after checkout (this status write is the user's OWN action, read-your-writes applies, no lag here). As the order progresses through downstream services (payment confirmation, inventory allocation, shipping label creation), each of those services' writes propagate to the status page ASYNCHRONOUSLY, the status page might briefly show "Processing" for a few seconds after payment has actually already been confirmed elsewhere. The design mitigates this with: an optimistic UI update the moment the user's own action (placing the order) is confirmed (read-your-writes), a lightweight polling or push-based refresh (not the user having to manually reload) that updates the displayed status as soon as new information propagates, each status carrying a timestamp shown subtly to the user ("updated 3s ago") so the display doesn't implicitly claim to be instantaneous, and, if the status hasn't updated within an expected window (e.g. no change after 30 seconds when a change was expected), a fallback to an explicit strongly-consistent check rather than leaving the user staring at a potentially-stale status indefinitely.
Testing user-facing correctness. Beyond the backend correctness tests discussed elsewhere in this topic (convergence, monotonicity), UI-level testing specifically injects realistic replication delay into a staging environment and verifies: the acting user's own view never shows a regression (their own action always reflected, per read-your-writes), the staleness indicator accurately reflects actual lag (not a hardcoded or misleading value), and the fallback-to-strong-check path actually fires and resolves correctly when the expected update doesn't arrive within the design's own stated window.
Trade-offs and pitfalls. A common design mistake is either fully hiding staleness (presenting eventually-consistent data with the same visual confidence as strongly-consistent data, which then produces a confusing "it says X but actually Y" moment when a user compares notes with someone else or refreshes at the wrong time) or over-communicating it (a persistent, anxiety-inducing "this data might be wrong" banner on every page, which erodes trust even when the actual staleness window is small and rarely matters), the better middle ground calibrates the UI signal to the actual, monitored staleness distribution for that specific data, not a blanket policy either way.
Design an architecture for coordinating cross-service transactions in a distributed data platform where ACID guarantees across services are infeasible. Walk through how you would make forward progress safely, detect when something has gone wrong, and recover, so the platform reaches a consistent state without ever needing a single distributed transaction across every participant.
Sample Answer
Direct answer: Where ACID guarantees across services aren't feasible, the architecture combines sagas with compensating transactions to make forward progress and correct partial failures after the fact, idempotency on every step so retries under failure are safe, monitoring that surfaces sagas stuck mid-flight, and a human-in-the-loop remediation path for the cases automation genuinely can't resolve on its own.
Structured elaboration
Why full ACID is infeasible here. Each service owns its own datastore, and a real distributed-transaction protocol (2PC or consensus-backed) across all of them would mean every service blocks holding locks for the duration of a cross-platform operation, an availability cost most data-platform workloads (analytics pipelines, cross-domain reporting, multi-team data products) can't tolerate, especially when the services involved don't share an operational team or even a network boundary.
Sagas plus compensation as the coordination mechanism. Each cross-service operation is modeled as a saga: a sequence of local, independently-committing steps, each with a defined compensating action. This gets you eventual consistency (the platform converges to a correct state) without requiring any step to block on another.
Idempotency at every step. Since network failures mean the platform can't always tell whether a step's call succeeded, every step (forward and compensating) is keyed with an idempotency token so a retry doesn't double-apply. This is the property that makes "just retry on failure" a safe default strategy rather than a source of duplicate side effects.
Monitoring for stuck sagas. Every saga's progress is tracked (as in the audit-trail design), and an automated monitor flags any saga that has been sitting in an intermediate, non-terminal state for longer than its expected duration, this is the platform's early-warning signal that something needs attention, rather than discovering it only when a downstream consumer complains about missing or inconsistent data.
Human-in-the-loop remediation. For sagas that genuinely can't be resolved automatically (an external dependency is down for an extended period, a compensating action itself keeps failing, or the situation requires a judgment call not encoded in the automated logic), the platform surfaces them in an operator queue with enough context to decide: force-retry, force-compensate, or manually correct the underlying data, with every manual action itself logged as part of the saga's audit trail.
Worked example. A data platform propagates a schema change across three downstream systems (a warehouse, a search index, and a caching layer) as a saga. The warehouse and search index apply the change successfully; the caching layer's apply step fails repeatedly due to a transient outage. The stuck-saga monitor flags this after it's been "in progress" for longer than the platform's SLA for this kind of propagation. An operator is alerted, sees the caching layer has been down for 40 minutes (from the same monitoring), and either waits for it to recover (retries resume automatically once it's healthy) or, if urgent, manually applies the schema change to the cache and marks that step "manually completed" in the saga's state, an action itself recorded in the audit trail.
Trade-offs and pitfalls. A platform that builds the saga-plus-compensation machinery but skips the monitoring and human-remediation path ends up with sagas that silently stall forever with no one aware, which is worse for data correctness than a system that never attempted eventual consistency in the first place, because nothing signals that the data is now actually inconsistent. The monitoring and remediation path is not optional polish, it's what makes "eventual" in "eventual consistency" an operational promise rather than a hope.
Design a conflict-resolution framework for complex JSON documents used in a distributed system. Documents contain nested objects, arrays, and fields whose correct merge behavior varies by field, some should replace, some should combine. Describe the metadata you would attach, how you would let different fields merge differently, and your fallback strategy for a conflict no automatic rule can safely resolve.
Sample Answer
Direct answer: For complex JSON documents with nested objects, arrays, and domain-specific merge rules, the design attaches per-field (or per-path) merge metadata rather than one blanket strategy for the whole document, applies structural rules by field TYPE (scalars use LWW or a domain rule, arrays use set/sequence semantics depending on intent, nested objects recurse the same merge logic), embeds explicit domain rules where the natural type-based default is wrong (ratings take max, tags union), and falls back to surfacing an unresolvable conflict rather than guessing when no rule cleanly applies.
Structured elaboration
Per-path metadata. Rather than one merge function for the whole document, the design tracks, for each JSON path (e.g. $.ratings.overall, $.tags), what KIND of merge applies there: last-write-wins, numeric-max, set-union, or a custom domain function. This is necessary because a single document genuinely mixes fields with very different correct merge semantics, treating them uniformly (e.g. LWW for everything) would be simple but wrong for many fields.
Default rules by structural type. Scalars (numbers, strings, booleans) default to LWW unless a domain rule overrides it. Arrays default to set-union semantics if order doesn't matter for that field (deduplicating by value or by an element ID), or to a sequence-CRDT-style position-preserving merge if order genuinely matters (e.g. an ordered list of steps). Nested objects recurse: the SAME per-path merge logic applies to each nested field independently, so a deeply nested document is handled compositionally rather than needing a special case for depth.
Domain-specific rule examples. "Ratings take max": for a field like $.qualityScore where two concurrent updates might reflect two different reviewers' concurrent submissions, the domain decides the highest score should win rather than an arbitrary last-write, a business rule, not a generic data-structure default. "Tags union": for $.tags, the domain decides concurrent additions from different sources should ALL be kept (set-union) rather than one replacing the other, since tags are additive by nature.
Fallback strategies for impossible merges. Some conflicts have no automatic resolution: two concurrent edits to a deeply structural field (e.g. one edit reshapes $.address from a string to a nested object, while a concurrent edit modifies the OLD string-shaped value), these are genuinely irreconcilable by any generic rule and need to be surfaced explicitly (both candidate document versions, with metadata about the conflicting paths) for human or application-level resolution, rather than the merge engine guessing and potentially producing an internally inconsistent document.
Worked example. A product-review document: $.title (LWW), $.rating (max, per the domain rule that a higher rating from a concurrent update should win, reflecting the reviewer's most positive assessment), $.tags (set-union, so tags added from two different concurrent edit sessions all survive), and $.photos (an OR-Set of photo IDs, so concurrently-uploaded photos from two devices both appear rather than one overwriting the other). Two concurrent edits: edit A sets rating: 4, tags: ["great_service"]; edit B (concurrent, unaware of A) sets rating: 5, tags: ["fast_delivery"]. Merge result: rating: 5 (max rule), tags: ["great_service", "fast_delivery"] (union rule), no conflict surfaced, since every field had a clean, applicable rule.
Trade-offs and pitfalls. The biggest practical risk in this design is an UNDEFINED merge rule for a path silently defaulting to something wrong (e.g. LWW applied to a field that actually needed union semantics) rather than failing loudly during development; a strong version of this design validates, at schema-definition time, that every field in the document has an EXPLICIT merge rule assigned, rather than relying on an implicit fallback that might quietly produce a business-incorrect result in production.
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.