Scrivio Interview library
CodingIntermediate6 min read · updated 12 November 2026

Write a Spring Boot service method that books a seat under PostgreSQL SERIALIZABLE isolation and retries on serialization failures up to three times. Explain where the retry must sit and which exceptions to catch.

We put the booking logic in a @Transactional(isolation = Isolation.SERIALIZABLE) method on one bean and call it from a loop in another bean, so every attempt goes through the transactional proxy and runs in a brand-new transaction. The loop catches Spring's ConcurrencyFailureException, which covers serialization failures (SQLSTATE 40001) and deadlocks (40P01), waits a short random backoff, and gives up after three attempts with a clear conflict error. Side effects such as emails stay outside the retried transaction.

Why this question is asked

Running a booking at SERIALIZABLE is the easy part; it is one attribute on an annotation. The part that decides whether the code works is the retry, because under SERIALIZABLE PostgreSQL will abort some transactions on purpose, and a retry in the wrong place silently does nothing. Interviewers ask for this code to see whether we know how Spring's transaction proxy works and which exceptions mean try again. In this answer, we will recap why serializable transactions fail, write the transactional booking method, put the retry in the right place, decide which exceptions to catch, and add backoff and the rules for side effects.

1Why Serializable Transactions Fail on Purpose

At SERIALIZABLE, PostgreSQL guarantees that concurrent transactions produce the same result as if they ran one at a time. It does this optimistically: transactions run without extra blocking, and when PostgreSQL detects that two of them read and wrote each other's data in a way no serial order could explain, it aborts one with SQLSTATE 40001, could not serialize access. For seat booking that is exactly what we want: two people trying to book seat 14C at the same moment will not both succeed. But the loser's transaction is gone, and the only correct reaction is to run the whole transaction again, where it will see the seat is taken.

2The Transactional Booking Method

First the unit of work: one method that checks and books, in one serializable transaction.

Java
@Service
class SeatBookingTx {
private final JdbcTemplate jdbc;
SeatBookingTx(JdbcTemplate jdbc) { this.jdbc = jdbc; }
@Transactional(isolation = Isolation.SERIALIZABLE)
public long book(long showId, String seat, long customerId) {
Integer taken = jdbc.queryForObject(
"SELECT count(*) FROM booking WHERE show_id = ? AND seat = ?", Integer.class, showId, seat);
if (taken > 0) throw new SeatTakenException(seat); // not retried: a business answer
return jdbc.queryForObject(
"INSERT INTO booking (show_id, seat, customer_id) VALUES (?, ?, ?) RETURNING id",
Long.class, showId, seat, customerId);
}
}

If two customers run this together, both counts return 0 and both try to insert. Under SERIALIZABLE, PostgreSQL sees that each transaction read what the other wrote and aborts one with 40001, either at the INSERT or at commit. In a real schema a unique constraint on (show_id, seat) would also be wise; this example shows the serializable path.

3Where the Retry Must Sit

The retry goes in a different bean that calls SeatBookingTx through its Spring proxy. The proxy is the wrapper Spring generates around a bean to start and end transactions. Each call through it begins a new transaction and, when the call throws, rolls it back. So each loop iteration is a fresh transaction with a fresh snapshot.

Java
@Service
class SeatBookingService {
private final SeatBookingTx tx;
SeatBookingService(SeatBookingTx tx) { this.tx = tx; }
public long book(long showId, String seat, long customerId) {
for (int attempt = 1; ; attempt++) {
try {
return tx.book(showId, seat, customerId); // new SERIALIZABLE transaction each time
} catch (ConcurrencyFailureException e) { // 40001 serialization, 40P01 deadlock
if (attempt == 3) throw new BookingConflictException(seat, e); // -> HTTP 409
backoff(attempt);
}
}
}
private static void backoff(int attempt) {
long base = 20L << (attempt - 1); // 20 ms, then 40 ms
try { Thread.sleep(base + ThreadLocalRandom.current().nextLong(base)); }
catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new IllegalStateException(ie); }
}
}
// attempt 1: ConcurrencyFailureException (other customer won the race)
// attempt 2: count = 1 -> SeatTakenException, returned to the user as 'seat taken'
Step throughTwo attempts, two transactions
Booking serviceSeatBookingTx proxyPostgreSQL
book() attempt 1
BEGIN SERIALIZABLE, count, insert
ERROR 40001
rollback, ConcurrencyFailureException
sleep 20 to 40 ms
book() attempt 2
BEGIN SERIALIZABLE, count = 1
SeatTakenException, no retry

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

