Systems & Backend

Deadlock

Two transactions each hold a lock the other needs, so both wait forever — the database must detect and kill one.

A deadlock is when two or more transactions each hold a lock the other needs and both wait indefinitely — a cycle of waiting that never resolves on its own. Databases detect deadlocks and abort one transaction (the “victim”) to break the cycle.

Worked example: transaction A locks row 1 then wants row 2, while B locks row 2 then wants row 1 — neither can proceed; the database rolls one back with a deadlock error, and the app retries it. Gotcha: the classic prevention is to always acquire locks in a consistent order (both grab row 1 before row 2), which removes the cycle; and because deadlocks are expected under contention, transactions should be short and the app should retry the aborted one rather than crash.