Menu

1 / 5

Deadlocks Explained: When Two Transactions Wait for Each Other Forever

DEV Community: backend·Abdeldjalil Chougui·about 5 hours ago
#spAxftWq
#devtobackend#devto#dev#transaction#lock
Long article (1163 words) — no AI summary yet.
Reading 0:00
15s threshold

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 =…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.