Retries are supposed to make distributed systems more reliable. Yet a retry policy that ignores latency, load, idempotency and failure semantics can turn a small service interruption into a cascading outage. This guide explains how to design timeouts, bounded retries, exponential backoff, jitter, circuit breakers and bulkheads as one coherent reliability strategy, with practical Java and Spring Boot examples.
You will follow a request through a distributed system, learn why a timeout does not prove that an operation failed, implement safer retry behavior, and examine the operational signals that reveal a retry storm. The central principle is simple: retries are additional load, not free recovery.
1. Why Distributed Calls Fail in More Than One Way
A call from one service to another looks like a method invocation in application code:
PaymentStatus status = paymentClient.getStatus(orderId);
But unlike a local method call, the operation crosses process and network boundaries. The caller depends on DNS resolution, connection establishment, TLS, load balancers, network paths, remote queues, application threads, databases and the remote service's own dependencies. Any of these can introduce latency or failure.
It is useful to distinguish several outcomes:
- Fast failure: The caller receives a clear error, such as a connection refusal.
- Slow response: The remote service eventually responds, but later than the caller can usefully wait.
- Timeout: The caller stops waiting before it receives a response.
- Connection loss: The connection disappears while the request or response is in transit.
- Overload: The service is alive but cannot process incoming work at the current rate.
- Partial success: The remote operation takes effect, but the response never reaches the caller.
These outcomes are not interchangeable. A connection refusal usually indicates that a connection was not established. A read timeout after a POST request is more ambiguous: the server may have committed the operation and then lost the response.
The ambiguity of a timeout
Imagine an order service sends a request to a payment service:
- The order service sends
POST /payments. - The payment service authorizes the payment.
- The payment service commits the result.
- The response is lost because the connection breaks.
- The order service times out.
From the caller's perspective, the result is unknown. It cannot conclude that the payment was not authorized. Blindly sending the same operation again could create a duplicate charge if the payment API does not protect against duplicates.
This is the fundamental problem behind safe retries: a failed observation is not necessarily a failed operation.
The HTTP standard makes a related distinction between safe and idempotent methods. Idempotency concerns the intended effect of repeating a request, not whether every response or side effect is byte-for-byte identical. See RFC 9110, Section 9.2.2.
2. Timeouts: Put a Bound on Waiting
A timeout defines how long a caller is willing to wait for some operation. Without a timeout, a blocked call can retain a thread, connection, memory, queue slot or other resource for an unbounded period.
Timeouts are not a single setting. A typical HTTP client may expose several:
| Timeout | What it limits | What it does not necessarily limit |
|---|---|---|
| DNS timeout | Name resolution | The complete HTTP request |
| Connection timeout | Establishing a connection | Time waiting for the response body |
| TLS handshake timeout | Secure connection negotiation | Application processing |
| Response/read timeout | Waiting for response data | Total time across all retries |
| Pool-acquisition timeout | Waiting for a pooled connection | Remote service execution |
| Overall deadline | End-to-end operation time | Work already accepted by a remote service |
The exact names and semantics vary by HTTP client. Read the documentation for the client in use rather than assuming that a property called readTimeout is a total request deadline.
A timeout budget must fit the caller's deadline
Suppose an incoming API request has a deadline of 1,000 milliseconds. It calls an inventory service and then a pricing service sequentially. If each dependency is allowed to consume the full second, the outer request cannot meet its deadline.
A simplified budget could be:
| Activity | Budget |
|---|---|
| Authentication and local processing | 100 ms |
| Inventory call | 300 ms |
| Pricing call | 300 ms |
| Response assembly and safety margin | 200 ms |
| Total | 900 ms |
The remaining 100 ms is margin, not an invitation to add another unbounded call. In a real system, budgets must account for parallel calls, queueing, retries, network variation and the service-level objective.
Deadlines are stronger than independent timeouts
A timeout on each attempt does not automatically bound the complete operation. If a client allows three attempts of 800 ms each and sleeps between them, total latency can exceed two seconds.
A deadline is an absolute end time or remaining time budget propagated through the call chain. Each downstream operation should use the remaining budget, not restart the original timeout.
Conceptually:
Duration remaining = deadline.remaining();
if (remaining.isZero() || remaining.isNegative()) {
throw new DeadlineExceededException();
}
Duration attemptTimeout = min(configuredAttemptTimeout, remaining);
This is illustrative pseudocode. A production implementation should use the deadline or cancellation mechanism supported by its RPC framework and HTTP client.
Choosing timeout values
Timeouts should be based on observed latency distributions and the latency budget of the caller. A common method is to select a high percentile of downstream latency, then add an explicit margin appropriate to the system and network path. AWS describes this approach in its engineering guidance on timeouts, retries and backoff with jitter.
Do not blindly choose a percentile without considering false timeouts, workload differences, cold starts, connection reuse and the consequences of slow calls. A timeout that is too short creates avoidable failures and retries. One that is too long ties up resources and allows slow dependencies to consume the caller's capacity.
3. Retries: Decide Which Failures Are Worth Another Attempt
A retry repeats an operation after a failure. It can help with transient faults such as a brief connection interruption, temporary overload or a service instance becoming unavailable during a deployment.
It does not fix permanent faults. Retrying invalid input, failed authorization, a missing resource or a deterministic business-rule rejection merely repeats work that cannot succeed.
A retry policy needs at least four decisions:
- Which failures are retryable?
- How many total attempts are allowed?
- How long should the caller wait between attempts?
- What happens when the overall deadline or retry budget is exhausted?
Classify errors by meaning
A simplified policy might look like this:
| Failure | Typical retry decision | Reason |
|---|---|---|
| Invalid request / validation error | Do not retry | Repeating unchanged input will not help |
| Authentication / authorization failure | Do not retry | Credentials or permissions must change |
| Resource not found | Usually do not retry | Often a stable application result |
| Connection refused | Maybe retry | A different instance or short delay may help |
| Connection reset | Maybe retry | Outcome may be ambiguous |
| Request timeout | Maybe retry, if operation is safe | The remote side may have completed it |
| HTTP 429 | Respect server guidance | Client is being rate limited |
| HTTP 503 | Maybe retry within budget | Temporary unavailability is possible |
| HTTP 500 | Context-dependent | Can represent transient or deterministic failure |
This table is a starting point, not a universal mapping. An HTTP status code alone may not reveal whether a particular operation is safe to repeat. Define the behavior in the API contract and distinguish transient infrastructure failures from permanent application failures.
Do not retry at every layer
Suppose a browser, API gateway, order service and payment client each allow three retries after the initial attempt. One user action can create up to:
[
4 \times 4 \times 4 \times 4 = 256
]
downstream attempts in the worst case, if each layer retries independently and the failures propagate through all layers.
The exact number depends on where retries occur and how calls are structured, but the multiplication illustrates the risk. Google SRE guidance specifically warns against retry amplification and recommends limiting retries, using randomized exponential backoff and considering a server-wide retry budget. See Addressing Cascading Failures.
Choose retry ownership deliberately. In many systems, the layer that understands the operation's semantics is the best place to decide whether repeating it is safe. Avoid stacking independent retry policies without calculating their combined attempt count and latency.
4. Exponential Backoff and Jitter
If a dependency is temporarily overloaded, retrying immediately adds work at exactly the moment the service has the least capacity to handle it.
Exponential backoff increases the delay after successive failures. A common form is:
[
d_n = \min(d_{\max}, d_0 \times 2^{n-1})
]
where (d_0) is the initial delay, (n) is the retry number starting at 1, and (d_{\max}) is the maximum delay.
For example, with an initial delay of 100 ms and a cap of 1,000 ms, the nominal delays are 100, 200, 400, 800 and then 1,000 ms.
But exponential backoff alone has a weakness: many clients that fail at the same time can calculate the same retry schedule. They wake up together and create another burst. This is often called a synchronized retry or thundering-herd effect.
Jitter adds randomness to spread retries over time. One common full-jitter strategy is:
[
d_n = U(0, \min(d_{\max}, d_0 \times 2^{n-1}))
]
where (U(0,x)) is a uniformly distributed random delay between zero and (x).
Other jitter strategies exist. The important properties are that clients do not all retry at the same instant and that the delay remains bounded. AWS and Google SRE both discuss jitter as an important part of retry design.
Java example: bounded exponential backoff with full jitter
import java.time.Duration;
import java.util.concurrent.ThreadLocalRandom;
public final class RetryDelay {
private RetryDelay() {}
public static Duration fullJitter(
int retryNumber,
Duration initialDelay,
Duration maxDelay) {
if (retryNumber < 1) {
throw new IllegalArgumentException("retryNumber must be >= 1");
}
if (initialDelay.isNegative() || maxDelay.isNegative()) {
throw new IllegalArgumentException("Delays must not be negative");
}
long initial = initialDelay.toMillis();
long cap = maxDelay.toMillis();
if (initial == 0 || cap == 0) {
return Duration.ZERO;
}
int shift = Math.min(retryNumber - 1, 30);
long exponential;
try {
exponential = Math.multiplyExact(initial, 1L << shift);
} catch (ArithmeticException ex) {
exponential = Long.MAX_VALUE;
}
long upperBound = Math.min(cap, exponential);
return Duration.ofMillis(
ThreadLocalRandom.current().nextLong(upperBound + 1)
);
}
}
This example is intentionally small. Production code should validate configuration, handle duration overflow carefully, use a monotonic clock for elapsed-time calculations and ensure that the delay fits the remaining request deadline. If maxDelay can approach Long.MAX_VALUE, the inclusive upper-bound calculation also needs a safer implementation.
Respect server-provided retry guidance
Some APIs return Retry-After, including in rate-limiting or temporary-unavailability responses. A client should understand the API's contract and honor the server's requested delay where appropriate, while still enforcing its own deadline and retry budget. It should not interpret every 429 or 503 as permission to retry indefinitely.
5. Idempotency: Make Repetition Safe
Idempotency is central to retry safety. An operation is idempotent when repeating it has the same intended effect as performing it once.
HTTP defines methods such as PUT and DELETE as idempotent in terms of their intended effect. That does not mean every implementation is automatically correct, nor does it mean every POST is necessarily unsafe. The semantics of the particular API matter. See RFC 9110.
Consider a payment endpoint:
POST /payments
Content-Type: application/json
{
"orderId": "order-123",
"amount": 49.99,
"currency": "EUR"
}
If the client times out after the payment is accepted, sending the request again may create a second payment. An idempotency key can let the server recognize that the second request represents the same logical operation.
POST /payments
Idempotency-Key: 6f9c2d3a-7a2d-4a10-8d11-0f6e8b3b1234
Content-Type: application/json
The key must be generated once for the logical operation and reused across retries. Generating a new key for each attempt defeats deduplication.
Server-side processing model
A robust implementation usually needs to:
- Scope the key to the authenticated customer or account and the operation.
- Persist the key with a request fingerprint and processing state.
- Ensure concurrent requests with the same key cannot both execute the side effect.
- Return the stored result for a completed duplicate request.
- Reject reuse of the same key with a different payload.
- Define how in-progress requests, timeouts and retention are handled.
A simplified relational schema could be:
CREATE TABLE idempotency_record (
account_id VARCHAR(100) NOT NULL,
idempotency_key VARCHAR(120) NOT NULL,
request_hash VARCHAR(64) NOT NULL,
status VARCHAR(20) NOT NULL,
response_body TEXT,
created_at TIMESTAMP NOT NULL,
PRIMARY KEY (account_id, idempotency_key)
);
This schema is illustrative, not a complete payment ledger. The uniqueness constraint is important because application-level "check then insert" logic alone can race under concurrent requests.
The operation and idempotency record should be coordinated transactionally where possible. If the side effect occurs in an external provider, the design must account for the boundary between the local database and that provider. Use the provider's own idempotency mechanism when available, persist correlation identifiers and define reconciliation for uncertain outcomes.
Idempotency does not mean "ignore every duplicate." It means identify repeated attempts for the same logical operation and return a result consistent with the original operation.
6. Circuit Breakers: Stop Calling a Dependency That Is Failing
A circuit breaker protects a caller from repeatedly invoking a dependency that is likely to fail or is taking too long. It has three common states:
- Closed: Calls are allowed. The breaker records outcomes.
- Open: Calls are rejected quickly, usually without contacting the dependency.
- Half-open: A limited number of test calls are allowed to determine whether recovery has occurred.
A breaker can open after a configured failure rate or slow-call rate is observed over a measurement window. After a wait period, it may transition to half-open. If the test calls succeed, it closes; if they fail, it opens again.
The circuit breaker does not repair the remote service. It limits the damage that repeated calls can cause and gives the dependency an opportunity to recover.
Circuit breaker versus retry
| Pattern | Primary question | Main effect |
|---|---|---|
| Timeout | How long may this call consume? | Bounds waiting |
| Retry | Is another attempt justified? | Repeats selected operations |
| Circuit breaker | Should we call this dependency now? | Fails fast while unhealthy |
| Bulkhead | How much capacity can this dependency consume? | Isolates resources |
| Rate limiter | How quickly may calls be made? | Controls request rate |
These patterns solve different problems. A circuit breaker is not a substitute for a timeout. A retry is not a substitute for a circuit breaker. Combining them requires deliberate ordering and configuration.
Circuit breaker limitations
A breaker can produce false positives if its window is too small or its thresholds are poorly chosen. It can also remain open when a dependency has recovered if the half-open policy is too conservative. A breaker shared across unrelated operations can allow one failing operation to block healthy ones.
Scope breaker instances around meaningful dependency boundaries, such as a particular remote service or operation class. Do not share one global breaker across unrelated services. Resilience4j's guidance discusses instance management and the distinction between circuit breakers, retries, bulkheads and other decorators.
7. Bulkheads and Concurrency Limits
The bulkhead pattern takes its name from ship compartments: damage in one compartment should not flood the entire vessel. In software, a bulkhead limits how much of a process's resources one dependency or workload can consume.
Imagine a service has 100 request-processing threads. If all 100 become blocked waiting for a slow recommendation service, unrelated checkout requests may also stop progressing. A bulkhead can cap concurrent recommendation calls so that the dependency cannot consume every available execution slot.
Common implementations include:
- Semaphore bulkhead: Limits the number of concurrent calls.
- Thread-pool bulkhead: Uses a dedicated bounded thread pool and queue.
- Connection-pool isolation: Separates connection capacity by dependency.
- Queue limits: Rejects or sheds work before unbounded waiting consumes memory.
A bounded queue matters. An unbounded queue can convert overload into rising latency and memory pressure. When the queue is full, the system needs an explicit rejection or degradation policy.
Bulkheads should be combined with timeouts. A concurrency limit without bounded call duration can still have every permit occupied indefinitely.
8. Putting the Patterns Together in Spring Boot
The following example uses Spring Boot with Resilience4j concepts. Exact dependency versions and property names should be aligned with the Spring Boot and Resilience4j versions used by your application. Consult the Resilience4j documentation and the Spring Cloud CircuitBreaker Resilience4j reference before copying configuration into production.
Add the required dependencies
For a Spring Boot 3 application using the Resilience4j Spring Boot starter, the Gradle dependencies commonly include:
dependencies {
implementation "io.github.resilience4j:resilience4j-spring-boot3:${resilience4jVersion}"
implementation "org.springframework.boot:spring-boot-starter-actuator"
implementation "org.springframework.boot:spring-boot-starter-aop"
implementation "io.github.resilience4j:resilience4j-micrometer"
}
Use a version compatible with your Java and Spring Boot baseline. Keep dependency versions managed consistently, preferably through your dependency-management approach or version catalog.
Configure a named dependency policy
A representative YAML configuration is:
resilience4j:
circuitbreaker:
instances:
inventoryService:
slidingWindowType: COUNT_BASED
slidingWindowSize: 20
minimumNumberOfCalls: 10
failureRateThreshold: 50
waitDurationInOpenState: 10s
permittedNumberOfCallsInHalfOpenState: 3
automaticTransitionFromOpenToHalfOpenEnabled: true
retry:
instances:
inventoryService:
maxAttempts: 3
waitDuration: 200ms
enableExponentialBackoff: true
exponentialBackoffMultiplier: 2
bulkhead:
instances:
inventoryService:
maxConcurrentCalls: 20
maxWaitDuration: 0
timelimiter:
instances:
inventoryService:
timeoutDuration: 500ms
These are illustrative starting values, not recommendations for every service. In particular, a library's retry wait configuration may not provide the jitter strategy required by your traffic profile. Verify the supported properties for the exact library version and configure a custom interval function or retry policy when necessary.
Also note that annotation-based composition and decorator order affect behavior. A circuit breaker around a retry can record one final outcome, while a retry around a circuit breaker may observe individual breaker rejections and behave differently. Do not assume the order is irrelevant. Test the exact composition.
Annotate a dependency call
@Service
public class InventoryGateway {
private final InventoryClient client;
public InventoryGateway(InventoryClient client) {
this.client = client;
}
@CircuitBreaker(name = "inventoryService")
@Retry(name = "inventoryService")
@Bulkhead(name = "inventoryService")
public InventoryResponse getAvailability(String sku) {
return client.getAvailability(sku);
}
}
This snippet demonstrates the integration points, not a complete production policy. Before using it:
- Configure connection and response timeouts in the underlying HTTP client.
- Decide which exceptions and response codes are retryable.
- Ensure the method is safe to repeat.
- Verify annotation support and aspect ordering for your versions.
- Check whether the bulkhead type is appropriate for the execution model.
- Define a meaningful fallback or propagate a controlled error.
- Test what happens when the breaker is open and the bulkhead is full.
A fallback must not fabricate business success. Returning "available" when inventory cannot be checked is not resilience; it is data corruption waiting for a customer.
Make the HTTP client timeout explicit
The precise configuration depends on whether the application uses RestClient, WebClient, RestTemplate, OpenFeign or another client. For a synchronous client, configure both connection establishment and response waiting limits in the underlying request factory. For a reactive client, configure connection, response and overall timeout behavior appropriate to the Reactor Netty version.
Do not assume that a Resilience4j TimeLimiter automatically cancels every underlying blocking operation. Cancellation semantics depend on the execution model and client. A caller timing out while the remote operation continues can still consume remote resources.
9. Retry Policy Design: A Worked Decision
Consider an order service calling an inventory service to read availability. The operation is a read, and the inventory API contract states that the response is safe to repeat.
A reasonable policy might be:
- Attempt once immediately.
- Retry only connection failures and selected transient server errors.
- Do not retry validation, authentication or authorization failures.
- Allow at most two retries after the initial attempt.
- Use capped exponential backoff with jitter.
- Stop when the overall deadline is exhausted.
- Do not retry if the circuit breaker is open.
- Record every attempt and the final outcome.
For a payment-creation operation, the policy changes. It should only be retried if the payment API provides a reliable idempotency mechanism or the client can otherwise establish that the original operation was not applied. A timeout alone is insufficient evidence.
Example retry decision pseudocode
RetryDecision decide(
Throwable failure,
int attemptsUsed,
Instant deadline) {
if (Instant.now().isAfter(deadline)) {
return RetryDecision.stop("deadline_exceeded");
}
if (attemptsUsed >= 3) {
return RetryDecision.stop("attempt_limit_reached");
}
if (failure instanceof ValidationException
|| failure instanceof AuthenticationException
|| failure instanceof AuthorizationException) {
return RetryDecision.stop("permanent_failure");
}
if (failure instanceof ConnectException
|| failure instanceof SocketTimeoutException) {
return RetryDecision.retryWithBackoff();
}
return RetryDecision.stop("failure_not_classified_as_transient");
}
This is pseudocode, not a drop-in Java implementation. Real systems should avoid broad exception matching where a client library exposes more precise exception types. They should also use a monotonic time source for measuring elapsed time and ensure retry delays fit within the remaining deadline.
The decision should be based on operation semantics as well as transport errors. A SocketTimeoutException during a read is different from the same exception after a non-idempotent write may already have committed.
10. The Failure Scenario: How a Retry Storm Becomes a Cascading Outage
Assume a service normally receives 800 requests per second. It calls a downstream pricing service. A deployment introduces a slow database query, causing pricing latency to rise from 80 ms to 1.5 seconds.
The caller has a 500 ms timeout and retries twice immediately.
A simplified sequence follows:
- Pricing becomes slow and begins accumulating in-flight requests.
- The caller times out after 500 ms, even though pricing may still be processing the original request.
- The caller immediately sends another attempt.
- More requests arrive while earlier attempts are still consuming resources.
- Pricing uses more threads and database connections, increasing queueing.
- More calls exceed the timeout.
- Retries add traffic to an already overloaded service.
- Other services begin timing out while waiting for pricing.
- The failure spreads beyond the original dependency.
The critical feedback loop is:
higher latency → timeouts → retries → more load → higher latency
This is a positive feedback loop. The retries are not merely failing to help; they are contributing to the failure.
Google's SRE book describes cascading failures as failures that grow through positive feedback, often involving overload and reduced available capacity. It recommends randomized exponential backoff, retry limits and retry budgets.
Why recovery can be harder than failure
When overloaded instances restart, incoming traffic may immediately overwhelm them again. Load balancers can shift traffic toward the remaining instances, which then become overloaded too. A service may need a substantial reduction in incoming work to recover.
A retry storm can also hide the original symptom. Teams may see elevated error rates and assume the downstream service is simply unhealthy, while retry traffic is a major cause of its continued overload.
A safer response
- Stop retrying permanent failures.
- Add backoff and jitter.
- Limit attempts and total retry time.
- Apply a retry budget.
- Use concurrency limits and load shedding.
- Open the circuit when the dependency is unhealthy.
- Preserve capacity for critical traffic.
- Reduce or disable nonessential work during an incident.
A retry budget can be defined per process, tenant or service. For example, a system might permit retries only up to a small fraction of original requests over a time window. The correct fraction depends on workload and capacity; it should be measured and tested, not copied blindly from another system.
11. Common Mistakes and Their Consequences
| Mistake | Why it is dangerous | Better practice |
|---|---|---|
| Retrying every exception | Permanent failures are repeated | Classify retryable failures explicitly |
| Retrying immediately | Clients synchronize and create bursts | Use exponential backoff with jitter |
| Unlimited attempts | Work and latency become unbounded | Set attempt and deadline limits |
| Retrying at every layer | Attempts multiply through the call graph | Choose retry ownership and calculate amplification |
| Retrying non-idempotent writes blindly | Duplicate side effects may occur | Use idempotency keys or reconcile outcome |
| No connection timeout | Calls can wait too long before connecting | Configure the relevant client timeouts |
| Only per-attempt timeouts | Total operation can exceed caller deadline | Propagate an end-to-end deadline |
| Circuit breaker without timeout | Slow calls can hold resources before the breaker reacts | Combine bounded calls with breaker policy |
| One breaker for unrelated services | One dependency can block healthy dependencies | Scope breaker instances by dependency |
| Fallback returns fake success | The system hides data loss or inconsistency | Return explicit degraded or unavailable behavior |
| No retry metrics | Amplification is hard to diagnose | Track attempts, retries, latency and exhaustion |
| No overload policy | Queues and resources can grow without bound | Bound queues and shed work intentionally |
One especially subtle mistake is treating every timeout as a transient failure. A timeout can be caused by a permanently slow query, a saturated thread pool, a deadlock or a downstream dependency that cannot recover without intervention. Retrying those failures can increase pressure without changing the outcome.
12. Observability: Measure Attempts, Not Just Requests
A service dashboard that reports only successful requests and failed requests can conceal retry amplification. If one logical request causes four network attempts, request volume at the dependency is higher than the user-facing request count suggests.
At minimum, instrument:
- Logical request count.
- Attempt count per logical request.
- Retry count and retry reason.
- Retry exhaustion count.
- Circuit breaker state transitions.
- Circuit breaker rejected calls.
- Bulkhead rejections and queue wait time.
- Connection-pool saturation.
- In-flight requests.
- Downstream latency percentiles.
- Timeout and cancellation counts.
- HTTP status and exception categories.
Useful derived signals include:
[
\text{Retry ratio} =
\frac{\text{retry attempts}}{\text{initial attempts}}
]
[
\text{Attempt amplification} =
\frac{\text{all downstream attempts}}{\text{logical operations}}
]
Interpret these metrics with care. A retry ratio can rise during a brief network disturbance without causing an outage. The dangerous pattern is a sustained increase in retries alongside rising latency, growing in-flight work, resource saturation and falling useful throughput.
Use distributed tracing to connect attempts to their parent logical request. Record attempt number and retry reason as span attributes, while avoiding sensitive data and high-cardinality metric labels. Do not put order IDs, user IDs or raw exception messages into metric labels.
Resilience4j can integrate with Micrometer metrics when the relevant dependencies are present. See the Spring Cloud CircuitBreaker Resilience4j reference.
13. Testing Resilience: Prove the Failure Behavior
A resilience policy should be tested under failure, not only during a healthy integration test.
Build tests for at least these scenarios:
- The dependency succeeds on the first attempt.
- The dependency fails transiently and succeeds on a later attempt.
- The dependency fails permanently and is not retried.
- The total deadline expires before another attempt.
- The circuit opens after the configured failure condition.
- Calls are rejected while the circuit is open.
- A half-open probe succeeds and closes the circuit.
- The bulkhead rejects excess concurrent calls.
- A duplicate idempotency key does not repeat the side effect.
- A timeout after a remote commit can be reconciled safely.
Test the retry count
A simplified unit test can verify that a transient failure causes a bounded number of calls:
@Test
void retriesTransientFailureOnlyWithinConfiguredLimit() {
AtomicInteger calls = new AtomicInteger();
Supplier<String> operation = () -> {
if (calls.incrementAndGet() < 3) {
throw new TransientDependencyException();
}
return "available";
};
String result = retryExecutor.execute(operation);
assertEquals("available", result);
assertEquals(3, calls.get());
}
retryExecutor is an application abstraction representing the configured retry policy. The test should use the actual retry implementation in the project, with deterministic backoff or a controllable clock where possible. Avoid making unit tests sleep for real seconds.
Test the dangerous ambiguous outcome
For a payment-like operation, simulate this sequence:
- The server commits the operation.
- The response is lost.
- The client retries with the same idempotency key.
- The server returns the original result.
- The side effect occurs once.
This test checks a system property, not just a retry library setting. It is often more important than proving that a client can retry a connection exception.
Use integration tests with a controllable mock server, fault injection or a test environment to simulate delays, connection resets, slow responses and partial failures. Load tests should also evaluate recovery behavior, not merely steady-state throughput.
14. A Practical Design Checklist
Before enabling retries for a dependency, answer these questions:
- What is the caller's end-to-end deadline?
- Are connection, response and pool-acquisition timeouts configured?
- Does the operation have side effects?
- Is the operation idempotent by contract or protected by an idempotency key?
- Which exact failures are retryable?
- Are permanent errors excluded?
- Is there a strict maximum attempt count?
- Is backoff bounded and randomized?
- Does the retry delay fit within the remaining deadline?
- Are retries limited to one deliberate layer?
- Is there a retry budget or overload policy?
- Does a circuit breaker protect the dependency?
- Are concurrency and queue sizes bounded?
- Is fallback behavior semantically correct?
- Are attempts, retry reasons and breaker states observable?
- Have partial success and duplicate-operation scenarios been tested?
If these questions cannot be answered, adding retries is premature. First establish the operation's semantics and the system's time and resource budgets.
15. Further Reading and Standards
The following sources provide the technical foundations and implementation guidance behind this article:
- AWS Builders' Library: Timeouts, retries, and backoff with jitter — practical guidance on timeout selection, retry behavior, idempotency and jitter.
- Google SRE Book: Addressing Cascading Failures — overload, retry amplification, randomized backoff and retry budgets.
- RFC 9110: HTTP Semantics, Section 9.2.2 — normative definition of idempotent HTTP methods and implications for automatic retries.
- Resilience4j Documentation — circuit breaker, retry, rate limiter, bulkhead and time limiter components.
- Spring Cloud CircuitBreaker: Resilience4j — Spring integration, bulkhead configuration and metrics.
- Spring Boot Reference Documentation — framework-level configuration and application observability.
Conclusion: Retry Deliberately, Recover Gracefully
Retries are useful when failures are transient, the operation is safe to repeat and the caller still has time to benefit from another attempt. They are dangerous when they are unlimited, synchronized, layered or applied to operations whose outcomes are uncertain.
A robust design combines several controls:
- Timeouts and deadlines bound how long work may consume resources.
- Retry classification, backoff and jitter make another attempt selective and less disruptive.
- Idempotency protects operations against duplicate effects.
- Circuit breakers, bulkheads and retry budgets limit the impact of unhealthy dependencies.
- Observability and failure testing show whether the policy works under real conditions.
The objective is not to make every request succeed at any cost. It is to preserve useful system behavior when dependencies become slow or unavailable, protect the rest of the application, and fail in a controlled and understandable way. In distributed systems, knowing when not to retry is just as important as knowing when to try again.




