Deadlock Interview Question: Find and Fix It in SQL

Checkout fails with "Deadlock found when trying to get lock". Read the wait graph, fix the lock order and add a safe retry, as asked in interviews.

In this chapter

Interview: checkout fails with “Deadlock found”

Deadlocks: common questions

How do you fix a database deadlock?

Lock rows in the same order in every transaction, keep transactions short, index the columns you lock by, and retry the transaction that the database rolled back.

More on Ticket interviews

Keep learning

Overview

UPDATE inventory … sku=42 T1 locks the inventory row. UPDATE wallets … user=7 T2 locks the wallet row. T1 needs the wallet. T2 has it. T1 waits. T2 needs inventory. T1 has it. A cycle. ERROR 1213 Deadlock → rolled back InnoDB finds the cycle at once and rolls back the smaller transaction (T2). COMMIT ✓ T1 finishes. T2’s refund must be retried by the app. T1 locks inventory first. T2 also starts with inventory, so it simply waits. It holds nothing. T1 takes the wallet. Nobody is in its way. T1 releases both locks. T2 continues. A short wait, no deadlock. Both succeed. inventory sku=42 wallets user=7 Lock wait-for graph Lock order Opposite order Same order T1 placeOrder T2 refundOrder Play step 1 Next step

Checkout fails with “Deadlock found”

row locks lock order isolation levels no-AI coding 0.5% of checkouts fail with ERROR 1213 at peak Order and refund lock two rows in opposite order One lock order, no I/O inside, retry the victim

Checkout randomly fails at peak

About 0.5% of checkouts fail at peak with ERROR 1213: “Deadlock found”. It started after the refunds feature launched. Customers retry, and it usually works. failed checkouts REPEATABLE READ Restated: two transactions wait on each other. MySQL kills one. The app does not retry.

Find every transaction that touches the same rows

Order: inventory, then wallet. Also sends an email inside the transaction. Order: wallet, then inventory. The opposite of placeOrder. INNODB STATUS SHOW ENGINE INNODB STATUS prints the last deadlock: who held what, and who waited for what. ① inventory → ② wallet ① wallet → ② inventory Same two rows, opposite order. That is all a deadlock needs.

Prove it, don’t guess

Deadlock (1213) or lock wait timeout (1205)? read the error code 1213: InnoDB found a cycle and killed one at once. A timeout would take 50 s by default. Which statements formed the cycle? SHOW ENGINE INNODB STATUS placeOrder holds inventory, wants the wallet. refundOrder holds the wallet, wants inventory. Is the lock order consistent across code paths? compare the two files No: inventory→wallet vs wallet→inventory. That is the cause. Are locks held longer than they need to be? look inside the transaction Yes. emailReceipt() makes a network call while holding both locks. Does the app retry a deadlock victim? search the code for 1213 No. The error goes straight to the user.

Three precise changes

Lock inventory always first Lock wallet always second locks released Send email after commit The fixed shape of every checkout and refund transaction. Two rows, two sessions, opposite order. The second wait closes the cycle. InnoDB rolls one session back at once. writes it without help explains which one is rolled back Would switching to READ COMMITTED fix it? REPEATABLE READ READ COMMITTED Row locks from UPDATE Gap locks on range scans This deadlock can happen No. UPDATE takes row locks at every isolation level. READ COMMITTED drops most gap locks (locks on the space between rows). That cuts range-scan and insert deadlocks, not this one. Cost: non-repeatable reads and phantoms inside a transaction. row locks vs gap locks names the anomaly it allows The UPDATE’s WHERE column has no index. What changes? locks + indexes No index Full scan → every row (and gap) gets locked. Index on the WHERE column Only the matching rows get locked. The write locks every row it scans: effectively the whole table. InnoDB locks the index records it reads, not just the matches. So an index also decides how many rows a write locks. locks follow the scan indexes shrink lock footprint Deadlock detection costs CPU. When does that matter? Detection ON (default) Victim picked at once. CPU grows with waiters. Detection OFF + short timeout Cheap. Victims wait out the timeout. When thousands of threads wait on one hot row. Each new wait runs a wait-for graph search (who waits on whom). Some systems set innodb_deadlock_detect=OFF and use a short lock timeout. Better: remove the hot row. Shard counters, batch, or queue writes. hot rows Is the retry safe? ERROR 1213 Full rollback 20ms·2ⁿ + jitter Replay whole tx max 3 tries Yes inside the database: the victim was fully rolled back. Outside, only if side effects happen after COMMIT. Cap retries and add jitter, or a burst becomes a retry storm. full rollback side effects after commit bounded retries

Peak sale in two hours. What do you ship?

Pick your fix. Consistent lock order + bounded retry Removes the cycle and catches rare leftovers. Small diff, easy to test before the sale. Risk to ship Retry forever, change nothing else Hides the bug. At peak, retries pile up and latency climbs for everyone. One global lock (GET_LOCK) around checkout No deadlocks, but checkout runs single-file. At peak that is an outage. Switch to READ COMMITTED Does not fix this row-lock cycle. It changes every read, so not a two-hour change.

“Tell me about a time your code crashed because of a deadlock.”

Tell me about a production deadlock you debugged. Error rate, endpoint, start time. INNODB STATUS and the two statements. Lock order, missing index, gap lock, or I/O. One order, short transactions, retry with jitter. Review checklist for lock order and side effects.

Did you show these?

Told 1213 (deadlock) from 1205 (timeout) Used INNODB STATUS, not guesses Fixed lock order in every code path Moved network I/O out of the transaction Bounded whole-transaction retry, with jitter Named deadlock types and Coffman conditions Wrote a deadlocking pair unaided Linked missing indexes to wider locks

More courses

  • Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
  • Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
  • React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
  • System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
  • NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
  • Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
  • Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
  • AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
  • Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
  • TypeScript in depth — The type system as a design tool. Inference, narrowing, generics, and the errors that mean the model is wrong — not a catalog of utility types.
  • CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
  • Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
  • Docker — What an image is, why layers cache, and how containers find each other on a network.
  • Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
  • Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
  • AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
  • Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.