Notice that SeatBookingService itself has no @Transactional. If it did, the inner call would join the outer transaction, and every retry would run inside the same aborted transaction. A TransactionTemplate inside the loop works equally well, since it also starts a new transaction per call.

4Which Exceptions to Catch

Spring translates SQL errors into its DataAccessException hierarchy. SQLSTATE 40001 from PostgreSQL typically surfaces as CannotAcquireLockException or another subtype of PessimisticLockingFailureException, which extends ConcurrencyFailureException; the exact class has changed between Spring versions, so check your version. Deadlocks, 40P01, land in the same family. Catching ConcurrencyFailureException covers both, and also optimistic locking failures from @Version, which are safe to retry too.

We do not catch DataAccessException in general. A unique constraint violation, a syntax error or a lost connection are not cured by trying again, and retrying them only hides real problems. Business exceptions such as SeatTakenException must pass straight through.

5Using a Retry Annotation Instead of a Loop

The same structure can be written declaratively. With Spring Retry, the separate library, we annotate the outer method with @Retryable(retryFor = ConcurrencyFailureException.class, maxAttempts = 3, backoff = @Backoff(delay = 20, multiplier = 2, random = true)). Spring Framework 7 adds a @Retryable of its own in its core resilience support, enabled with @EnableResilientMethods; check your version for the exact attribute names. Either way, the rule is the same: the retry interceptor must sit outside the transactional proxy, either on a different bean or with the retry advice ordered before the transaction advice.

6Side Effects and Giving Up

Anything inside the retried transaction may run more than once. If book() sent a confirmation email or called a payment API, the first, rolled-back attempt would already have done it. So side effects happen after the successful call returns, or through an outbox table written in the same transaction and processed afterwards, or they must be idempotent, for example with an idempotency key on the payment call.

After the last attempt we stop and return a clear conflict, such as HTTP 409 with a message to try again, instead of retrying forever. A metric on the number of 40001 retries tells us when contention grows enough to need a design change.

7Follow-up questions

Why does a retry inside the same @Transactional method not work?

Because after a serialization failure PostgreSQL marks the whole transaction as aborted, and every further statement in it fails with current transaction is aborted, commands ignored until end of transaction block. The method is also still using the old snapshot. Spring's transaction interceptor only starts a new transaction when a call comes in through the proxy, so the retry has to be outside the transactional method and call it through the proxy each time.

Should the backoff be random?

Yes. If two transactions conflicted and both retry after exactly 20 ms, they are likely to conflict again. Random jitter spreads them apart so one usually finishes first.

Is three attempts enough?

For ordinary contention, almost always: most conflicts resolve on the second attempt. If the third attempt regularly fails, the problem is a hot spot that retries cannot fix.

8Conclusion

In this answer, we wrote a seat booking that runs @Transactional(isolation = Isolation.SERIALIZABLE) on one bean and retries from another bean, so each attempt is a new transaction through the proxy. We catch ConcurrencyFailureException, which covers 40001 serialization failures and 40P01 deadlocks, use a short backoff with jitter and three attempts, return a clear conflict at the end, and keep side effects outside the retried transaction or make them idempotent.

What to say in the interviewAbout 80 seconds aloud

Open with

I'd split it into two beans. The first, SeatBookingTx, has the method annotated @Transactional with isolation SERIALIZABLE. It counts existing bookings for the seat, throws SeatTakenException if there is one, and inserts the booking.

Then, if they want more

The second bean, the booking service, calls it in a loop, and it's not transactional itself. That matters, because each call has to go through Spring's transactional proxy to get a brand-new transaction. After a serialization failure PostgreSQL has aborted the transaction, so retrying inside it can't work. In the loop I catch ConcurrencyFailureException.

SQLSTATE 40001 shows up as CannotAcquireLockException or another subtype depending on the Spring version, and deadlocks, 40P01, are in the same family. I don't catch DataAccessException in general, because things like constraint violations won't be fixed by retrying.

Between attempts I sleep a small backoff with jitter, say 20 then 40 milliseconds plus randomness, and after the third attempt I return a 409 conflict. I could use @Retryable from Spring Retry, or the one in Spring Framework 7 core, as long as it sits outside the transaction.

And I'd keep side effects like emails out of the retried transaction, or use an outbox, so they don't happen twice.

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 "Write a Spring Boot service method that books a seat under PostgreSQL SERIALIZABLE...": https://scrivio-interview-library.netlify.app/databases/acid-and-isolation/1f976591ff/