Scrivio Interview library
LeadershipAdvanced6 min read · updated 12 November 2026

Deadlock errors across your 60 services are rising, and each team handles them differently: some retry forever, some fail the request, some catch and ignore. Write the engineering standard you would publish.

The standard says deadlocks and serialization failures are normal, expected events in concurrent systems, and every service must handle them the same way: retry the whole transaction a small number of times with jittered backoff, only for the retryable codes (SQLState 40001, PostgreSQL 40P01, MySQL 1213), and never in a way that repeats external side effects. Teams use one shared retry component instead of their own loops, follow the prevention rules (consistent lock order, short transactions, proper indexes, no remote calls inside transactions), and the deadlock rate per service is monitored.

Why this question is asked

When sixty services each invent their own answer to the same error, we get the worst of all worlds: infinite retry loops that amplify load, requests failing for an error that would have succeeded a millisecond later, and swallowed exceptions that silently lose writes. Interviewers ask senior engineers to write the standard because it tests both the technical facts and the judgement to make a rule that teams will actually follow. In this answer, we will go through why the current handling is harmful, then write the standard section by section: the principle, the retry rules, the shared component, prevention, and monitoring.

1Why the Current Handling Is Harmful

Each of the three behaviours fails in a different way. Retrying forever turns a burst of contention into a storm: every failed transaction comes back immediately, takes the same locks again and creates more deadlocks, and a dependency that is down keeps threads busy indefinitely. Failing the request treats a transient, harmless condition as an error the user sees, even though one retry would almost always succeed. Catching and ignoring is the worst: the database rolled the transaction back, so the write is lost, while the code carries on as if it succeeded.

The common root is that teams see a deadlock as a bug or as noise. The standard has to replace that with a shared understanding of what a deadlock is.

2The Principle: Deadlocks Are Expected and Retryable

The first section states the principle plainly. In any database where concurrent transactions lock rows, deadlocks can occur, and at SERIALIZABLE or REPEATABLE READ in PostgreSQL, and in distributed SQL databases, serialization failures do too. When the database reports one, it has already rolled back the victim's whole transaction, and nothing is left half done. Running the same transaction again is the correct response and is usually successful, because the other transaction has finished. So these errors are part of normal operation, to be retried safely and counted, while a rising rate is a signal to investigate.

3The Retry Rules

The rules are specific. Retry only these errors: SQLState 40001 (serialization failure, also MySQL deadlocks), PostgreSQL 40P01 (deadlock detected), MySQL error 1213; and, by explicit decision, lock wait timeouts. Never retry constraint violations, syntax errors or data errors, which will fail the same way again.

Retry the whole transaction, never a single statement, because the earlier statements were rolled back too. Limit attempts to three in total for online requests, with exponential backoff and random jitter, for example 20 to 50 milliseconds then 40 to 100, so the colliding transactions do not meet again in lockstep. And a retried transaction must not repeat external side effects: no emails, payments or messages sent from inside it. Those go through an outbox or happen after commit, and anything external is called with an idempotency key.

Step throughWhat the standard requires on a database error
  1. Transaction failsthe database has rolled it back
  2. SQLState 40001, 40P01 or MySQL 1213?
    YesretryableNofail fast, no retry
  3. Attempts left (max 3 online)?
    Yeswait with backoff and jitterNofail the request, log and count
  4. Run the whole transaction againnew transaction from the start, no external side effects inside
  5. Record the metricretries and failures per service and transaction

5 steps in order. Play them, or step through them one at a time.

4One Shared Component, No Ad Hoc Loops

The platform team provides one component and the standard forbids hand-written retry loops. In Spring, that can be a RetryTemplate from Spring Retry, a Resilience4j Retry, or the retry support built into Spring Framework 7, wrapped around a TransactionTemplate, so the boundary is unmistakable: each attempt is a fresh transaction.

Java
@Component
public class TxRetry {
private final TransactionTemplate tx;
private final RetryTemplate retry = RetryTemplate.builder()
.maxAttempts(3)
.exponentialBackoff(Duration.ofMillis(25), 2.0, Duration.ofMillis(200), true) // with jitter
.retryOn(TransientDataAccessException.class) // deadlock and serialization failures map here
.build();
public TxRetry(PlatformTransactionManager m) { this.tx = new TransactionTemplate(m); }
public <T> T run(TransactionCallback<T> work) {
return retry.execute(ctx -> tx.execute(work)); // each attempt: new transaction
}
}
// orders.place(...) wrapped as txRetry.run(s -> orders.place(req))

