Scrivio Interview library
ConceptFoundations7 min read · updated 12 November 2026

What is a database deadlock, how does the database resolve it, and how does it appear in a Spring application?

A deadlock happens when two transactions each hold a lock the other one needs, so neither can ever continue. The database notices the cycle, picks one transaction as the victim and rolls it back with an error (SQLState 40P01 in PostgreSQL, error 1213 with SQLState 40001 in MySQL), which Spring turns into a PessimisticLockingFailureException such as CannotAcquireLockException. The right response is to retry the whole transaction.

Why this question is asked

Deadlocks are one of those errors that appear only under real load: the tests pass, the first week in production is quiet, and then one day the logs show a burst of failed requests. Interviewers ask about them because handling them well needs three pieces of knowledge at once: what a lock is, what the database does when locks form a circle, and what our Spring code sees when that happens. In this answer, we will recap how row locks work, build a deadlock step by step, see how PostgreSQL and MySQL detect and break it, look at the exception Spring gives us, and finish with how to retry correctly.

1A Quick Recap of Row Locks

When a transaction changes a row, the database locks that row until the transaction commits or rolls back. A lock is a marker that says this row belongs to me for now. Any other transaction that wants to change the same row has to wait. This waiting is normal and usually lasts milliseconds, because the first transaction finishes and releases its locks.

Locks are held until the end of the transaction, not until the end of the statement. That detail matters. If our transaction updates row 1, then does some other work, then updates row 2, it is holding the lock on row 1 the whole time. The longer a transaction runs and the more rows it touches, the more chances it has to get in someone else's way.

2How Two Transactions End Up Waiting Forever

A deadlock needs two transactions that lock the same rows in a different order. Let us take two accounts with ids 1 and 2, and two transactions that both want to update both rows.

SQL
-- Transaction A -- Transaction B
BEGIN; BEGIN;
UPDATE account SET balance = balance - 10
WHERE id = 1; -- A locks row 1
UPDATE account SET balance = balance - 5
WHERE id = 2; -- B locks row 2
UPDATE account SET balance = balance + 10
WHERE id = 2; -- A waits for B
UPDATE account SET balance = balance + 5
WHERE id = 1; -- B waits for A: deadlock
Step throughTwo transactions lock rows in opposite order
Transaction ADatabaseTransaction B
UPDATE row 1: lock granted
UPDATE row 2: lock granted
UPDATE row 2: wait for B
UPDATE row 1: wait for A
deadlock detected: B is rolled back
lock on row 2 granted, A continues

6 messages in order. Play them, or step through them one at a time.

The circle A waits for B and B waits for A can only be broken by aborting one of them.

Notice what happened at the end. A is waiting for B to release row 2, and B is waiting for A to release row 1. Neither can commit, because neither can finish its work. Without help from the database, both would wait forever. This circle of waiting is what we call a deadlock, and it is different from ordinary lock waiting, which always ends when the other transaction finishes.

3How the Database Detects and Breaks the Cycle

Databases keep a graph of who is waiting for whom. When that graph contains a cycle, they know no amount of waiting will help, so they choose one transaction, called the victim, roll it back and release its locks. The other transaction then gets its lock and carries on as if nothing had happened.

PostgreSQL does not check for cycles on every wait, because that would be expensive. A transaction that has waited for a lock longer than deadlock_timeout, which is one second by default, runs the check. If it finds a cycle, it aborts itself with ERROR: deadlock detected and SQLState 40P01. MySQL's InnoDB checks immediately when a transaction starts to wait, and it usually picks as victim the transaction that has changed fewer rows, because it is cheaper to undo. It reports error 1213, Deadlock found when trying to get lock; try restarting transaction, with SQLState 40001.

So in both databases one transaction is sacrificed and the other succeeds. The database has done its job; the rest is up to our application.

4What Our Spring Code Sees

The JDBC driver throws an SQLException with the SQLState and the vendor code. Spring catches it at the boundary of JdbcTemplate, a Spring Data repository or the JPA layer, and translates it into its own DataAccessException hierarchy, so our code does not have to know the vendor codes.

Java
try {
transferService.transfer(1L, 2L, new BigDecimal("10.00"));
} catch (PessimisticLockingFailureException e) {
// e is usually CannotAcquireLockException in Spring 6 and 7
log.warn("deadlock victim: {}", e.getMostSpecificCause().getMessage());
// ERROR: deadlock detected (PostgreSQL, SQLState 40P01)
}

