Quick revision
The short answer
The advice loops up to three times, calling pjp.proceed() each time, catching TransientDataAccessException, waiting with a backoff between attempts, and rethrowing the last exception when the final attempt fails. Because the method may run more than once, it must be idempotent, meaning running it twice has the same effect as running it once. If the method is also @Transactional, the retry aspect must wrap the transaction, so each attempt runs in a fresh transaction, which means ordering the retry aspect ahead of the transaction advice; in production code, Spring Retry, Resilience4j or the retry support in newer Spring Framework versions provide tested implementations.
What to remember
In this answer, we wrote an @Around advice that calls proceed() up to three times, catches only TransientDataAccessException, waits with exponential backoff and jitter, and rethrows after the last attempt. We saw that the advised method must be idempotent, because it may run more than once, and that external side effects need an outbox or idempotency key. We also saw that the retry aspect must run outside @Transactional so each attempt gets a fresh transaction, and that Spring Retry, Resilience4j or Spring Framework 7's own @Retryable are the tested choices for production.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The advice loops up to three times, calling pjp.proceed() each time, catching TransientDataAccessException, waiting with a backoff between attempts, and rethrowing the last exception when the final attempt fails. Because the method may run more than once, it must be idempotent, meaning running it twice has the same effect as running it once. If the method is also @Transactional, the retry aspect must wrap the transaction, so each attempt runs in a fresh transaction, which means ordering the retry aspect ahead of the transaction advice; in production code, Spring Retry, Resilience4j or the retry support in newer Spring Framework versions provide tested implementations.
Why this question is asked
Transient database failures, such as a deadlock, a lock timeout or a brief connection blip, are normal in busy systems, and retrying them is often the right response. Writing the retry as an aspect is a classic exercise because it uses the full power of @Around: calling proceed() more than once. Interviewers like it because the code is short but the conditions around it are where the real knowledge shows: idempotency and the interaction with transactions. In this answer, we will recap what a transient exception is, write the advice step by step, add backoff, explain why the method must be idempotent, sort out the order with @Transactional, and finish with the libraries that do this for us.
1A Quick Recap of Transient Data Access Exceptions
Spring translates database errors into its own DataAccessException hierarchy, so our code does not depend on vendor error codes. One branch of that hierarchy is TransientDataAccessException, for failures where the same operation might succeed if we simply try again without changing anything. Examples include QueryTimeoutException, and the concurrency failures such as PessimisticLockingFailureException and its subclass CannotAcquireLockException, which cover deadlocks and lock timeouts. Errors such as a constraint violation (DataIntegrityViolationException) are not transient, and retrying them only wastes time.
2Writing the Retry Advice
We start with a marker annotation so the retry is opt-in, then an @Around advice that loops around proceed().
Notice the details. The advice returns Object and returns proceed()'s result, so the caller gets the real value. Only TransientDataAccessException is caught; any other exception passes straight through on the first attempt. After the third failure the advice rethrows the original exception, so the caller sees a real error rather than null. Calling proceed() again is allowed in Spring AOP and runs the rest of the chain and the method again.
3Why the Backoff Matters
Retrying immediately after a deadlock often hits the same conflict, because the other transaction is still running. Waiting a little gives it time to finish. Doubling the wait each time, exponential backoff, avoids hammering a struggling database, and adding jitter, a small random amount, stops many threads that failed at the same moment from retrying at the same moment again. Keep the total wait small, here about 300 milliseconds over three attempts, because a request thread is blocked while it sleeps.
4The Method Must Be Idempotent
Retrying means the method may run two or three times. If the first attempt did something before failing, the second attempt does it again. That is safe only if the method is idempotent: running it several times has the same effect as running it once.
Database work inside a transaction that rolled back is naturally safe, because the failed attempt's changes are undone. The danger is side effects outside the transaction: sending an email, calling a payment API, publishing a Kafka message. If the method charged a card and then hit a deadlock while saving the result, a retry would charge the card again. Such methods should either move their external side effects after the commit, for example with @TransactionalEventListener or an outbox table, or use an idempotency key so the external system ignores duplicates.
5Ordering the Retry and the Transaction
If the method is @Transactional, there are two advices on the same call: retry and transaction. Their order decides whether retrying works at all. When the transaction is outside and the retry inside, all three attempts run in the same transaction. After a deadlock the database has usually already rolled that transaction back or marked it unusable, and Spring has marked it rollback-only, so the later attempts fail or commit nothing useful.
The retry must be outside: each attempt then enters the transaction advice afresh, which begins a new transaction, runs the method, and commits or rolls back before the retry decides whether to try again. Spring's transaction advisor uses the lowest precedence by default, so giving the retry aspect a higher precedence, a lower @Order value as in the code above, puts it on the outside. We can also set the order explicitly with @EnableTransactionManagement(order = ...).
11 messages in order. Play them, or step through them one at a time.
Each attempt gets its own transaction because retry wraps the transaction advice.
6Use a Library in Production
Writing the aspect is a good way to understand retries, but production code usually uses a library that has handled the edge cases. Spring Retry offers @Retryable with maxAttempts, backoff settings and @Recover methods, enabled with @EnableRetry. Resilience4j offers @Retry with configuration in application.yml, metrics, and combinations with circuit breakers. Spring Framework 7 adds its own @Retryable annotation in the core framework, so check your version. All of them need the same care about idempotency and ordering relative to @Transactional.
7Follow-up questions
Why not retry on every DataAccessException?
Because most data access errors are not transient. A constraint violation, a bad SQL grammar or a missing table will fail the same way every time, so retrying only delays the error and adds load. TransientDataAccessException is exactly the category Spring designed for this.
Is Thread.sleep acceptable in the advice?
For a short backoff on a request thread, yes, as long as the total wait stays small. For long waits, or in reactive code, it is better to use a library that schedules the retry instead of blocking a thread. Remember that sleeping holds a request thread and, if the retry were inside a transaction, a database connection.
What happens if the retry aspect is inside the transaction by mistake?
The first failure usually marks the transaction rollback-only or the database has already aborted it. Later attempts then fail immediately or run in a broken transaction, and the commit at the end throws UnexpectedRollbackException. Integration tests that force a deadlock can catch this ordering mistake.
8Conclusion
In this answer, we wrote an @Around advice that calls proceed() up to three times, catches only TransientDataAccessException, waits with exponential backoff and jitter, and rethrows after the last attempt. We saw that the advised method must be idempotent, because it may run more than once, and that external side effects need an outbox or idempotency key. We also saw that the retry aspect must run outside @Transactional so each attempt gets a fresh transaction, and that Spring Retry, Resilience4j or Spring Framework 7's own @Retryable are the tested choices for production.
Open with
I would write an @Around advice on an opt-in annotation like @RetryOnTransient. The advice returns Object and loops: inside a try it returns pjp.proceed(), and it catches only TransientDataAccessException, which is Spring's category for errors that may succeed on a plain retry, like lock timeouts, deadlocks and query timeouts.
Then, if they want more
If it was the third attempt, it rethrows the exception so the caller sees the real failure. Otherwise it logs, sleeps with exponential backoff and a bit of jitter, say about 100 and then 200 milliseconds, and tries again. The advised method has to guarantee idempotency, because it may run more than once.
Database work in a rolled-back transaction is undone, but side effects like sending an email or calling a payment API would repeat, so those need an outbox, an after-commit event or an idempotency key. If the method is @Transactional, the order matters: the retry must be outside the transaction, so each attempt gets a new transaction.
If it were inside, every attempt would reuse a transaction that has already failed or been marked rollback-only. Spring's transaction advisor has the lowest precedence by default, so I give the retry aspect a higher precedence with @Order.
In real code I would rather use Spring Retry, Resilience4j, or the @Retryable in Spring Framework 7, which handle backoff, metrics and recovery, but they need the same idempotency and ordering care.
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.
- Official documentation
- Spring Framework reference, Core technologies
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 an @Around advice that retries a method up to three times on a...": https://scrivio-interview-library.netlify.app/spring-boot/aop/ff80546b7f/