Scrivio Interview library
CodingIntermediate6 min read · updated 12 November 2026

Write code that retries a whole transaction up to three times when an ObjectOptimisticLockingFailureException occurs.

We loop up to three times, and in each attempt we call transactionTemplate.execute(status -> doWork()), so every attempt is a brand-new transaction that reads fresh data. We catch ObjectOptimisticLockingFailureException, or its parent OptimisticLockingFailureException, outside the transaction, wait with a backoff plus random jitter, and rethrow after the last attempt. Declarative retry with Spring Framework 7's @Retryable or Spring Retry also works, as long as the retry wraps the transaction from outside.

Why this question is asked

Optimistic locking detects conflicts instead of preventing them, which means some transactions will fail and need to run again. The retry looks trivial, but there is one rule that many implementations get wrong: the retry has to happen outside the failed transaction. Interviewers use this question to check that we know why. In this answer, we will recap what the exception means, see why retrying inside the transaction cannot work, write the retry loop with backoff and jitter, and then do the same declaratively.

1A Quick Recap: What the Exception Means

With optimistic locking, each row has a version column, mapped with @Version. When Hibernate updates the row, it adds where version = ? with the version it read. If another transaction changed the row in between, no row matches, and Hibernate throws an exception at flush or commit. Spring translates it into ObjectOptimisticLockingFailureException, a subclass of OptimisticLockingFailureException.

The exception tells us that our transaction worked on data that is now outdated. The right reaction is to read the current data again and redo the work, which is exactly what a new transaction does.

2Why Retrying Inside the Transaction Does Not Help

A tempting mistake is to put the retry inside a @Transactional method, around the code that failed.

Java
@Transactional
public void addPoints(long id, int points) {
for (int i = 0; i < 3; i++) {
try {
Account a = repo.findById(id).orElseThrow(); // same persistence context: cached, stale
a.addPoints(points);
repo.flush();
return;
} catch (ObjectOptimisticLockingFailureException e) {
// retry ... but the transaction is already marked rollback-only
}
}
}
// attempt 2 reads the same stale entity from the persistence context
// at the end: UnexpectedRollbackException

Three things go wrong. The persistence context, Hibernate's cache of entities loaded in this transaction, still holds the stale Account, so findById() returns the same old object instead of reading the row again. Hibernate's session is unusable after this exception anyway. And Spring has marked the transaction rollback-only when the exception passed through the repository, so even if a later attempt succeeded, the commit would fail. The only clean way to read fresh data is to throw this transaction away and start a new one.

3The Retry Loop Around TransactionTemplate

So the loop lives outside the transaction, and each attempt calls the template. The calling method must not itself be @Transactional, or the template would join the outer transaction and we would be back to the broken case.

Java
@Service
class PointsService {
private static final int MAX_ATTEMPTS = 3;
private final TransactionTemplate tx;
private final AccountRepository repo;
PointsService(TransactionTemplate tx, AccountRepository repo) {
this.tx = tx;
this.repo = repo;
}
public void addPoints(long id, int points) { // no @Transactional here
for (int attempt = 1; ; attempt++) {
try {
tx.executeWithoutResult(status -> { // a new transaction each time
Account a = repo.findById(id).orElseThrow(); // fresh read
a.addPoints(points);
}); // commit: version check happens here
return;
} catch (OptimisticLockingFailureException e) {
if (attempt == MAX_ATTEMPTS) throw e; // give up, caller sees the conflict
sleepWithJitter(attempt);
}
}
}
private static void sleepWithJitter(int attempt) {
long base = 50L << (attempt - 1); // 50 ms, then 100 ms
long wait = ThreadLocalRandom.current().nextLong(base / 2, base + 1);
try {
Thread.sleep(wait);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
throw new IllegalStateException("interrupted while retrying", ie);
}
}
}
// attempt 1: conflict, wait about 25-50 ms
// attempt 2: conflict, wait about 50-100 ms
// attempt 3: success -> committed, or conflict -> exception rethrown
Step throughOne attempt after another
  1. Start a new transactionNothing cached from earlier attempts
  2. Read the row and apply the changeFresh version number
  3. Commit succeeded?
    YesReturn to the callerNoCatch the conflict outside
  4. Attempts left?
    YesWait with backoff and jitter, start againNoRethrow the exception

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