Spring's exception translation turns the vendor codes into the TransientDataAccessException family (for deadlocks, a PessimisticLockingFailureException; for serialization failures, a CannotSerializeTransactionException or a similar concurrency subclass, depending on version). The shared component also emits metrics and logs, so every service reports retries the same way. The exact builder method names vary by Spring Retry version, so the platform library hides them behind run().

5Prevention and Monitoring

Retry handles deadlocks; prevention keeps them rare. The standard lists the design rules: lock rows in a consistent order, such as ascending primary key, in every code path; keep transactions short and never make remote calls inside them; make sure every UPDATE and DELETE filter is backed by an index, so statements lock only the rows they need; and prefer single conditional statements over read-then-write.

Finally, monitoring. Each service exports retries and final failures per transaction type from the shared component. On the database side, deadlock counts come from pg_stat_database.deadlocks in PostgreSQL, from logging every deadlock with innodb_print_all_deadlocks in MySQL, and from the deadlock reports in SQL Server's system health session. A dashboard ranks services by deadlock rate, and a sustained rise opens an investigation into the transactions named in the deadlock logs.

6Follow-up questions

Why is @Retryable on a @Transactional method a common mistake?

Because the retry and the transaction boundary must be nested the right way round, and the annotations hide which way they are. If the retry runs inside the transaction, or the method joins an outer transaction through REQUIRED propagation, each retry reuses a transaction that the database has already aborted (in PostgreSQL: current transaction is aborted), so every attempt fails. The order of the two interceptors on one method depends on advisor ordering, which is easy to get wrong and invisible in code review. Putting the retry in a separate bean that calls the transactional method, or using retry around TransactionTemplate, makes each attempt a new transaction by construction.

Should batch jobs follow the same retry limits as online requests?

The principle is the same, but a batch job can afford more attempts and longer backoff, for example five attempts up to a few seconds, because nobody is waiting on an HTTP response. The standard can define both profiles in the shared component.

What about lock wait timeouts, are they retryable?

They can be, but they mean a transaction waited too long behind another, often a long-running one, and blind retries add pressure. The standard should let a team opt in per transaction, with a single retry, and require alerting so the long holder gets fixed.

7Conclusion

In this answer, we saw why retrying forever, failing immediately and ignoring deadlocks each cause harm, and wrote a standard that treats deadlocks and serialization failures as expected, retryable events. The whole transaction is retried a few times with jittered backoff, only for 40001, 40P01 and 1213, with no external side effects inside, through one shared component built from RetryTemplate or Resilience4j around TransactionTemplate. Prevention rules keep deadlocks rare, and deadlock and retry metrics per service tell us when to investigate.

What to say in the interviewAbout 80 seconds aloud

Open with

The standard would start by saying deadlocks and serialization failures are expected in concurrent systems. The database has already rolled back the victim, so the right response is to run the transaction again, not to treat it as a bug or swallow it.

Then, if they want more

Ignoring it loses the write, failing immediately shows users a transient error, and retrying forever creates retry storms.

The rules: retry only the retryable codes, SQLState 40001, PostgreSQL 40P01 and MySQL 1213; retry the whole transaction, not the statement; at most three attempts online, with exponential backoff and jitter; and nothing inside the transaction may have external side effects that a retry would repeat, so emails and messages go through an outbox or happen after commit.

Teams must use one shared component, something like a RetryTemplate or Resilience4j retry wrapped around a TransactionTemplate, so each attempt is a fresh transaction and metrics come for free; hand-written loops aren't allowed. Then prevention: consistent lock order, short transactions, indexes behind every update filter, no remote calls inside transactions.

And we'd monitor deadlock and retry rates per service from the component and the database, and investigate when a service's rate goes up.

About this answer

Last updated
12 November 2026
Versions it names
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 "Deadlock errors across your 60 services are rising, and each team handles them...": https://scrivio-interview-library.netlify.app/databases/database-locking/ab7fefcac7/