The interview problem
A transactional database spans 100 partitions and runs 50,000 concurrent transaction attempts. Transactions can hold exclusive locks on multiple partitions while waiting for another lock. Design a service to detect cross-partition deadlocks and recover without violating atomicity. Explain delayed observations, coordinator failure, prepared transactions and retry storms.
Original system-design practice, not a reported company interview. The numerical workload and protocol below are interview assumptions, not a description of PostgreSQL. Sources retrieved September 27, 2026; interview date not applicable.
Quick answer
A distributed deadlock occurs when transactions cannot proceed because their lock dependencies form a cycle under the stated lock model. Collect a wait-for graph, identify candidate cycles and ask the transaction coordinator to resolve a victim. Delayed graph updates can create phantom cycles; a timeout alone does not establish deadlock.
1. Define the wait model before drawing a graph
Assume each transaction attempt issues one blocking lock request at a time, exclusive locks have one holder, and acquired write locks remain held until transaction completion. A blocked request can be cancelled while its previously acquired locks remain held. Reads that use snapshots are outside this lock graph. The transaction coordinator is the authority for a durable terminal decision.
Represent an edge A → B when attempt A cannot acquire its requested lock because attempt B holds it. Under this simplified model, a simultaneous directed cycle means none of its participants can acquire the awaited resource without external intervention. A transaction waiting for several alternative resources needs a different dependency model: a cycle alone need not prove deadlock when any one alternative can unblock it.
Track the full transaction-attempt identity, not a reusable connection ID. Distinguish lock waiting, waiting for a commit decision, a slow participant and an unreachable coordinator. A timeout is useful recovery policy but is not proof of a cycle.
2. Build a cross-partition example
| Attempt | Already holds | Requests | Wait edge |
|---|---|---|---|
| A | X on partition 1 | Y held by B on partition 2 | A → B |
| B | Y on partition 2 | Z held by C on partition 3 | B → C |
| C | Z on partition 3 | X held by A on partition 1 | C → A |
No partition sees the complete cycle from its own lock table. The detector must connect global attempt identities across the three partition reports. Aborting B eventually releases Y, allowing A to acquire it. A's eventual completion releases X, allowing C to continue. Aborting a victim breaks this cycle; it does not promise that every surviving transaction will immediately finish or avoid another cycle.
3. Keep detection separate from transaction authority
partition lock managers → versioned wait events → graph service
↓
suspected cycle
↓
authoritative edge checks
↓
coordinator abort request
↓
durable decision → participant cleanupFor this workload, start with a single logical graph service with a standby. Lock managers emit additions and removals containing partition epoch, monotonic sequence number, waiter attempt, blocker attempt, resource identifier and request generation. Deduplicate events. A leadership epoch change invalidates the previous partition view until a replacement snapshot is installed.
Install a partition snapshot at sequence s, then apply events after s. A gap triggers resynchronization rather than silent continuation. Keep removal versions long enough to reject late additions. Stable transaction identifiers also need attempt generations so a retry cannot inherit an old wait edge.
Run local detection quickly, and send sustained waits to the global service after a configurable threshold. Periodic snapshots repair dropped events. Avoid holding a lock manager's internal mutex while calling remote services. The detector is advisory: losing its memory affects recovery speed, not whether committed writes remain atomic.
4. Show why a collected cycle can be false
Consider two attempts that already hold X and Y respectively:
- A requests Y and waits for B. The detector records A → B.
- A cancels that pending request and resumes other work while retaining X. The edge-removal event is delayed.
- B now requests X and waits for A. B → A reaches the detector.
The cached graph contains A → B → A, but there was no instant with both waits active. This example does not depend on transaction-ID reuse or releasing an acquired write lock. Out-of-order addition events can recreate the same problem unless removals carry versions.
Re-read each candidate edge from its authoritative lock manager with the expected request generation and holder identity. Reject changed or missing edges. However, sequential successful rechecks are not by themselves a proof of a simultaneous global snapshot: an earlier checked edge could change before a later check.
For this design, explicitly allow occasional unnecessary aborts of still-active, abortable attempts. Label the result a suspected cycle and measure rejected checks and suspected false positives. If the requirement forbids false deadlock diagnoses, the design needs an additional proven synchronization protocol or stronger monotonic-wait assumptions. Attaching timestamps or doing a second scan is not that proof.
5. Make an abort request safe and idempotent
Choose an abortable victim using estimated rollback cost, priority and previous victim count. Treat these as policy inputs, not correctness arguments. Send an idempotency key derived from the victim attempt and detection identifier to its coordinator.
The coordinator serializes an abort request against commit processing. It can atomically change an eligible ACTIVE state to an abort decision; a duplicate returns that same decision. If the commit protocol has progressed beyond the abortable boundary, reject the request or consult the durable protocol state. Do not overwrite a committed result or assume a participant can unilaterally abort a prepared transaction.
Participants release locks according to the transaction protocol after learning the authoritative decision and performing required rollback. The detector never directly deletes remote locks. If a coordinator is unavailable, recover its decision authority using the database's existing recovery mechanism. Killing a process cannot substitute for resolving an in-doubt transaction.
Two detectors may concurrently request different victims. The protocol must remain safe even if both eligible attempts abort. Leader leases reduce redundant work, but safety should follow from per-attempt decision serialization. An old detector request cannot abort a newly retried generation.
6. Budget graph work and recovery latency
Suppose 20% of the 50,000 active attempts are waiting, each with one blocker. The graph contains at most 50,000 vertices and 10,000 wait edges under these assumptions.
edge payload estimate = 10,000 × 96 bytes = 960,000 bytes ≈ 0.96 MB edge snapshot transfer every 2 seconds ≈ 0.48 MB/s 20,000 edge transitions/s × 96 bytes ≈ 1.92 MB/s
The transition rate is a separate hypothetical workload assumption, not derived from the number of waiting attempts. Payload estimates omit indexing, queues, serialization, replication and transport. A graph traversal is O(V + E); scanning five times per second corresponds to about 300,000 vertex-plus-edge visits per second, before implementation overhead. Measure CPU and allocation costs before choosing a larger architecture.
For an illustrative healthy-path budget: a 200 ms wait threshold, 100 ms event delivery, up to 200 ms until the next scan, 80 ms parallel validation and decision processing, and 120 ms participant cleanup total 700 ms. This is an additive planning estimate, not a percentile guarantee. Partitions, event gaps, queueing and coordinator recovery can make it much longer.
Full snapshots may use less bandwidth than a high-churn event stream, but they add delay and still do not establish a consistent global snapshot. A hybrid design trades earlier hints against periodic repair. Sharding the detector requires preserving cross-shard cycles; hashing edges independently is insufficient.
7. Recover without creating a retry storm
- Graph service fails: reconstruct from snapshots and resume detection. Keep bounded transaction deadlines as a separate policy, coordinated through transaction authority.
- Events lag: expose partition sequence lag and snapshot age; do not advertise complete coverage with missing partitions.
- One attempt is repeatedly chosen: incorporate aging or retry history into victim policy and cap total attempts.
- Clients retry immediately: use bounded exponential backoff with jitter. Preserve a stable business idempotency key while creating a new database attempt identity.
- Side effects occur outside the transaction: use an appropriate outbox or idempotent external workflow. Retrying the database transaction does not undo an email or external payment.
- The graph has no cycle: inspect hot locks, long-running holders, prepared transactions and unavailable coordinators rather than blaming deadlock detection.
Monitor wait duration, suspected cycles, validation rejection rate, abort acceptance, lock-release latency, retry exhaustion and transaction age. Page on sustained loss of detection coverage or blocked transactions, not every recovered cycle.
8. Compare prevention and detection
A consistent resource acquisition order can prevent the circular-wait pattern, but dynamic resource discovery and lock upgrades complicate enforcement. Requesting all locks upfront can reduce flexibility and increase lock footprint. Timestamp-based prevention can avoid certain waits but trades waiting for aborts and requires explicit priority semantics. Optimistic concurrency removes some lock waits but can turn contention into validation failures.
Choose detection when dynamic access patterns justify it and the database can safely abort attempts. Keep transaction scopes short. Start by understanding which waits the database already detects; do not install a second abort authority beside an existing transaction manager.
Follow-ups and self-review
How do shared locks and lock upgrades change the graph? What if an attempt can wait on any of several replicas? Can you construct a stale cycle without reusing an ID? What happens when an abort races with preparation? How would you demonstrate bounded starvation or measure unnecessary aborts?
A strong answer constructs the actual cycle, gives global attempt identities and explains versioned edge updates. An excellent answer distinguishes suspicion from proof, preserves commit authority, budgets detector work and defends recovery under message delay. A solution that simply kills a lock holder or assumes all sequential observations were simultaneous fails the correctness review.
Deadlock, starvation, or simply slow?
Suppose A waits for B, B waits for C, and C is doing a slow write but waits for no lock. The graph has no cycle. Killing C because a deadline expired may be an operational timeout policy, but it is not proof of deadlock. If C also waits for A, the graph now has the cycle A → B → C → A.
Next, suppose A is repeatedly chosen as the victim and retried. Each detected cycle may be resolved correctly while A still starves. Track retries by logical transaction, not just by attempt ID; use backoff, age-aware victim selection where safe, or admission control to reduce repeated conflicts. These policies improve fairness but cannot promise completion under arbitrary failures.
Interview check: name the evidence for a cycle, the authority allowed to abort, and the separate fairness policy. An abort proposal must never directly erase another coordinator’s locks or resolve an in-doubt prepared transaction.
Sources and attribution
- PostgreSQL 17: explicit locking and deadlocks — local deadlock handling, consistent lock order and retry context; exact page publication date unstated.
- PostgreSQL wiki: distributed deadlock detection project — a project proposal discussing remote dependencies and changing local wait graphs. It describes a separate PostgreSQL 14 branch, not a claim that upstream PostgreSQL provides this complete design. Exact publication date unstated.
Retrieved September 27, 2026. The three-partition example, cancellation timeline, event protocol, numerical budget and explicit false-positive policy are original design exercises. Neither source establishes a recently asked company interview question.
Continue your preparation
Choose a connected learning path or browse more System design questions. Read our editorial method and attribution policy.