Two requests are slow. Each holds something the other needs. Adding workers only produces more waiting. In a senior or staff engineer interview, the useful next move is to identify the dependency cycle, explain who can break it, and show that recovery preserves the operation's meaning.

This guide treats deadlocks as a progress problem across database transactions, application locks, and connection pools. The examples and rehearsal rubric are illustrative practice material, not a description of any employer's assessment. Start with a small execution you can explain precisely; then extend it across ownership boundaries.

1. Draw the wait-for graph before proposing a fix

For an exclusive-lock example, draw an arrow from a blocked operation to the operation holding its requested resource. A cycle explains why the participants cannot finish through ordinary execution. PostgreSQL's deadlock documentation shows this with conflicting transactions and explains that its detector aborts one participant. The application must accept either participant as the victim.

An illustrative two-reservation schedule

Suppose a service moves reserved inventory between bins 12 and 47. Request A locks bin 12 and will next lock bin 47. Request B locks bin 47 and will next lock bin 12. Pause execution after both first locks have succeeded. A now waits for B, while B waits for A. Neither reaches its commit and release step. The problem exists even if both requests have correct arithmetic and sufficient inventory.

Write the sequence explicitly: A acquires 12; B acquires 47; A requests 47; B requests 12. This is a counterexample to the proposed locking protocol. It is more useful than saying that concurrency is difficult because it identifies both the failing interleaving and the resources a repair must cover.

Now change one fact. If B never needs bin 12 and eventually commits, A has a blocking dependency but this execution has no cycle. A long wait alone does not prove deadlock. During practice, distinguish that case from starvation, where a participant repeatedly loses opportunities to run, and livelock, where participants keep reacting without completing useful work. Each diagnosis needs evidence of how progress fails.

Ask what the arrows mean in the actual implementation. A lock request may conflict with a holder or wait behind another requester. PostgreSQL's pg_blocking_pids documentation distinguishes these hard and soft blockers. That detail matters when explaining why an apparently compatible request still waits in a queue.

2. Make acquisition order a shared protocol

For the bin example, choose a canonical order: compare immutable bin IDs, acquire the smaller ID first, then acquire the larger ID. Both transfer directions use that sequence. Preserve the original source and destination for business logic; sorting lock acquisition must not reverse the requested transfer. If both IDs are equal, validate or handle that case before requesting the same non-reentrant application lock twice.

The argument is specific: every operation in this protocol acquires bin locks in increasing order, so a cycle composed solely of those acquisitions would require the IDs to increase all the way back to the starting ID. That is impossible. This proves something about the stated protocol, rather than promising the entire service is deadlock-free.

PostgreSQL recommends consistent object ordering and acquiring the strongest needed lock mode first. Its guide also notes that ordinary row updates can deadlock without explicit locking statements. Enumerate every relevant path: transfers, cancellation, repair jobs, and administrative tools. An ordering convention followed only by the new endpoint is incomplete.

Lock modes and hidden acquisitions count

Consider two readers that both retain a read lock while requesting exclusive access. Naming only the object order misses the upgrade dependency. In Go, the RWMutex contract explicitly disallows upgrading a read lock to a write lock and warns against recursive read locking. If you release the read lock before acquiring write access, revalidate the state: another writer may have changed it in the gap.

Do not assume one SQL statement means one lock. The MySQL 8.4 deadlock guide explains that even single-row inserts or deletes can involve several index-record locks. It recommends short transactions, consistent operation order, and suitable indexes. In an interview, state the engine and access paths before extending an application-level proof to database internals.

For practice, add a bin-summary record to the design. If the transfer locks bins before their summary but the reconciliation job locks the summary before its bins, your earlier proof no longer covers the whole graph. Establish a resource-class hierarchy as well as an ID order within each class, or redesign the transaction boundary. Document the rule where callers can actually follow it.

3. Separate detection, timeout, and safe retry

A detector identifies a cycle within the resources it observes. A timeout limits waiting without establishing the cause. PostgreSQL's deadlock_timeout setting controls the delay before checking for deadlock; it is not a general lock-wait deadline. Lowering that setting changes detection overhead and timing, not the underlying acquisition protocol.

Explain the recovery contract separately from detection. PostgreSQL identifies deadlock failures with SQLSTATE 40P01. Its transaction retry guidance stresses retrying the complete transaction, including the logic that chose statements and values. For the reservation example, repeat the reads, availability checks, and updates together. Replaying only the final update can reuse decisions made against obsolete state.

Know what was rolled back

MySQL's InnoDB error-handling reference makes an important distinction: a deadlock rolls back the entire transaction, while a lock-wait timeout normally rolls back only the current statement unless rollback-on-timeout is enabled. A generic “retry any database error” helper hides that difference. Establish the transaction state and cleanup behavior before starting another attempt.

