SQL error · Locks and concurrency

Deadlock: two transactions block each other

Problem: There is a wait cycle: each transaction needs a resource locked by the other.

Solution: Access resources in a consistent order and set up a safe retry of the whole transaction.

Why it happens: two transactions block each other

Waiting on a lock is not, on its own, a deadlock. If transaction B waits for A and A can still finish, that is an ordinary wait. A deadlock happens when the dependency loops back on itself: A is waiting for something held by B while B is waiting for something held by A.

Two sessions, opposite order
-- Session A
BEGIN;
UPDATE orders SET status = 'processing' WHERE id = 1;
-- holds a lock on order 1
UPDATE orders SET status = 'processing' WHERE id = 2;

-- Session B, at the same time
BEGIN;
UPDATE orders SET status = 'processing' WHERE id = 2;
-- holds a lock on order 2
UPDATE orders SET status = 'processing' WHERE id = 1;

If A has already locked row 1 and B has already locked row 2, A may end up waiting for row 2 while B waits for row 1. An engine with deadlock detection breaks the cycle by aborting one of the transactions, so do not assume which one will “win”.

Key idea: the problem is not concurrency itself but different transactions acquiring shared resources in incompatible orders.

“Deadlock: two transactions block each other” error messages by engine

The exact wording depends on the database. Compare these common messages with the one in your console.

EngineTypical message
PostgreSQLERROR: deadlock detected (SQLSTATE 40P01)
MySQLERROR 1213 (40001): Deadlock found when trying to get lock; try restarting transaction
SQL ServerMsg 1205, Level 13: Transaction (Process ID 54) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.
OracleORA-00060: deadlock detected while waiting for resource

SQLite locks the whole database for writes: instead of a deadlock you will see “database is locked” (SQLITE_BUSY).

How to fix it in SQL

Main fix: use a consistent order

If two flows have to change the same resources, make them acquire those resources in the same order. In the example above, both transactions should process order 1 first and then order 2.

Consistent order
-- Session A
BEGIN;
UPDATE orders SET status = 'processing' WHERE id = 1;
UPDATE orders SET status = 'processing' WHERE id = 2;
COMMIT;

-- Session B: same access order
BEGIN;
UPDATE orders SET status = 'shipped' WHERE id = 1;
UPDATE orders SET status = 'shipped' WHERE id = 2;
COMMIT;

The second session may still have to wait, but it no longer creates the same dependency cycle. It also helps to keep transactions short, avoid pauses while they are open and touch only the rows you need.

After a deadlock: retry the whole transaction

When the engine aborts a transaction because of a deadlock, the application should treat that failure as recoverable whenever the operation is safe to retry. Blindly resending the last statement is not enough: the transaction may already have been rolled back, so the whole logical unit must start again.

  • In PostgreSQL, the documentation recommends retrying transactions that fail with 40P01.
  • In MySQL/InnoDB, a deadlock rolls back the whole transaction, and the documentation says to repeat all of its operations.
  • In SQL Server, error 1205 rolls back the transaction chosen as the victim, and the application can run the unit of work again.

In real applications, limit the number of retries and wait a short, random interval between attempts so that many sessions do not collide again at exactly the same moment.

How to check it

  1. Identify which transaction was rolled back and keep the engine's error code.
  2. Collect the statements of all the transactions involved, not just the last one that failed.
  3. Write down which rows, tables or ranges each operation locks, and in what order.
  4. Find the cycle: A holds X and waits for Y; B holds Y and waits for X.
  5. Check whether every path through the application touches those resources in the same order.

In MySQL you can inspect the latest InnoDB deadlock with SHOW ENGINE INNODB STATUS. SQL Server reports deadlock information through its diagnostic tools; PostgreSQL logs the deadlock error and its SQLSTATE code. The point of these tools is to reconstruct the order of the waits, not to “guess” which query looks heaviest.

Differences between engines

EngineTypical signWhat the engine doesRecommended response
PostgreSQL40P01 deadlock_detectedDetects the cycle and aborts one transaction.Fix the locking order and set up a retry of the transaction.
MySQL / InnoDBError 1213Detects the deadlock and rolls back one transaction.Repeat the whole transaction and reduce collisions.
SQL ServerError 1205Chooses a victim and rolls back its transaction.Retry the unit of work and analyse the deadlock graph.
SQLiteSQLITE_BUSY / SQLITE_LOCKED depending on the conflictWrites are serialised in the usual model; one writer can stop another from continuing.Keep transactions short, set a suitable busy timeout and do not assume the problem is a server-style deadlock.

Making future deadlocks less likely

  • Stable order: access shared tables and rows following the same rule in every flow.
  • Short transactions: do not leave a transaction open while waiting for user input or doing work unrelated to the database.
  • Suitable filters and indexes: narrowing the set a statement has to examine can shorten locks and reduce their reach.
  • Fewer resources per transaction: do not touch more rows or tables than the business rule needs.
  • Controlled retry: treat deadlocks as something that can happen in concurrent systems, not as an impossible exception.

A single wait is not a deadlock. Shorter transactions help, but they do not remove every cycle.