DEV Community

Cover image for Deadlocks Explained: When Two Transactions Wait for Each Other Forever
Abdeldjalil Chougui
Abdeldjalil Chougui

Posted on Originally published at abdeldjalilchougui.biz

Deadlocks Explained: When Two Transactions Wait for Each Other Forever

Your logs show an error you have never seen in testing: deadlock detected in PostgreSQL, or Deadlock found when trying to get lock; try restarting transaction in MySQL. It happens a few times a day, under load, and never when you try to reproduce it. That is the typical shape of a deadlock.

What a deadlock is

A deadlock is a cycle of waiting. Transaction A holds a lock that B needs, and B holds a lock that A needs. Neither can continue, and neither will release its lock until it continues. Without outside help, they would wait forever.

The classic example is a money transfer.

  • Transaction A moves money from account 1 to account 2.
  • Transaction B moves money from account 2 to account 1, at the same moment.
-- Transaction A                          -- Transaction B
BEGIN;                                    BEGIN;
UPDATE accounts SET balance = balance - 50
WHERE id = 1;     -- locks row 1
                                          UPDATE accounts SET balance = balance - 20
                                          WHERE id = 2;     -- locks row 2
UPDATE accounts SET balance = balance + 50
WHERE id = 2;     -- waits for B
                                          UPDATE accounts SET balance = balance + 20
                                          WHERE id = 1;     -- waits for A: deadlock
Enter fullscreen mode Exit fullscreen mode

Step by step:

  1. A updates row 1 and takes its lock.
  2. B updates row 2 and takes its lock.
  3. A tries to update row 2 and waits for B.
  4. B tries to update row 1 and waits for A.

Now A waits for B and B waits for A. That is the cycle.

The four conditions

A deadlock needs four things at once (known as the Coffman conditions):

  1. Mutual exclusion: a resource, such as a row lock, can be held by only one transaction at a time.
  2. Hold and wait: a transaction holds one lock while waiting for another.
  3. No preemption: the database does not take a lock away from a running transaction.
  4. Circular wait: there is a cycle of transactions each waiting for the next.

Databases need the first three to keep data correct, so in practice the prevention work is on the fourth: avoid cycles.

How databases deal with it

Relational databases do not let a deadlock last forever. They run a deadlock detector. It builds a "waits-for" graph (A waits for B, B waits for A) and looks for cycles.

  • In PostgreSQL, a transaction that has waited for a lock longer than deadlock_timeout (one second by default) triggers a check.
  • MySQL InnoDB detects deadlocks as soon as a lock wait creates a cycle, by default.
  • SQL Server runs a background monitor that checks periodically.

When a cycle is found, the database picks one transaction as the victim, aborts it with an error, and releases its locks. The other transaction continues and commits. The victim's work is rolled back completely.

So a deadlock is not data corruption. It is one failed transaction that your application must handle, usually by retrying it.

Reading the evidence

Each database can tell you what happened:

  • PostgreSQL logs the error with the two processes and the statements involved. Turning on log_lock_waits also logs long lock waits.
  • MySQL shows the latest deadlock in SHOW ENGINE INNODB STATUS, and innodb_print_all_deadlocks writes all of them to the error log.
  • SQL Server records deadlock graphs in its built-in system_health Extended Events session.

Look for the two statements and the order in which they took locks. The fix almost always comes from that order.

How to prevent deadlocks

1. Lock in a consistent order

This is the most effective rule. If every transaction locks rows in the same order, a cycle cannot form. For the transfer, always lock the account with the lower ID first:

BEGIN;
SELECT id FROM accounts WHERE id IN (1, 2) ORDER BY id FOR UPDATE;
UPDATE accounts SET balance = balance - 50 WHERE id = 1;
UPDATE accounts SET balance = balance + 50 WHERE id = 2;
COMMIT;
Enter fullscreen mode Exit fullscreen mode

Now A and B both try to lock account 1 first. One wins, the other waits, and there is no cycle. The same applies to tables: if code touches orders and inventory, always in that order.

2. Keep transactions short

The longer a transaction holds locks, the more chances another transaction collides with it. Do not call external APIs, send emails or wait for user input inside a transaction. Prepare everything first, then open the transaction, write, and commit.

3. Touch fewer rows

An UPDATE without a good index may scan and lock many more rows than it changes, especially in MySQL InnoDB, which locks the index ranges it scans. An index on the WHERE columns reduces the locked set and with it the chance of overlap.

4. Batch large updates

Updating a million rows in one statement holds a million locks. Doing it in chunks, each in its own short transaction, and in a consistent order (for example by primary key), keeps each lock set small.

5. Retry on deadlock

Even with good habits, deadlocks can still happen under load. Treat them as a normal, retryable error:

for attempt in 1..3:
    try:
        run the whole transaction
        break
    except DeadlockError:
        wait a short random time, then retry
Enter fullscreen mode Exit fullscreen mode

Retry the whole transaction, not only the last statement, because the database rolled everything back. Add a small random delay so the two transactions do not collide again immediately, and cap the number of attempts.

Deadlocks outside databases

The same idea applies to threads and mutexes in your code: thread 1 holds lock X and wants Y, thread 2 holds Y and wants X. The difference is that most programming languages do not detect it for you. The program simply hangs. The prevention rule is the same: always acquire locks in the same order, and hold them as briefly as possible.

Common mistakes

  • Treating a deadlock error as a bug in the database. It is the database protecting you from an endless wait.
  • Not retrying. The user sees an error for something that would have succeeded a millisecond later.
  • Retrying only the failed statement. The whole transaction was rolled back.
  • Long transactions that include network calls or slow processing.
  • Locking in the order the data arrives, for example in the order items appear in a shopping cart. Sort by ID first.
  • Raising lock timeouts to "fix" deadlocks. Timeouts do not break cycles; detection does.

Watch the animated version: https://youtu.be/TZsSkWJY3jI

In short

  • A deadlock is a cycle: each transaction holds a lock the other needs.
  • The database detects the cycle, aborts one transaction as the victim, and lets the other finish.
  • Prevent most deadlocks by locking in a consistent order, keeping transactions short and indexing your WHERE columns.
  • Handle the rest by retrying the whole transaction with a short random delay.

Originally published at abdeldjalilchougui.biz.

Top comments (0)