An illustrative retry policy could allow a small bounded number of attempts, apply randomized delay, and stop when the request's remaining deadline cannot support another transaction. Those are design choices to justify under load, not universal recommended constants. Release locks and the failed transaction's resources before waiting. Track attempts per logical operation so a good success rate does not conceal rapidly growing database work.

Keep irreversible effects outside a blindly replayed transaction body. If a mock transfer sends a notification before commit, a database rollback cannot unsend it. One design is to record an event in the same database transaction and deliver it afterward through a separate idempotent workflow. State that delivery needs its own duplicate-handling contract; database retry safety does not automatically make external effects safe.

Also distinguish an explicit deadlock rejection from losing the connection during commit. The latter does not establish whether the operation committed. In the practice design, give each logical transfer a stable identity and a way to inspect its recorded outcome before deciding what to repeat. Treat unknown outcomes as a separate recovery branch rather than assuming every failed response means rollback.

4. Follow dependencies beyond the database

A database detector cannot repair a cycle whose essential edges live in application code. Imagine worker A holding an application mutex while waiting for a SQL connection. Worker B holds the only available connection and calls code that needs the mutex before releasing it. The database may have no blocked SQL statement to diagnose. The cycle crosses two resource managers.

The Go project's connection-management guide explicitly warns that limiting open connections makes acquisition resemble a lock or semaphore and can deadlock an application. For this example, increasing the pool may hide the smallest reproduction while leaving the dependency pattern intact. Review whether a transaction-owning helper accidentally uses the general pool instead of the transaction's connection.

Extend the exercise to a bounded worker pool. A parent task occupies a worker, submits a child to the same fully occupied pool, and synchronously waits for it. If every worker is occupied by such a parent, no child can start. Draw workers as resources too. Possible repairs include doing the child work inline, restructuring dependencies, or scheduling parents without retaining scarce execution capacity while waiting.

Use evidence with a stated visibility boundary

For PostgreSQL, capture blockers, transaction age, operation identity, and query context. The pg_locks reference recommends pg_blocking_pids over a naive self-join because queue ordering and parallel workers complicate interpretation. It also describes snapshot limitations. A monitoring query is evidence about an observed moment, not a complete history of every acquisition.

For InnoDB, SHOW ENGINE INNODB STATUS exposes the latest deadlock; the all-deadlocks logging option can collect broader diagnostic evidence. Preserve enough context to compare recurring patterns, with sensitive values redacted. Separate deadlock counts from ordinary lock waits and retry exhaustion so the dashboard supports a specific decision.

Runtime diagnostics also have limits. Java 21's ThreadMXBean.findDeadlockedThreads detects cycles involving platform threads and supported monitor or ownable-synchronizer locks; it does not find cycles containing virtual threads. A clean result from that API does not prove a service has no progress failure. Combine runtime evidence with the resource graph your architecture actually uses.

5. Rehearse a counterexample, a repair, and a test

Use an illustrative thirty-minute rehearsal. Spend five minutes describing the operation and its invariant: a successful transfer changes both bins atomically and preserves total reserved inventory. Spend ten minutes drawing the failing schedule and repairing the lock protocol. Use the remaining time to explain recovery, instrumentation, and a test that could falsify your design.

Build the reproduction around explicit synchronization points rather than hopeful sleeps. Arrange for each participant to signal after acquiring its first resource. Then allow both to request their second resource. In an isolated database test, use separate connections and verify the expected deadlock outcome, rollback, and survivor completion. Always clean up both sessions even when an assertion fails.

After imposing canonical ordering, change the test coordination too. A barrier that requires both participants to hold different first locks is impossible under the repaired protocol and would manufacture a test-harness hang. Instead, pause the first participant after its first acquisition, start its competitor, verify that the competitor waits there, then release the first participant and require both operations to complete within the test deadline.

Check the business invariant after all attempts settle. Exercise reverse transfer directions, identical resource IDs, an aborted attempt, cancellation while waiting, and retry exhaustion. For the application-mutex and connection-pool example, reproduce with a deliberately tiny pool. These tests examine progress and cleanup under a controlled schedule; passing them does not prove every possible interleaving safe.

As a practice rubric, assess four things: whether you identified the complete dependency cycle, whether your ordering argument covers every participating path, whether recovery preserves transaction meaning, and whether diagnostics reveal the failure within their visibility limits. If an explanation lacks one of those pieces, rehearse that piece again. The goal is a design argument you can defend when the interviewer adds a new resource or changes the failure boundary.

Practice explaining concurrency failures

Use Interview Copilot to prepare technical explanations and rehearse follow-up questions. Start with the two-bin schedule, then practice defending lock order, transaction retries, and evidence from a blocked system.

Start practicing