Database Concurrency & Scaling interview question · Most asked
After a deploy, logs show hundreds of 'deadlock detected' errors per hour on checkout. Walk through how you'd investigate.
Summary
Read the deadlock reports to find the two statements and tables involved, map them to the two code paths, and compare their lock order. Usually a new code path locks the same rows in a different order (or holds locks longer); fix the ordering and keep a retry for the remainder.
Longer Answer
- Get the report: Postgres logs
deadlock detectedwithProcess X waits for ShareLock on transaction Y; blocked by process Zand each blocked query; MySQL showsLATEST DETECTED DEADLOCKinSHOW ENGINE INNODB STATUS(enableinnodb_print_all_deadlocks). - Remember the queries shown are the ones that were blocked; the conflicting locks were taken earlier in the same transactions.
- Correlate with the deploy: which new code touches those tables? A loop over cart lines in customer order, a new FK insert, a longer transaction with an HTTP call inside.
- Fix: lock rows in a deterministic order (sort ids), shorten transactions, add missing indexes (fewer rows locked), move external calls out.
- Keep a retry for deadlock errors (40P01 / 1213) — but only once the transaction body is side-effect free.
Key Points
- Read the database's deadlock report
- Find both code paths and compare lock order
- Deterministic lock order + short transactions
- Retry as a safety net, not the fix
Deep dive: Reading Deadlock Reports
More most-asked Database Concurrency & Scaling questions
- How do you prevent overselling in a flash sale with 50,000 buyers in the first minute?
- Two customers buy the last item at the same moment and both orders are confirmed. What happened, and how do you prevent it?
- Your service throws 'connection pool exhausted' errors but database CPU is only 20%. What's going on?
- Why shouldn't you call a payment API inside a database transaction?
- What's the difference between Read Committed and Repeatable Read in practice?
- Database CPU is at 85%. How do you decide what to optimise before buying a bigger server?
- A user saves their profile and the next page shows the old data. Reads go to replicas. How do you fix it?
- How do you choose a shard key for a multi-tenant SaaS?