Spring / Spring Retry Interview Questions
What is the RetryContextCache and when do you need a custom implementation?
RetryContextCache is the storage mechanism used by stateful retry to persist RetryContext objects between separate method invocations. In stateful retry, when a retryable operation fails and a transaction is rolled back, the retry state (attempt count, last exception) must survive the rollback so the next invocation can continue the retry sequence rather than starting fresh.
Spring Retry's default implementation is MapRetryContextCache, which stores retry contexts in a thread-safe in-memory ConcurrentHashMap:
RetryTemplate template = new RetryTemplate(); template.setRetryContextCache(new MapRetryContextCache(1000)); // capacity 1000
When you need a custom RetryContextCache:
- Clustered/distributed environments: If your application runs on multiple nodes and a retryable job item can be picked up by a different node on the next attempt, the in-memory cache will be empty on the new node. A Redis- or database-backed cache solves this.
- Cache eviction concerns: The default map has no TTL. Items for permanently failed operations that were never cleaned up accumulate over time. A custom cache with TTL prevents memory leaks.
- Very large workloads: Spring Batch jobs processing millions of items may exhaust the default map capacity.
Implement the RetryContextCache interface (two methods: get(Object key) and put(Object key, RetryContext context)) to provide a distributed or TTL-aware alternative.
More Related questions...