Spring / Spring Retry Interview Questions
What is stateful retry in Spring Retry and when should it be used?
Stateful retry in Spring Retry means that the retry context and failure count are preserved across separate, independent method invocations for the same logical operation — typically identified by a key. This is in contrast to stateless retry, where each call to execute() begins a fresh retry sequence.
Stateful retry is needed when the retried operation has side effects or when its transactional boundary means a failed attempt cannot be reattempted within the same thread or method call. The most common use case is Spring Batch item processing: if a batch item fails, the transaction is rolled back, and the next call to process that item should count as a retry — not a fresh attempt.
How it works:
- A
RetryStateobject with a unique key (typically the item or operation identity) is passed toretryTemplate.execute(). - Spring Retry stores the retry count and context externally (in a
RetryContextCache). - On subsequent calls with the same key, the stored state is retrieved and updated.
DefaultRetryState state = new DefaultRetryState(itemKey); retryTemplate.execute(ctx -> processItem(item), ctx -> recover(item), state);
The default RetryContextCache is a thread-safe in-memory map. For clustered environments, a custom distributed cache implementation can be plugged in.
More Related questions...