Key takeaways
- ✓A deadlock is two transactions each holding a lock the other needs. Neither can ever move. Postgres checks for one only after a transaction has waited 1 s (its default), then aborts one of them, which gets a “deadlock detected” error and must retry.
- ✓Both sides pay. Played exactly, 5 times out of 5: one victim, and both the victim and the survivor waited about 1,003 ms.
- ✓A deadlock doesn't lose money, it costs time. 16 clients making transfers among 50 accounts, locking the sender's row first: 26 deadlocks in 20 s, money correct, 342 transfers a second, and a p99 of 1,015 ms. Transfers that never deadlocked had a 1,009 ms p99 too: they queued behind the locked rows.
- ✓Checking sooner (after 50 ms) made each deadlock cheaper, but they went from 26 to 114 because 5.3× as many transfers ran. It treats the symptom.
- ✓The fix is one lock order everywhere: lowest account number first. 0 deadlocks and 2,238 transfers a second, 6.5× the sender-first order. Written as one UPDATE per account, the same change gave 9.4× (310 → 2,916).
- ✓A request that holds a pooled connection and asks the same pool for a second one can hang the service. With a pool of 10: 9 requests at once all finished, 10 never did. No error came back, and a check that doesn't touch the database answered OK in 36 ms.
- ✓A timeout on getting a connection turns the hang into visible errors, but isn't a fix: 32 finished and 118 failed with 503 (79% of the answers). One connection per request ran 450 a second with 20 clients and 454 with 50.
Some work never fails; it waits. This chapter is about two ways that happens. The first is in the database: bank transfers that were always correct, but where the slowest one in a hundred took a full second. The second is inside the service: 9 requests at once worked, 10 never finished, no request got an error, and a check said the service was fine. Both are deadlocks: work waiting for other work that is waiting for it. Each has a measured cost and a fix that removes it.
The examples come from Lab 05 (Concurrency, Locks and Deadlocks) of the system design labs, scripts 02_deadlocks.py (one deadlock played step by step, then deadlocks under load) and 05_pool_deadlock.py (a connection pool that waits for itself). The same lab's scripts on race conditions, lost updates, isolation levels and the hot row (01, 03 and 04) are Chapter 8, which also introduces the tiny bank used here. Script 06, a Redis lock with a lease and fencing tokens, isn't covered in either chapter. The setup is the same laptop as before (an Apple M4 Max; Docker Desktop with 16 virtual CPUs): Postgres 18.6 in Docker, and the lab's small Python web service (FastAPI) next to it. The lab's 376 unit tests, which check its test harness and metric code, run in a few seconds without a database; they all pass. Other work kept the laptop busy during the runs (a load average, the number of processes wanting a core, of about 18 when the deadlock results were saved and 23 for the pool results), so read the shapes, not the last digit.
The workshop: locks in a transfer
A transfer moves money from one account (the sender) to another (the receiver). Each account is one row in Postgres. To stay correct, the transfer locks both rows until it's done, so nobody else can change them meanwhile. In SQL that's SELECT … FOR UPDATE: read the row and lock it; anyone else who wants to change or lock that row waits until this transaction commits (saves its changes and lets go of its locks). Chapter 8 measured why the lock is needed: without it, concurrent transfers lose money.
The lab's transfer took its locks one row at a time, the sender's first:
for i in (src, dst): # sender first, then receiver
bal[i] = await conn.fetchval("SELECT balance FROM accounts WHERE id = $1 FOR UPDATE", i)
Think of a workshop. Each account is a tool that only one worker can hold. A transfer is a worker that needs two tools at the same time. Postgres is the supervisor.
One deadlock, played exactly
Two transfers start at the same moment. Worker A moves money from account 1 to 2; worker B from 2 to 1. A picks up tool 1, B picks up tool 2. Now A waits for tool 2 and B waits for tool 1. Neither can ever move. That's a deadlock: a circle of transactions, each waiting for a lock that the next one holds.
Postgres doesn't look for this right away. A transaction that has waited for a lock longer than the setting deadlock_timeout (1 s by default) runs Postgres's deadlock check, which looks for a circle of waiting. If it finds one, it aborts one transaction, the victim. The victim's code gets an error and has to try again:
deadlock detected
DETAIL: Process 6842 waits for ShareLock on transaction 997016; blocked by process 6840.
Process 6840 waits for ShareLock on transaction 997015; blocked by process 6842.
The script played this exact interleaving: each side locks its first row (here with an UPDATE, which takes the same row lock), both wait until the other has done so, then each asks for the other's row. Five times for each of three deadlock_timeout settings:
| Check after | Runs with exactly one victim | Victim waited | Survivor waited |
|---|---|---|---|
| 1 s (default) | 5/5 | 1,003 ms | 1,003 ms |
| 200 ms | 5/5 | 204 ms | 204 ms |
| 50 ms | 5/5 | 53 ms | 53 ms |
Medians of 5 runs. The survivor, the one that went on to commit, waited just as long as the victim. Until the check runs, both hold their locks, and anything else that needs those rows waits behind them.
Worker A moves money from account 1 to account 2; worker B, at the same moment, from 2 to 1. Each locks the sender's row first.
Recorded: the sender-first deadlock, 5 runs per setting · deadlock_timeout
Medians of 5 runs. The picture is a diagram of the script's exact interleaving (each side locks its first row, both wait at a barrier, then each asks for the other's row); the times are measured. The lowest-number-first order wasn't played one-on-one; under load it had 0 deadlocks (next widget).
Under load: a deadlock costs time, not money
Now the lab ran it under load: 16 clients, each sending transfer after transfer (a closed loop, as in Chapter 5) between random pairs of 50 accounts, for 20 seconds. A transfer that hits a deadlock is retried. After each run the script checked the money: the total unchanged, no negative balance, and every balance matching the ledger of transfers.
| Lock order | Check after | Deadlocks | Money correct | Transfers a second | p99 | p99, never deadlocked |
|---|---|---|---|---|---|---|
| Sender first | 1 s | 26 | yes | 342 | 1,015 ms | 1,009 ms |
| Sender first | 50 ms | 114 | yes | 1,806 | 66 ms | 61 ms |
| Lowest number first | 1 s | 0 | yes | 2,238 | 38 ms | 38 ms |
The p99 is the latency 99% of transfers came in under: the slowest one in a hundred. "Deadlocks" is Postgres's own count (from its statistics view pg_stat_database), and it matched the number of deadlock retries the test harness counted, exactly, in every run.
With the sender's row locked first: 26 deadlocks, and the money still came out right. A deadlock doesn't corrupt anything; the victim is rolled back and retried. It costs time: 342 transfers a second, and a p99 of 1,015 ms. The transfers that hit a deadlock took a median of 1,025 ms, about the 1 s check plus the retry.
The surprise is the last column. Transfers that never deadlocked had a p99 of 1,009 ms too. Some arithmetic shows why: 26 deadlocks, each lasting about 1 s, in about 20 s of running, is 1.3 deadlock-seconds per second. On average about one deadlock was going on at any moment, holding two rows. With 16 clients on 50 accounts, plenty of other transfers soon needed one of those rows, and waited behind it. (That "about one" is an average worked out from the counts, not something the lab measured directly.)
Lock rows first (SELECT … FOR UPDATE)
One UPDATE per account, no read
Transfers a second, all five runs
26 deadlocks × 1 s each ÷ 20.0 s ≈ 1.3: on average about one deadlock was in progress at any moment, holding two rows that other transfers needed. That's why even transfers that never deadlocked had a p99 of 1,009 ms.
Each client sends transfer after transfer among 50 accounts; a transfer that deadlocks is retried. One run per row; the money (total, no negative balance, balances match the ledger) was correct in all five. Deadlocks are Postgres's own count, which matched the harness's retries exactly. The “in progress” figure is arithmetic, an average, not a measurement.
Check sooner?
If each deadlock costs one deadlock_timeout, why not check sooner? With the check after 50 ms, each deadlock got cheaper: 1,806 transfers a second and a 66 ms p99.
But deadlocks went up, from 26 to 114. More transfers ran (36,153 against 6,852, 5.3× as many), so more of them collided. Per transfer, deadlocks were in fact a little rarer: 0.32% against 0.38%. Checking sooner treats the symptom. The cause is still there, and every lock wait longer than 50 ms, deadlock or not, now runs the check.
The fix: one lock order
The fix is to lock both rows in one query, in a fixed order:
SELECT id, balance FROM accounts WHERE id = ANY($1::int[]) ORDER BY id FOR UPDATE
ORDER BY id means the lowest account number is locked first, every time, whichever way the money goes. In the workshop: before, A picks up tool 1 then 2, and B picks up 2 then 1; they cross. After, both reach for tool 1 first. B waits for it, holding nothing, then gets both. Whoever holds tool 1 can always get tool 2, because nobody holds a higher number while waiting for a lower one. Transfers still wait for each other, but in a line, never in a circle.
The same test, lowest number first: 0 deadlocks, 2,238 transfers a second, 6.5× the sender-first order, with a p99 of 38 ms.
The lab ran one more version: the transfer written as one UPDATE per account (balance = balance − amount on the sender, + amount on the receiver), with no read first; the lab calls it the atomic update (Chapter 8). It still takes two row locks, in whatever order the code runs the two statements, so it still deadlocks when the sender goes first:
| One UPDATE per account | Deadlocks | Transfers a second | p99 |
|---|---|---|---|
| Sender first | 26 | 310 | 1,011 ms |
| Lowest number first | 0 | 2,916 | 25 ms |
9.4× faster with the order fixed. Here the order comes from sorting the two account numbers in the code before running the two statements.
Ten workbenches
Same workshop, a new problem. Forget the tools. Now each worker is a web request, and the service has ten workbenches: ten database connections, kept open and shared between requests. A set of shared connections is a connection pool; a request acquires (borrows) a connection, uses it, and gives it back.
The lab's endpoint /pool/nested (one URL of the service) takes a connection from a pool of 10, does its work, then, still holding the first connection, borrows a second one to write an audit note. Simplified from the service's code:
async with p.acquire() as conn: # borrow a connection
async with conn.transaction():
await conn.execute("SELECT pg_sleep($1)", hold_ms / 1000) # the request's work
async with p.acquire() as audit_conn: # a SECOND connection, first still held
await audit_conn.execute("INSERT INTO audit DEFAULT VALUES")
pg_sleep stands in for the request's real work (50 ms in the first test, 20 ms in the second). The audit note goes on its own connection so it's saved in its own transaction, even if the main work is rolled back. That's a common, reasonable-sounding pattern.
The script sent c requests at the same moment and gave each 5 seconds to answer:
| Requests at once | Finished in 5 s | Idle connections after 1 s | A check without the database, meanwhile |
|---|---|---|---|
| 1, 5, 9 | all | 10 | 200 OK, 1–10 ms |
| 10 | 0 | 0 | 200 OK, 36 ms |
| 11, 20, 50 | 0 | 0 | 200 OK, 3–125 ms |
With 9 at once, one bench is still free. Someone gets a second bench, finishes, and frees two, and the rest follow. With 10, none finished, and nothing in the code would ever free them: every bench is held by a request waiting for a second bench. It's a deadlock too, only inside the service. Eleven, twenty, fifty: the same. The limit is exactly the pool size.
Requests sent at the same moment
Nine at once: one bench is still free. Someone gets a second bench, finishes, and frees two, and the rest follow. All 9 finished; one more request and none would.
Each request to /pool/nested takes a connection (a bench), does 50 ms of work, then asks the same pool for a second connection to write an audit note. The picture is a diagram of the moment every request has its first bench, when they all start together; the four numbers are recorded. “Errors returned” counts HTTP errors: none, the requests just never answered.
It looks healthy
During the hang, the service's /noop endpoint (it answers without touching the database) returned 200 OK, in 36 ms at 10 requests. No request got an error back; every request was just waiting. From outside it looks like a slow dependency, not a bug in this service.
And Postgres's deadlock check had nothing to find: no transaction was waiting for a row lock. Going by the code, Postgres would see ten connections sitting idle in the middle of a transaction (the lab didn't query Postgres during the hang to show it). The waiting is in the service's pool, where the database can't see it.
Give up after a second?
The next test kept the load on: clients in a loop for 15 seconds, each sending its next request as soon as the last one ended. A client gives up on a request after 5 seconds and sends another. Then the pool got an acquire timeout: a request that waits more than 1 s for a connection gives up, and the service answers 503 (the HTTP status for "service unavailable"). It's the pool's version of the supervisor sending a worker home.
| Endpoint | Clients | Finished | Finished a second | 503 errors | Given up after 5 s |
|---|---|---|---|---|---|
| nested | 5 | 3,113 | 208 | 0 | 0 |
| nested | 9 | 4,134 | 276 | 0 | 0 |
| nested | 10 | 0 | 0 | 0 | 30 |
| nested | 20 | 0 | 0 | 0 | 60 |
| nested, 1 s acquire timeout | 10 | 32 | 2 | 118 | 0 |
| nested, 1 s acquire timeout | 20 | 34 | 2 | 266 | 0 |
| flat (one connection) | 20 | 6,755 | 450 | 0 | 0 |
| flat (one connection) | 50 | 6,803 | 454 | 0 | 0 |
With 10 clients and no timeout, nothing finished in 15 seconds: each of the 10 gave up three times (30), and the next requests hung again. With the timeout, the hang turned into errors you can see and alert on: 118 of them. But only 32 requests finished; 118 of the 150 answers were errors, 79% (89% with 20 clients). The lab's explanation: the stuck requests time out together, and the next ones grab every connection and collide again. A timeout doesn't remove the trap. It only stops the waiting.
One bench is enough
The fix is to write the audit note on the same connection, right after the work, in its own transaction on that connection. The lab's /pool/flat does exactly that: one bench per request. With 20 clients it ran 450 requests a second; with 50, 454. With one bench each, nobody waits for a second one, so it can't get stuck this way. (Tested at 20 and 50 clients.)
450 a second is the pool's limit. By Little's law (Chapter 1), 10 connections all busy at 450 a second means each request holds one for 10 ÷ 450 ≈ 22 ms: the 20 ms of work plus a little overhead. If the inner work really needs its own connection, give it a separate pool, so a request never waits on the pool it's holding.
The same trap appears with thread pools: a task that waits for a subtask queued in the same pool. The lab's third exercise used a pool of 4 threads. With 1 or 3 parent tasks, none got stuck; with 4, 5 and 8 parents, the pool stalled until a 1 s timeout fired (1, 2 and 5 parents timed out). With the subtasks in their own pool, none got stuck.
Caveats
- One run per row, on a busy laptop. Every load figure is a single run, with a load average of 18–36 while the results were saved. The ratios (6.5×, 9.4×) are large enough to survive that noise; the last digit isn't.
- "About one deadlock at any moment" is arithmetic, an average from the counts (26 × 1 s ÷ 20 s), not a measurement.
- The 50 ms run shows what the setting does, not a recommendation. A slightly shorter check can help the victims, but it runs on every lock wait that long, and it leaves the cause in place.
- What Postgres saw during the pool hang wasn't measured. The lab recorded the service's pool (0 idle connections),
/noop, and the client side. That the database sees idle connections and no lock wait follows from the code. - "It can't get stuck" is about this trap. The flat version was tested at 20 and 50 clients; it removes the nested acquire, not every way a pool can run out.
- The hang appeared at once because the requests started together. The lab notes that clients starting at different times run until, by chance, every connection is held by a waiter at the same moment. Staggered traffic hangs later, not never.
The checklist
- Take locks in one fixed order everywhere. Lowest id first, in one query (
ORDER BY id FOR UPDATE) or by sorting the ids in the code. Check every code path that locks the same rows. - Count deadlocks. Postgres keeps a counter per database; alert on it. A deadlock that's retried looks like a slow request, not an error.
- Don't treat the delay as the fix. A shorter deadlock check makes each deadlock cheaper; only the lock order removes them.
- Never hold one connection while waiting for another from the same pool. Look for helpers that open their own connection or session, and "separate transaction" writes for audit or outbox. Use the connection you hold, or a separate pool. Thread pools have the same trap.
- Test at the pool size. Send exactly as many requests at once as the pool has connections, and one fewer. A hang that appears at exactly the pool size points to a nested acquire.
- Add timeouts, so a hang becomes an error you can see. An acquire timeout and lock timeouts turn silent waiting into errors and alerts. Then fix the cause.
- Watch the pool, not just the database. Connections in use, idle, and requests waiting; when it's stuck, every stuck request will be at an acquire.
Practice: find the cycle
Write the lab's logic: the order a transfer locks its rows in, a check for a circle of waiting (what Postgres's deadlock check looks for), what a deadlock costs under load, when a pool can hang, and a small model of the burst test. The tests use the recorded runs: two transfers crossing in request order and not in id order, 1.3 deadlocks in progress on average, 6.5× and 9.4× for the fixed order, a pool of 10 that hangs at exactly 10, 79% errors with the timeout, and about 22 ms per request on the flat version.
Quiz
1.Transfer A moves money from account 1 to 2 and locks the sender's row first; transfer B, at the same moment, moves money from 2 to 1 the same way. What happens?
2.In a deadlock with Postgres's default 1 s check, how long does the transaction that survives wait?
3.Under load, 26 deadlocks in 20 s pushed the p99 of transfers that never deadlocked to 1,009 ms. Why were they slow?
4.Lowering the deadlock check from 1 s to 50 ms raised throughput from 342 to 1,806 transfers a second. Why isn't that the fix?
5.Why does locking the lowest account number first make a deadlock impossible between transfers?
6.A service with a pool of 10 database connections hangs at 10 requests at once, returns no errors, and a check that doesn't use the database says OK. What's the most likely cause?
Check your understanding
Try each question before opening its answer.
What is a deadlock, and what does Postgres do about one?
Two or more transactions each hold a lock the next one needs, in a circle, so none can move. Postgres checks for such a circle only after a transaction has waited a set time (1 s by default). Then it aborts one, which gets a “deadlock detected” error and must retry. In the lab, 5 runs out of 5 ended with exactly one victim.
A deadlock is detected after 1 s and one side is retried. Who paid, and how much?
Both sides: the victim and the survivor each waited about 1,003 ms. So did everything that needed their rows. Under load that meant transfers that never deadlocked had a 1,009 ms p99, with about one deadlock going on at any moment on average.
Your transfer locks the sender's row, then the receiver's. How do you remove the deadlocks?
Lock both rows in one fixed order, lowest account number first: one query with ORDER BY id and FOR UPDATE, or sort the two ids before locking. Nobody then holds a higher number while waiting for a lower one, so no circle can form. In the lab: 0 deadlocks and 2,238 transfers a second against 342 (6.5×); written as one UPDATE per account, 9.4×.
Why didn't checking for deadlocks after 50 ms instead of 1 s solve the problem?
Each deadlock got cheaper, so more transfers ran (36,153 against 6,852) and more collided: 114 deadlocks against 26, though a bit rarer per transfer (0.32% against 0.38%). The cause, two orders of locking, was untouched.
A service with a pool of 10 connections works with 9 requests at once and hangs with 10. No errors, the database looks idle. What's happening?
Each request holds one connection and asks the same pool for a second. With 10 at once, all 10 connections are held by requests waiting for another, and none will ever be free. Postgres sees no lock wait, so its deadlock check has nothing to find, and a check that doesn't use the database still answers OK (36 ms in the lab).
Is an acquire timeout on the pool the fix?
No. It turns the hang into 503 errors you can see and alert on, which is worth having. But the trap stays: with 10 clients only 32 requests finished and 118 of 150 answers were errors (79%). The fix is one connection per request (the flat version did 450 a second with 20 clients and 454 with 50), or a separate pool for the inner work.
Next up: Chapter 10, retries and idempotency: so far every request came from a client on the same machine and was retried only inside the database. The next chapter puts a network API in front, where a client retries after a timeout, and shows how idempotency keys and deadlines keep a retry from charging twice.