Retry Pattern
Resilience4j Retry — max attempts, wait duration, exponential backoff, retry on exceptions
- Automatically retry failed calls with @Retry and Retry.executeCallable()
- Configure exponential backoff with jitter to avoid retry storms
- Limit retries to specific exception types
Table of Contents
- Overview
- Why Retry Exists
- Definition
- Real-World Analogy
- Why the Client Shouldn't Just Retry Itself
- When to Retry — Core Rules
- Idempotency and Retry
- HTTP Status Code Retry Decision Table
- Types of Retry Strategies
- 1. Fixed Interval Retry
- 2. Exponential Backoff
- 3. Exponential Backoff + Jitter
- 4. Custom Interval Retry
- Comparison Table of Retry Strategies
- Spring Boot Implementation — Fixed Interval Retry
- Spring Boot Implementation — Exponential Backoff
- Spring Boot Implementation — Exponential Backoff + Jitter
- Internal Working — How AOP Builds the Retry Object
- Custom Retry — Manual Implementation
- Execution Walkthrough (Observed Behavior)
- Memory Representation
- Common Mistakes
- Best Practices
- Interview Notes
- Related Concepts
- Practice Questions
- Summary
Overview
Retry is one of the five Resilience4j fault-tolerance mechanisms (alongside Rate Limiter, Bulkhead, Time Limiter, and Circuit Breaker), and — per the recommended logical ordering covered elsewhere in this series — it comes last in the sequence: Rate Limiter → Bulkhead → Time Limiter → Circuit Breaker → Retry.
Retry allows a system to automatically re-attempt a failed downstream call, on the theory that many failures in a distributed system are transient (short-lived, temporary) and will succeed if simply attempted again after a short delay.
Why Retry Exists
In a distributed system, a call to a downstream service can fail due to transient issues — short-lived, temporary problems such as network glitches or timeouts — rather than any fundamental, lasting problem with the request itself. Retrying the same request after a short delay can often succeed, simply because the transient condition has since resolved.
Definition
Retry
is a fault-tolerance mechanism that automatically re-attempts a failed operation (typically a downstream service call) a configured number of times, using a configured delay strategy between attempts, in order to recover from transient failures without requiring manual intervention or requiring the original caller to resubmit the entire request.
Real-World Analogy
Imagine calling a friend on the phone and the call drops due to a brief signal issue. You don't hang up, walk to the store, and ask a stranger to relay a completely new message to your friend from scratch — you simply redial a few seconds later, because the problem was almost certainly momentary (a dead zone, a dropped tower handoff), not something fundamentally wrong with your friend's phone number.
Now imagine you'd already spent 10 minutes explaining a complicated situation to your friend before the call dropped, and only had one more sentence left to say. Hanging up and asking someone else to start that whole 10-minute explanation over again from scratch (analogous to asking the client to resubmit and reprocess the entire original request) would be enormously wasteful compared to simply redialing and finishing that last sentence (analogous to letting the system retry just the failed step, at the point where 90% of the work is already done).
Why the Client Shouldn't Just Retry Itself
A natural question: if a downstream call can fail transiently, why does the system itself need to implement retry logic? Why not simply let the client (the original caller of our API) invoke our API again if it fails?
The Answer: Cost of Redundant Work
For each incoming API call, a service typically performs heavy processing — and that processing is not free. It consumes memory, time, and compute resources.
Consider this scenario:
If the system itself retries just the failed downstream call, only the remaining (uncompleted) portion of work needs to be redone. But if the client is instead asked to resubmit the entire original request, the already-completed 90% of processing gets thrown away and redone entirely — a pure waste of resources.
When to Retry Core Rules
Knowing that retry is valuable doesn't answer the harder question: when exactly should a retry actually be attempted? There are several critical rules.
Rule 1 Do NOT Retry on Permanent Failures
A permanent failure is one that will always fail, no matter how many times it is retried. The classic example is a 4xx error, which generally falls into the category of a validation error — the client's input request itself is incorrect. Unless the client changes the input, retrying with the exact same request will simply reproduce the same validation error every time.
Rule 2 Do NOT Retry if the Operation Is Non-Idempotent
Covered in full detail in the next section — retrying a non-idempotent operation risks creating duplicate resources.
Rule 3 Rule of Thumb: Retry Only on 5xx Errors
A 5xx error indicates a system error — the client's input request was fine (it passed all validation), but something went wrong on the system/server side. Since:
- The input request itself is known to be correct (no validation issue), and
- The previous request is confirmed to have been unsuccessful,
...it is generally safe to retry on 5xx errors, since there's a reasonable chance the underlying system issue might resolve itself (e.g., a transient overload, a temporary downstream outage) by the time the retry executes.
Rule 4 Retry Network Errors and Timeouts (With Idempotency Caveat)
Network errors and timeout errors should generally be retried — but only if the API being called supports idempotency (see next section for why).
Idempotency and Retry
Why This Matters A Worked Example
Consider Service A invoking a create API on Service B:
- Service A's request to Service B times out from Service A's point of view — but internally, Service B did successfully insert the row into its database before the timeout occurred on Service A's side.
- Because Service A perceived a failure (timeout), it retries — and Service B, having no way to recognize this as "the same request as before," simply performs the create operation again, inserting a second, duplicate row (
Id: 2) for what was semantically a single logical request.
create API) is not idempotent — calling it multiple times with logically the same request does not produce the same end state as calling it once; instead, it produces duplicate side effects (duplicate database rows, in this example).HTTP Status Code Retry Decision Table
HTTP Status Code Retry Decision Table
| HTTP Status Code | Meaning | Retry? | Reasoning |
|---|---|---|---|
| 200 | Success | ❌ No | Request already succeeded — nothing to retry. |
| 400 | Bad Request | ❌ No | Validation error — permanent failure; retrying with the same input always fails again. |
| 401 | Unauthorized | ❌ No | Validation/auth error — permanent failure until credentials change. |
| 403 | Forbidden | ❌ No | Validation/permission error — permanent failure. |
| 404 | Not Found | ❌ No | Validation-category error — permanent failure; the resource doesn't exist regardless of retries. |
| 429 | Too Many Requests | ✅ Yes (with delay) | Caused by rate limiting — retrying after a delay can succeed once the rate limit window resets. |
| 500 | Internal Server Error | ✅ Yes | System error — input was valid; retry may succeed if the transient system issue resolves. |
| 502 | Bad Gateway | ✅ Yes | System error — often transient upstream/gateway issue. |
| 503 | Service Unavailable | ✅ Yes | The service may have been temporarily down; retrying might succeed once it's back up. |
| Network Error / Timeout | Connectivity issue | ✅ Yes (if idempotent) | Likely transient — but only safe to retry if the operation is confirmed idempotent. |
Types of Retry Strategies
There are four main retry strategies, differing in how the delay between retry attempts is computed.
1. Fixed Interval Retry
Definition: Retry after a constant delay — the same delay duration is used between every retry attempt.
Example: Total attempts = 4 (1 original call + 3 retries), fixed delay = 2 seconds.
◆ Worked Thundering Herd Example
2. Exponential Backoff
Definition: The delay between retries increases exponentially over time, rather than remaining fixed.
Formula:
1delay = base_delay × (factor ^ number_of_failed_retry_attempts)Example: base_delay = 100ms, factor = 2, total attempts = 4 (1 original + 3 retries).
| Attempt | Failed Attempts So Far | Formula | Delay |
|---|---|---|---|
| Original call | — | — | occurs at t = 0ms |
| Retry 1 | 0 | 100 × 2^0 | 100ms → occurs at t = 100ms |
| Retry 2 | 1 | 100 × 2^1 | 200ms → occurs at t = 300ms |
| Retry 3 | 2 | 100 × 2^2 | 400ms → occurs at t = 700ms |
base_delay and factor values with no randomness, they will still end up retrying at the exact same computed times as each other.
- Added latency when the outage is actually short-lived: if the underlying issue resolves quickly (e.g., within 500ms), but the next scheduled retry isn't due until 800ms (per the exponential formula), the caller still has to wait the full 800ms before the successful retry occurs — even though the problem was already fixed earlier.3. Exponential Backoff + Jitter
Definition: Same exponential growth in delay as standard Exponential Backoff, but with an added random component ("jitter") to help avoid retry storms/thundering herd more effectively.
Formula:
1delay = random(0, min(max_delay, base_delay × (factor ^ number_of_failed_retry_attempts)))max_delayis a hard ceiling — no matter how large the exponential formula's raw output grows, the delay will never exceed this configured maximum (e.g., 5 seconds).- A random value is then chosen between
0and the smaller of (max_delay, the exponential backoff formula's computed value) for that attempt.
4. Custom Interval Retry
Definition: You define your own fully custom retry delay logic — for example, a Fibonacci-style sequence: wait 1ms, then 1ms, then 2ms, then 3ms, then 5ms, then 8ms, and so on.
Comparison Table of Retry Strategies
| Strategy | Delay Pattern | Thundering Herd Risk | Complexity | Best Used When |
|---|---|---|---|---|
| Fixed Interval | Constant delay every retry | High | Very Low | Simple use cases, low concurrent client volume |
| Exponential Backoff | Delay grows exponentially | Medium (reduced, not eliminated) | Low-Medium | Downstream service needs recovery time under load |
| Exponential Backoff + Jitter | Exponential + randomization | Low | Medium-High | High-concurrency systems where retry storms are a real risk |
| Custom Interval | Fully user-defined | Depends entirely on your logic | High (self-maintained) | Specialized retry patterns not covered by the built-in strategies |
Spring Boot Implementation Fixed Interval Retry
Step 1 Annotate the Method to Retry
1@Service2public class OrderService {3
4 @Autowired5 private ProductClient productClient;6
7 @Retry(name = "productService", fallbackMethod = "productServiceFallback")8 public String invokeProductApi() {9 try {10 return productClient.getProductById("1");11 } catch (Exception e) {12 throw new RuntimeException("Not able to invoke product API");13 }14 }15
16 public String productServiceFallback(Throwable throwable) {17 return "Product service is busy";18 }19}@Retry annotation directly on the method containing only the specific logic you actually want retried. If the annotated method also contains a lot of unrelated business logic, or a database call, all of it will get re-executed on every retry attempt — not just the downstream call you intended to protect. Double-check exactly what logic lives inside the annotated method, since all of it is subject to retry.Step 2 Configuration (`application.properties`)
1resilience4j.retry.instances.productService.max-attempts=32resilience4j.retry.instances.productService.wait-duration=2sConfiguration Breakdown
| Property | Meaning |
|---|---|
max-attempts | Total number of attempts, including the original call. Here, 3 means 1 original call + 2 retries. |
wait-duration | The fixed delay between attempts — here, 2 seconds. Values can also be specified in milliseconds (e.g., 500ms) or other duration units. |
Observed Output
120:56:10 → Original call: Not able to invoke product API2[wait 2s]320:56:12 → Retry 1: Not able to invoke product API4[wait 2s]520:56:14 → Retry 2: Not able to invoke product API6→ All retries exhausted → Fallback: "Product service is busy"The fixed 2-second gap between each attempt is clearly visible in the timestamps, confirming the constant-delay behavior of Fixed Interval retry.
Spring Boot Implementation Exponential Backoff
Configuration
1resilience4j.retry.instances.productService.max-attempts=42resilience4j.retry.instances.productService.wait-duration=1s3resilience4j.retry.instances.productService.enable-exponential-backoff=true4resilience4j.retry.instances.productService.exponential-backoff-multiplier=2Configuration Breakdown
| Property | Meaning |
|---|---|
max-attempts=4 | 1 original call + 3 retries. |
wait-duration=1s | The initial wait time (used as the base delay in the exponential formula) — here, 1 second (1000ms). |
enable-exponential-backoff=true | Explicitly enables exponential backoff, since it is not the default retry strategy. |
exponential-backoff-multiplier=2 | The multiplication factor used in the exponential formula — here, 2, meaning the delay is based on 2 raised to increasing powers. |
Computed Delays
Using the formula delay = initial_wait × multiplier^(retry_iteration - 1):
| Attempt | Delay Computation | Delay | Occurs At (relative) |
|---|---|---|---|
| Original call | — | — | t = 0s |
| Retry 1 | 1000ms × 2^0 | 1s | t = 1s |
| Retry 2 | 1000ms × 2^1 | 2s | t = 3s |
| Retry 3 | 1000ms × 2^2 | 4s | t = 7s |
Observed Output
121:22:40 → Original call2[wait 1s]321:22:41 → Retry 14[wait 2s]521:22:43 → Retry 26[wait 4s]721:22:47 → Retry 38→ All 4 attempts exhausted → Fallback executedThe growing gaps between timestamps (1s, then 2s, then 4s) confirm the exponential growth in delay.
Backoff implementation class) implements exactly this same formula: initial_wait_time × factor^(number_of_failed_retry_attempts).Spring Boot Implementation Exponential Backoff + Jitter
Configuration
1resilience4j.retry.instances.productService.max-attempts=42resilience4j.retry.instances.productService.wait-duration=1s3resilience4j.retry.instances.productService.enable-exponential-backoff=true4resilience4j.retry.instances.productService.exponential-backoff-multiplier=25resilience4j.retry.instances.productService.enable-randomized-wait=trueenable-randomized-wait=true. This single flag is what tells Resilience4j to compute delays using its randomized backoff method internally, rather than the plain (non-randomized) exponential backoff method — adding the jitter/randomness behavior described earlier.Internal Working How AOP Builds the Retry Object
@Retry annotation, like @RateLimiter, relies entirely on AOP to work — specifically, AOP generates proxy code at runtime. Because this code is generated dynamically, it cannot be directly stepped through in a debugger. The explanation below describes, conceptually, what that generated code is understood to be doing internally — it is for understanding purposes, not something you can literally inspect line-by-line in your own codebase.The retry mechanism internally revolves around three conceptual parts:
1. Interval Function
This is the component responsible for computing the delay logic between attempts. Resilience4j ships with a framework class (an "Interval Function" class) containing multiple pre-built methods:
- One method for fixed delay computation (
IntervalFunction.of(...)). - One method for exponential backoff computation (
IntervalFunction.ofExponentialBackoff(...)). - One method for exponential backoff with jitter/randomness.
You generally do not need to implement this yourself unless you're writing fully custom retry logic (covered in the next section) — you simply reference the appropriate built-in method, and the framework computes delays for you.
2. Retry Config
This is where configuration values are set — maximum attempt count, which interval function to use, and which exceptions should trigger a retry.
Conceptually, the generated AOP code performs something equivalent to:
1RetryConfig config = RetryConfig.custom()2 .maxAttempts(3) // from configuration3 .intervalFunction(IntervalFunction.of(2000)) // fixed 2s delay, from configuration4 .retryExceptions(SomeException.class) // which exceptions to retry on5 .build();3. Retry Object
From the built RetryConfig, an actual Retry object is created — this is the object that will actually be used to perform the retry logic against your annotated method.
1Retry retry = Retry.of("productService", config);How It All Connects
- AOP determines which interval function method to use based on the explicit configuration provided (defaulting to fixed interval if nothing else is specified).
- It builds a
RetryConfigusing themax-attempts,wait-duration, and any configured retryable exceptions. - It creates a
Retryobject from that config. - It then wraps the logic inside your
@Retry-annotated method using thatRetryobject, so that failures automatically trigger delay computation and re-invocation, up to the configured maximum attempts — after which the fallback method is invoked instead.
Custom Retry Manual Implementation
@Retry internally depends on configuration (application.properties) to build its RetryConfig and Retry object, you cannot use the @Retry annotation for a fully custom retry strategy that has no fixed configuration values (like a Fibonacci-based delay sequence). Instead, you must manually construct the Retry object yourself, following the exact same three-part structure AOP would otherwise build for you automatically.Step 1 Define Your Custom Interval Function
1@Configuration2public class RetryConfiguration {3
4 @Bean5 public Retry customRetry() {6
7 IntervalFunction fibonacciInterval = attempt -> {8 // Simplified for demonstration purposes —9 // returns the delay (in milliseconds) to wait before the given retry attempt10 return 2000L; // hardcoded here for demo simplicity11 };12
13 RetryConfig retryConfig = RetryConfig.custom()14 .maxAttempts(6)15 .intervalFunction(fibonacciInterval)16 .retryExceptions(RuntimeException.class)17 .build();18
19 return Retry.of("customProductServiceRetry", retryConfig);20 }21}Syntax Breakdown
| Element | Meaning |
|---|---|
IntervalFunction fibonacciInterval = attempt -> {...} | A custom lambda implementing your own delay-computation logic. In a full Fibonacci implementation, this would compute delays following a Fibonacci-like sequence (1ms, 1ms, 2ms, 3ms, 5ms, 8ms...); the demonstration version here simply hardcodes a fixed 2000ms delay for simplicity. |
RetryConfig.custom() | Begins building a custom retry configuration, exactly analogous to what AOP would otherwise construct automatically from application.properties. |
.maxAttempts(6) | Total attempts — here, 1 original call + 5 retries. |
.intervalFunction(fibonacciInterval) | Registers your custom delay logic to be used between attempts. |
.retryExceptions(RuntimeException.class) | Specifies which exception types should trigger a retry. |
Retry.of("customProductServiceRetry", retryConfig) | Creates the actual Retry object from the built configuration, given a chosen name. |
Step 2 Manually Wrap Your Retryable Logic
Since @Retry cannot be used here, the method to be retried must be manually wrapped using the created Retry bean:
1@Service2public class OrderService {3
4 @Autowired5 private ProductClient productClient;6
7 @Autowired8 private Retry customProductServiceRetry;9
10 public String invokeProductApi() {11 Supplier<String> retryableSupplier = Retry.decorateSupplier(12 customProductServiceRetry,13 () -> {14 System.out.println("Calling product service at " + Instant.now());15 return productClient.getProductById("1");16 }17 );18
19 try {20 return retryableSupplier.get();21 } catch (Exception e) {22 return "All retries failed. This is fallback.";23 }24 }25}Syntax Breakdown
| Element | Meaning |
|---|---|
@Autowired private Retry customProductServiceRetry; | Injects the manually-created Retry bean via dependency injection — the same bean object AOP would otherwise have created and used internally. |
Retry.decorateSupplier(retry, supplier) | Wraps ("decorates") a piece of code — here, the actual call to productClient.getProductById(...) — inside the given Retry object, so that failures automatically trigger retry logic according to the retry object's configuration. |
() -> { ... } | The functional Supplier lambda representing exactly the logic you want retried — in this case, the downstream product service call. |
retryableSupplier.get() | Actually executes the wrapped, retry-enabled logic. If it fails and attempts remain, the Retry object automatically computes the next delay (via your custom interval function), waits, and retries. |
catch (Exception e) { return "All retries failed..."; } | Once all configured attempts are exhausted, this manually-written catch block serves the same purpose as a fallbackMethod would in the annotation-based approach. |
@Retry annotation's AOP machinery is doing behind the scenes: (1) build an Interval Function, (2) build a Retry Config, (3) create a Retry object from that config, and (4) wrap the target logic inside that Retry object so failures trigger automatic retry behavior.Observed Output
Since the demonstration interval function is hardcoded to always return a 2000ms delay:
1Calling product service at 22:35:452[wait 2s]3Calling product service at 22:35:474[wait 2s]5Calling product service at 22:35:496[wait 2s]7Calling product service at 22:35:50 (approx.)8... (continues for all 6 attempts) ...9→ All retries failed. This is fallback.Execution Walkthrough (Observed Behavior)
Fixed Interval Example (`max-attempts=3`, `wait-duration=2s`)
Exponential Backoff Example (`max-attempts=4`, `wait-duration=1s`, `multiplier=2`)
Custom Retry Example (`max-attempts=6`, hardcoded 2s delay)
Memory Representation
- The Retry Configuration (max attempts, wait duration, exponential settings) is read once and lives at the application/context level, similar in spirit to the Method Area's shared, relatively static data.
- The Retry object itself — tracking things like the interval function to use — lives on the heap, shared across invocations of the same named retry instance.
- Each invoking thread has its own stack frame for the method call and the AOP interception logic, but all such threads interact with the same shared
Retryobject configuration when determining delay behavior.
Common Mistakes
@Retry retries the entire annotated method's logic — if that method also includes unrelated business logic or database writes beyond the specific downstream call you meant to protect, all of that extra logic gets re-executed on every retry attempt too.base_delay and factor values will still retry at the exact same computed moments as each other — Exponential Backoff alone only reduces, but does not eliminate, this risk.Best Practices
- ✅ Only retry on failures known to be transient and safe to repeat — primarily 5xx system errors, and network/timeout errors where idempotency is confirmed.
- ✅ Never retry on 4xx validation errors — they represent permanent failures that retries cannot fix.
- ✅ Confirm an operation is idempotent before enabling retry on it, to avoid duplicate resource creation.
- ✅ Place
@Retry(and similarly scoped annotations) only around the specific logic you intend to retry — keep unrelated business logic and database writes out of the annotated method. - ✅ Prefer Exponential Backoff with Jitter for production systems with meaningful concurrent client volume, since it best balances reduced downstream load with mitigated thundering herd risk.
- ✅ Set a sensible
max_delayceiling when using exponential-style strategies, to avoid unbounded wait times for later retry attempts. - ✅ Reserve fully custom retry logic for genuinely specialized cases — the lecture's own experience notes that Exponential Backoff with Jitter is typically sufficient for the vast majority of real-world use cases.
Interview Notes
- "Why implement retry in the system itself instead of letting the client retry?"
Because a significant portion of processing may already be complete by the time a downstream transient failure occurs; retrying just the failed step avoids redoing already-completed work, which becomes a substantial resource savings at scale across many concurrent clients.
- "When should you NOT retry?"
On permanent failures (4xx validation errors) and on non-idempotent operations, since retries in both cases either waste resources reproducing an unfixable error, or risk creating duplicate resources/side effects.
- "What does idempotency mean in the context of retry, and why does it matter?"
Idempotency ensures that retrying a request multiple times does not cause duplicate processing/side effects. Without it, a retried create operation, for example, could insert duplicate database rows for what was semantically a single logical request.
- "What is the Thundering Herd Problem, and how do different retry strategies address it?"
It occurs when many clients retry simultaneously, overwhelming the system with retry traffic. Fixed Interval retry has the highest risk (all clients retry at identical fixed delays). Exponential Backoff reduces but doesn't eliminate the risk (still deterministic, so identical configs cluster). Exponential Backoff with Jitter adds randomness, spreading retries out and substantially reducing this risk.
- "What's the formula for Exponential Backoff?"
delay = base_delay × (factor ^ number_of_failed_retry_attempts).
- "What's the formula for Exponential Backoff with Jitter?"
delay = random(0, min(max_delay, base_delay × (factor ^ number_of_failed_retry_attempts))).
- "How does
@Retrywork internally?"
Through AOP-generated proxy code that builds three components: an Interval Function (delay computation logic), a Retry Config (max attempts, exceptions to retry on, which interval function to use), and a Retry object (created from the config) — which then wraps the annotated method so that failures trigger automatic delay-and-retry behavior, up to the configured maximum attempts, after which the fallback method runs.
- "Why can't you use the
@Retryannotation for a fully custom retry strategy?"
Because @Retry depends on declarative configuration (from application.properties) to construct its RetryConfig and Retry object internally. A fully custom strategy (e.g., Fibonacci-based delays) has no such fixed configuration to declare, so you must manually build the Retry object yourself and explicitly wrap your retryable logic using something like Retry.decorateSupplier(...).
- "What HTTP status codes are generally safe to retry, and which are not?"
Safe: 429 (with delay), 500, 502, 503, and network/timeout errors (if idempotent). Not safe: 400, 401, 403, 404 — all validation-category permanent failures.
Related Concepts
- Rate Limiter, Bulkhead, Time Limiter, Circuit Breaker — The other four Resilience4j mechanisms; Retry is placed last in the recommended logical ordering, after all of these.
- Thundering Herd Problem — A broader distributed-systems concept covered in more depth elsewhere in this series; directly relevant to why Fixed Interval retry is risky at scale, and why jitter is introduced.
- Idempotency & API Design — Covered in depth in dedicated high-level system design material; essential prerequisite knowledge for deciding whether an operation is safe to retry.
- AOP (Aspect-Oriented Programming) — The underlying mechanism powering
@Retry(and@RateLimiter) via dynamically generated proxy code at runtime. - HTTP Status Codes (4xx vs 5xx) — The foundational classification used throughout this guide's retry decision rules.
- Circuit Breaker — Closely related to Retry; a circuit breaker can prevent retries from even being attempted against a service that is currently known to be failing repeatedly, complementing retry logic.
Practice Questions
Easy
- What does it mean for a failure to be "transient," and why does this matter for retry?
- Name the four retry strategies covered in this guide.
- What does
max-attemptsrepresent — does it include the original call?
Medium
- Explain why retrying a non-idempotent
createoperation can result in duplicate database rows, using the Service A / Service B example. - Compare Fixed Interval and Exponential Backoff in terms of Thundering Herd risk and latency behavior when an outage resolves quickly.
- Why must
@Retry's annotated method be scoped carefully — what happens if it contains more logic than just the intended downstream call?
Hard
- Derive, step by step, the exact delay values for the first three retries under Exponential Backoff with
base_delay = 200msandfactor = 3. - Explain, using AOP terminology (Interval Function, Retry Config, Retry Object), exactly what components are built internally when a method is annotated with
@Retry, and describe why this same structure must be built manually for a fully custom retry strategy. - Design (conceptually) a custom Fibonacci-based
IntervalFunctionfor a Resilience4jRetryobject — what state would it need to track between calls to correctly return 1ms, 1ms, 2ms, 3ms, 5ms, 8ms on successive invocations?
Summary
- Retry automatically re-attempts a failed downstream call to recover from transient issues, and belongs last in the recommended Resilience4j ordering (Rate Limiter → Bulkhead → Time Limiter → Circuit Breaker → Retry).
- Retry logic belongs in the system itself, not pushed back onto the client, because significant processing work may already be complete by the time a downstream failure occurs — retrying just the failed step avoids wastefully redoing that completed work.
- Do not retry on permanent failures (4xx validation errors) or on non-idempotent operations, since the former wastes resources on an unfixable error and the latter risks creating duplicate resources/side effects.
- As a rule of thumb, retry on 5xx system errors, and on network/timeout errors only if the operation is confirmed idempotent.
- Four retry strategies exist: Fixed Interval (simple, but high Thundering Herd risk), Exponential Backoff (delay grows exponentially, reduces but doesn't eliminate Thundering Herd risk), Exponential Backoff + Jitter (adds randomness, best mitigates Thundering Herd, but harder to debug), and Custom Interval (fully user-defined logic, full control but no framework support).
- In Spring Boot,
@Retry(name=..., fallbackMethod=...)is configured viaapplication.properties(max-attempts,wait-duration,enable-exponential-backoff,exponential-backoff-multiplier,enable-randomized-wait), and — like@RateLimiter— is implemented entirely through AOP-generated proxy code at runtime, built from three conceptual parts: an Interval Function, a Retry Config, and a Retry Object. - For fully custom retry logic that has no declarative configuration to rely on, the
@Retryannotation cannot be used — instead, you must manually build theRetryobject (interval function + config) yourself and explicitly wrap your target logic using something likeRetry.decorateSupplier(...). - Always place retry annotations narrowly, around only the specific logic intended to be retried — since the entire annotated method's contents are subject to re-execution on every retry attempt.
Mastery check
How well can you recall this?
Finished this lesson?