The retry decision is always made outside a transaction.

Notice that the catch is on the broader OptimisticLockingFailureException. It covers the JPA case and also other Spring data access code that reports the same kind of conflict. The backoff grows with each attempt, and the jitter, a random part of the wait, matters as much as the growth: two requests that collided once would collide again if they both waited exactly 50 milliseconds.

4Doing It Declaratively

Spring Framework 7 adds its own @Retryable annotation in org.springframework.resilience.annotation, enabled with @EnableResilientMethods; Spring Retry offers a similar @Retryable for earlier versions. Check your version for the exact attribute names. The rule stays the same: the retry interceptor must run outside the transaction interceptor. The safest way is to put @Retryable on a method of one bean that calls a @Transactional method on another bean, so each retry goes through the transactional proxy again.

Java
@Service
class PointsFacade {
private final PointsWriter writer;
PointsFacade(PointsWriter writer) { this.writer = writer; }
@Retryable(includes = OptimisticLockingFailureException.class,
maxRetries = 2, delay = 50, multiplier = 2, jitter = 25)
public void addPoints(long id, int points) {
writer.addPoints(id, points); // new transaction per call
}
}
@Service
class PointsWriter {
@Transactional
public void addPoints(long id, int points) {
repo.findById(id).orElseThrow().addPoints(points);
}
}

Putting both annotations on the same method can work if the interceptor order is configured so that retry is outermost, but the two-bean version makes the order impossible to get wrong.

5Follow-up questions

Should every optimistic lock failure be retried?

No. A retry is right when the work can be recomputed from fresh data, such as adding points. When a user edited a form based on what they saw, retrying would silently overwrite the other person's change with the user's old view, so there we report a conflict instead.

Is it safe to retry if the transaction also calls another service?

Only if that call is idempotent or outside the retried block. Each attempt would repeat the call, so a payment or an email inside the transaction would be sent up to three times. Keep side effects outside the retry or make them idempotent with a request id.

What about serialization failures under SERIALIZABLE isolation?

They are retried the same way, a new transaction per attempt. In Spring they usually arrive as CannotAcquireLockException or another PessimisticLockingFailureException subclass, depending on the driver and version, so check what your stack throws and include it in the retry condition.

6Conclusion

In this answer, we saw that an optimistic lock failure means our transaction used outdated data, and the only way to get fresh data is a new transaction. The retry loop therefore sits outside the transaction and calls TransactionTemplate on each attempt, catches OptimisticLockingFailureException, waits with exponential backoff and jitter, and rethrows after the third attempt. Declarative retry works on the same principle when the retry wraps the transactional proxy from outside.

What to say in the interviewAbout 80 seconds aloud

Open with

The key point is that each retry has to be a new transaction. If I retry inside the same transaction, the persistence context still holds the stale entity, Hibernate's session is no longer reliable after the exception, and Spring has already marked the transaction rollback-only, so it will fail at commit anyway.

Then, if they want more

So I write a loop in a method that is not transactional. For attempt one to three, I call transactionTemplate.executeWithoutResult with a lambda that loads the account and applies the change. The version check happens at commit.

If I catch OptimisticLockingFailureException, which is the parent of ObjectOptimisticLockingFailureException, I check whether attempts are left; if yes I sleep with exponential backoff, 50 then 100 milliseconds, plus random jitter so the two colliding requests do not collide again, and if not I rethrow so the caller can report a conflict.

Declaratively, Spring Framework 7 has its own @Retryable and older versions can use Spring Retry, but I put the retry on one bean and the @Transactional method on another, so every retry goes through the transaction proxy again. I would only retry work that can be recomputed from fresh data, and keep non-idempotent side effects out of the retried block.

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 code that retries a whole transaction up to three times when an...": https://scrivio-interview-library.netlify.app/databases/transactions/c60957726a/