What Is a Deadlock?

A deadlock occurs when two or more processes or threads are each waiting for a resource the other holds, so none of them can ever proceed.

Published October 7, 2026

A deadlock is when two or more processes each hold a resource the other needs and wait forever. Prevent it by acquiring locks in a consistent order, using timeouts or avoiding nested locks.

The concept

Four conditions must all hold: mutual exclusion, hold-and-wait, no preemption and circular wait. Break any one and deadlock cannot occur.

Databases detect deadlocks and abort one transaction; application locks usually do not, so the program just hangs.

Circular wait

A wants Lock 2 / B wants Lock 1Thread Aholds Lock 1Thread Bholds Lock 2
Each side waits for what the other holds.

Practical examples

The bug

# Thread A: with l1: with l2: ...
# Thread B: with l2: with l1: ...   # opposite order → deadlock

Fix: consistent order

for l in sorted([l1, l2], key=id): l.acquire()

MySQL: retry on deadlock

for (let i = 0; i < 3; i++) {
  try { return await runTx() } catch (e) { if (e.code !== 'ER_LOCK_DEADLOCK') throw e }
}

Use timeouts

if not lock.acquire(timeout=2): raise TimeoutError()

Common mistakes

  • Taking locks in different orders in different code paths.
  • Holding locks during slow I/O.
  • Not retrying aborted database transactions.

Key takeaways

  • Circular waiting freezes progress.
  • Lock in a fixed order.
  • Use timeouts and retries.

FAQ

Deadlock vs livelock?

In livelock the threads keep changing state without progressing.

How does a database resolve one?

It picks a victim transaction and rolls it back.

More General articles