Spring / Spring Retry Interview Questions
1. What is Spring Retry and why is it used?
Spring Retry is a framework module that provides declarative and programmatic support for retrying failed operations in Spring-based applications. It is used to automatically re-execute a block of code when a transient failure occurs — such as a network timeout, a temporary database connection dr...
2. How do you add Spring Retry to a Spring Boot project?
To add Spring Retry to a Spring Boot project, you include the spring-retry dependency in your build file and enable retry support with an annotation on your configuration class. Maven dependency:
3. What is the @Retryable annotation and what are its key attributes?
The @Retryable annotation is placed on a Spring-managed bean method to declare that it should be retried automatically when it throws a specified exception. Spring Retry wraps the method in an AOP proxy and applies the configured retry policy transparently to the caller. Key attributes of @Retrya...
4. What is the @Recover annotation and when is it invoked?
The @Recover annotation marks a fallback method that Spring Retry calls when all retry attempts for a @Retryable method have been exhausted without success. It provides a graceful degradation path instead of allowing the exception to propagate to the caller. Rules for a valid @Recover method: It ...
5. What is the @Backoff annotation and how does it control retry delays?
The @Backoff annotation is a nested annotation used within @Retryable to define the waiting strategy between consecutive retry attempts. Without a backoff, retries happen immediately one after another, which can overwhelm a struggling resource. @Backoff introduces controlled delays to give the fa...
6. What is RetryTemplate and how does it differ from annotation-based retry?
RetryTemplate is the programmatic API for Spring Retry. It allows you to define retry behavior as code rather than annotations, giving you full control over when, how, and around which blocks of code retry logic is applied — including lambda expressions or any non-Spring-managed code. When using ...
7. What are the different retry policies available in Spring Retry?
Spring Retry ships with several built-in RetryPolicy implementations. Each controls the conditions under which a retry is attempted. Choosing the right one depends on whether you want to limit by count, time, exception type, or a combination of these. Spring Retry Policy Types Policy Description ...
8. What is a BackOffPolicy in Spring Retry and what implementations are available?
A BackOffPolicy defines how long Spring Retry waits between consecutive retry attempts. It is applied by the RetryTemplate after each failed attempt and before the next. The goal is to give the failing resource time to recover and to avoid hammering it with rapid successive requests. Available Ba...
9. What is a RetryContext and what information does it carry?
RetryContext is an object created by Spring Retry at the start of each retry sequence and passed through every retry attempt. It acts as a stateful record of the current retry operation, storing information that policies, listeners, and recovery callbacks can inspect or modify. Key information av...
10. How does the RetryListener interface work in Spring Retry?
RetryListener is a callback interface that lets you hook into retry lifecycle events without modifying the retried method or recovery logic. It is useful for metrics collection, structured logging, and alerting. The RetryListener interface defines three methods: public interface RetryListener { <...
11. How does Spring Retry implement the circuit breaker pattern?
Spring Retry includes a CircuitBreakerRetryPolicy that implements the circuit breaker pattern on top of its standard retry infrastructure. The circuit acts as a gate that opens when failure rates exceed a threshold, temporarily blocking retries to prevent further load on a failing downstream syst...
12. 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 seq...
13. How do you configure Spring Retry using application properties in Spring Boot?
Spring Retry itself does not directly read application.properties — its configuration is annotation or bean-driven. However, Spring Boot's auto-configuration for retry integrates with property placeholders, allowing you to externalize retry parameters using Spring Expression Language (SpEL) refer...
14. What is the difference between include and exclude in @Retryable?
In older versions of Spring Retry, @Retryable had include and exclude attributes to specify which exception classes should or should not trigger a retry. In newer versions (Spring Retry 1.3+), these were renamed to retryFor and noRetryFor respectively for clarity, though the old names are still s...
15. How does Spring Retry integrate with Spring Batch?
Spring Batch has first-class integration with Spring Retry at the step level. When configuring a Step , you can specify retry behavior on the StepBuilder so that item processing failures trigger automatic retries before the item is sent to the skip list or causes the step to fail. Step-level retr...
16. What common pitfalls should you avoid when using @Retryable?
Several mistakes are frequently made when developers first start using @Retryable . Being aware of these pitfalls saves significant debugging time. 1. Self-invocation problem Calling a @Retryable method from within the same class bypasses the AOP proxy, and the retry logic is silently ignored: //...
17. How do you write a unit test for a @Retryable method?
Testing a @Retryable method requires a Spring context because retry logic is applied by the AOP proxy. A plain unit test that calls the method on a new instance will not trigger retries. The recommended approach uses @SpringBootTest or a focused @SpringJUnitConfig with @EnableRetry . Test setup: ...
18. How does Spring Retry handle exceptions that are not in the retryFor list?
When an exception is thrown that is not listed in retryFor (or include in older versions) and is not an Exception.class default match, Spring Retry treats it as a non-recoverable failure and immediately rethrows it without retrying, regardless of how many attempts remain. This behavior is intenti...
19. What is the RetryOperationsInterceptor and how is it used?
RetryOperationsInterceptor is an AOP method interceptor provided by Spring Retry that allows you to apply retry behavior to beans programmatically without using @Retryable annotations. It bridges Spring AOP (MethodInterceptor) with Spring Retry (RetryOperations/RetryTemplate). This is useful when...
20. How can you use Spring Retry with Spring WebClient or RestTemplate?
Spring Retry can wrap calls made through RestTemplate or WebClient to handle transient HTTP failures automatically. The approach differs slightly between the two due to their synchronous vs reactive nature. With RestTemplate (synchronous) — using @Retryable: @Service public class OrderClient { @R...
21. How does the ExceptionClassifierRetryPolicy work?
ExceptionClassifierRetryPolicy allows you to map different exception types to different RetryPolicy instances. This is valuable when your retryable operation can fail with multiple exception types that require different retry strategies — for example, transient network errors should be retried se...
22. What is the RetryCallback interface in Spring Retry?
RetryCallback is a functional interface that wraps the operation to be retried when using RetryTemplate programmatically. It represents the unit of work that may fail and should be retried. @FunctionalInterface public interface RetryCallback < T, E extends Throwable > { T doWithRetry(RetryContext...
23. How does Spring Retry differ from Resilience4j Retry?
Both Spring Retry and Resilience4j Retry solve the same problem — retrying failed operations — but they differ significantly in design philosophy, feature set, and integration style. Spring Retry vs Resilience4j Retry Feature Spring Retry Resilience4j Retry Design focus Spring-native, AOP-first F...
24. 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...
25. Can Spring Retry be used with Spring Cloud OpenFeign? How?
Yes, Spring Retry integrates with Spring Cloud OpenFeign to add retry capability to Feign client calls. When Spring Retry is on the classpath and spring.cloud.openfeign.okhttp.enabled or Feign defaults are in use, you can configure retry through Feign's own Retryer mechanism or delegate to Spring...
26. How do you implement a custom RetryPolicy in Spring Retry?
You can implement a custom RetryPolicy by implementing the RetryPolicy interface, which gives you full control over whether a retry should be allowed based on any criteria — not just exception type or count. Custom policies are useful when retry decisions depend on application-specific state, suc...
27. How do you use Spring Retry with Spring Kafka consumers?
Spring Kafka provides its own retry and error-handling abstractions, but Spring Retry integrates naturally through the SeekToCurrentErrorHandler (or DefaultErrorHandler in newer versions) combined with FixedBackOff or ExponentialBackOff . Configuring retry in a Kafka listener container: @Bean pub...
28. What is the proxyTargetClass attribute in @EnableRetry?
The proxyTargetClass attribute of @EnableRetry controls whether Spring Retry uses subclass-based CGLIB proxies or interface-based JDK dynamic proxies to intercept methods annotated with @Retryable . Default behavior: @EnableRetry // proxyTargetClass = false by default public class AppConfig { } W...
29. How does the CompositeRetryPolicy work in Spring Retry?
CompositeRetryPolicy combines multiple RetryPolicy instances into one. It supports two composition modes: optimistic and pessimistic. This is useful when you need retry behavior that satisfies multiple independent conditions simultaneously. Optimistic mode (default): A retry is allowed if any of ...
30. What is the difference between retry and idempotency? Why does it matter?
Retry and idempotency are closely related but distinct concepts that must be understood together when designing resilient systems. Retry is the mechanism of re-executing a failed operation. Idempotency is the property of an operation that guarantees the same result regardless of how many times it...
31. How do you configure Spring Retry to use a fixed backoff programmatically?
A fixed backoff means the same delay is applied between every retry attempt, regardless of how many attempts have occurred. This is appropriate when the failure cause is likely to resolve in a predictable timeframe and exponential growth in delay is not needed. Using RetryTemplate.builder() (mode...
32. What is the maxAttemptsExpression attribute and how does it differ from maxAttempts?
Both maxAttempts and maxAttemptsExpression in @Retryable control how many total attempts (including the first try) are made. The difference is that maxAttempts accepts a hardcoded integer literal, while maxAttemptsExpression accepts a Spring Expression Language (SpEL) string that is evaluated at ...
33. How does Spring Retry integrate with Spring's @Transactional?
The interaction between @Retryable and @Transactional depends critically on the order of proxy application . If a method is annotated with both, the retry proxy must wrap the transaction proxy — not the other way around. This ensures that when a failure occurs, the transaction is fully rolled bac...
34. What is the use of the recover attribute in @Retryable?
The recover attribute in @Retryable allows you to explicitly name the recovery method that should be invoked when all retry attempts are exhausted. Without this attribute, Spring Retry uses automatic method matching — it looks for a @Recover method in the same bean whose return type and exception...
35. What are transient vs permanent failures and why does the distinction matter for retry?
Correctly classifying failures as transient or permanent is the foundation of any effective retry strategy. Retrying permanent failures wastes resources and delays the surfacing of bugs; failing to retry transient failures reduces system resilience unnecessarily. Transient failures are temporary,...
36. How do you implement retry with a custom exception condition using RetryPolicy?
Sometimes the retry decision cannot be based on exception type alone — it needs to inspect the exception message, error code inside the exception, or a response payload embedded in a custom exception. In this case, you implement a custom RetryPolicy or use SimpleRetryPolicy with a map and a subcl...
37. How does Spring Retry handle the case when @Recover returns void?
A @Recover method can return void if and only if the corresponding @Retryable method also returns void . Spring Retry's recovery method matching requires that the return types align. If there is a mismatch, Spring Retry will not find the recovery method and will rethrow the final exception. Corre...
38. What is exponential backoff with jitter and why is it preferred over plain exponential backoff?
Exponential backoff increases the delay between retries by multiplying the previous delay by a factor (e.g., 2). While this prevents relentless hammering, it creates a new problem in high-concurrency systems: all clients that started failing at the same time will retry at exactly the same interva...
39. How can you monitor and observe Spring Retry behavior in production?
Observing retry behavior in production is essential for detecting systemic issues with downstream dependencies. Spring Retry provides hooks through RetryListener , and for Spring Boot applications, you can wire this into Micrometer for metrics or into logging frameworks for audit trails. Approach...
40. What is the difference between RetryTemplate.execute() and RetryTemplate.executeWithLoadBalancer()?
RetryTemplate.execute() is the standard method for running a retryable operation. It takes a RetryCallback and optionally a RecoveryCallback , then applies the configured retry policy and backoff until the operation succeeds or retries are exhausted. There is no method named executeWithLoadBalanc...