In Spring Framework 6 and later, a deadlock usually arrives as CannotAcquireLockException, which is a subclass of PessimisticLockingFailureException. Older versions used DeadlockLoserDataAccessException, which is now deprecated. The exact subclass can depend on the version and on whether the error passes through Hibernate first, so it is safer to catch PessimisticLockingFailureException, or even its parent ConcurrencyFailureException, than one specific subclass. Check your version if you need the exact type.

5Retrying the Whole Transaction

The victim's transaction has been rolled back completely. Every change it made is gone, and on PostgreSQL the transaction is in an aborted state where no further statement will run. So we cannot simply repeat the last statement. We have to start the whole unit of work again from the beginning, with a fresh transaction, ideally after a short random pause so the two competitors do not collide again at the same moment.

Java
public void transferWithRetry(long from, long to, BigDecimal amount) {
for (int attempt = 1; ; attempt++) {
try {
tx.executeWithoutResult(s -> transfer(from, to, amount)); // a new transaction each time
return;
} catch (PessimisticLockingFailureException e) {
if (attempt == 3) throw e; // give up after 3 tries
sleep(ThreadLocalRandom.current().nextInt(20, 100)); // short random pause
}
}
}

Notice that the retry loop sits outside the transaction. If we put a retry inside a @Transactional method, every attempt would run in the same transaction that the database has already aborted. With Spring Retry's @Retryable or the @Retryable support built into Spring Framework 7, the same rule holds: the retry proxy must wrap the transactional proxy, not the other way round. Retries are the safety net; the real cure for frequent deadlocks is to lock rows in a consistent order and keep transactions short.

6Follow-up questions

What is the difference between a deadlock and a lock wait timeout?

A lock wait timeout means one transaction waited too long for a lock that another transaction was holding, but that other transaction could still finish. A deadlock means there is a cycle and nobody can finish. MySQL reports a lock wait timeout as error 1205 after innodb_lock_wait_timeout, 50 seconds by default, and PostgreSQL only times out if lock_timeout is set. Both are worth retrying, but a timeout often points to a long-running transaction rather than a bad lock order.

Can a deadlock happen with only one row?

Yes, in some cases. In MySQL, two transactions can each hold a shared lock on the same row and then both ask to upgrade it to an exclusive lock, which forms a cycle. Gap locks on missing rows can also deadlock two inserts. The pattern is always the same: each transaction holds something the other needs.

Should we retry every deadlock automatically?

Retrying is right when the whole transaction can safely run again, which is true for most database-only work. It is not safe if the transaction already triggered something outside the database, such as calling a payment provider or sending an email, unless that side effect is idempotent. A small number of attempts with a random pause is enough; if deadlocks keep happening, we fix the cause.

7Conclusion

In this answer, we saw that a deadlock is a cycle of transactions each waiting for a lock the other holds. PostgreSQL detects it after deadlock_timeout and reports SQLState 40P01, while MySQL detects it at once and reports error 1213 with SQLState 40001; both roll back one victim. Spring translates the error into a PessimisticLockingFailureException, usually CannotAcquireLockException, and our job is to retry the whole transaction from outside it, while fixing lock order so deadlocks stay rare.

What to say in the interviewAbout 80 seconds aloud

Open with

A deadlock is when two transactions each hold a lock the other one needs. For example, transaction A updates account 1 and then wants account 2, while transaction B has already updated account 2 and now wants account 1.

Then, if they want more

Neither can continue, so waiting will never end on its own. The database keeps track of who waits for whom, and when it finds a cycle it picks a victim and rolls it back. PostgreSQL runs the check after deadlock_timeout, one second by default, and raises deadlock detected with SQLState 40P01.

MySQL InnoDB detects it immediately and returns error 1213 with SQLState 40001, usually rolling back the transaction that changed fewer rows. In a Spring application, the driver's SQLException is translated into a PessimisticLockingFailureException, typically CannotAcquireLockException in Spring 6 and later, so I catch the parent type rather than one subclass.

Because the victim's transaction is fully rolled back, I retry the whole unit of work in a new transaction, from outside the @Transactional boundary, a couple of times with a small random pause. And I treat frequent deadlocks as a design problem, usually fixed by locking rows in a consistent order and keeping transactions short.

About this answer

Last updated
12 November 2026
Versions it names
Spring Framework 6, Spring Framework 7
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "What is a database deadlock, how does the database resolve it, and how does it appear in...": https://scrivio-interview-library.netlify.app/databases/locking-and-concurrency-control/e45f7684f1/