Two transfers, stuck forever
An app for friends splitting bills: 4,000 req/s, and 30% are transfers. Friends often pay each other back at the same moment, and every so often a transfer fails with "deadlock detected".
Play this levelFree with an account. It runs in your browser: build the design, press Run, and watch what breaks.
The lesson
A transfer locks two rows: the sender's and the receiver's. This app locks the sender first. Ana paying Ben locks Ana, then waits for Ben. Ben paying Ana at the same moment locks Ben, then waits for Ana.
Each holds the row the other needs, so neither can ever finish. That's a deadlock. The database spots the cycle after about a second, kills one transaction, and that person sees an error.
The fix costs nothing: always lock rows in the same order, such as the lower account number first. Both transfers now queue for the same first row, and one simply waits a moment for the other.
Retrying a killed transfer works too, but it only hides the problem. A fixed order makes the cycle impossible.
What you have to achieve
4,000 requests a second at the busiest hour, 30% of them writes.
- No broken or illegal connections
- No two transfers wait on each other forever
- No component is overloaded
- Fewer than 0.1% of requests fail
What you learn
Same machines, same speed, and no more stuck transfers. Deadlocks come from the order of your code's steps, not from load, so no amount of hardware fixes them.
Check yourself
Ana pays Ben while Ben pays Ana, and each transfer locks its sender first. What happens?
- Both go through
- Each waits for the other's row until the database kills one
- The second waits a moment, then goes through
Show the answer
Each waits for the other's row until the database kills one. Each transfer holds one row and waits for the other. Neither can finish, so the database has to pick one to fail.
Which change makes this deadlock impossible?
- A bigger database
- Lock both rows in the same order every time
- Retry failed transfers
Show the answer
Lock both rows in the same order every time. With one order, both transfers want the same row first, so one waits and no cycle can form. Retrying only cleans up after a deadlock.