System Design Part 6 Reliability

Timeouts, Retries, Backoff, and Jitter: How Retries Save a System, and How They Bring It Down

Bill.Lin 15 min read

System Design series Part 6-2 | Previous: Redundancy, Failover, and DR | Next: Circuit Breakers and Bulkheads | Series map

Read first: Part 5-4 Idempotency and Idempotency Keys.

Scenario and problem

Before it completes a sign-up, the sign-up service calls the payment service to confirm the payment status. One day the payment service’s database slows down, and its response time goes from 50 milliseconds to 30 seconds.

The sign-up service’s HTTP client has no timeout. Every sign-up request gets stuck waiting for payments to respond, Tomcat’s threads are taken one by one, and the connection pool is drained too. A few minutes later, even the talk lookup API, which does not need payments at all, stops responding, because there are no threads left.

An engineer adds a timeout and retries: a 5-second timeout and 3 retries on failure. The next time the payment service slows down, the sign-up service sends it 4 times its usual number of requests. The payment service was only slow before; now the retry traffic crushes it completely.

After payments slows down1 / 4
After payments slows downUsersRegistrationPaymentsUsersRegistrationPaymentssign upcheck payment50 msRegistrationPaymentsno timeout set30 s to respondThreads taken one by oneUsersRegistrationlook up talksNo threads leftNo responseRegistrationPayments5 s timeout, 3 retries4x the requestsCrushed by retries
  1. NormallyBefore it completes a sign-up, the sign-up service calls the payment service to confirm the payment status. Normally the answer comes back in 50 milliseconds.
  2. Payments slows to 30 secondsThe payment service's database slows down, and its response time goes from 50 milliseconds to 30 seconds. The sign-up service's HTTP client has no timeout, so every sign-up request gets stuck waiting, threads are taken one by one, and the connection pool is drained too.
  3. APIs that skip payments go down tooA few minutes later, even looking up talks, which does not need payments at all, stops responding, because there are no threads left.
  4. Add a timeout and retriesAn engineer adds a 5-second timeout and 3 retries on failure. The next time payments slows down, it receives 4 times its usual number of requests, and a service that was only slow is crushed completely by the retry traffic.

Timeouts and retries are both necessary, but set up wrong, they make a failure bigger instead of smaller.

The simplest approach and its limits

  • No timeout: many HTTP clients never time out by default, or time out only after several minutes. One slow downstream can hold every resource
  • Retry immediately on failure: the downstream is failing precisely because its load is too high, and retrying right away only pushes the load higher
  • Every layer retries 3 times: the user’s app, the API gateway, and the sign-up service each retry 3 times, so one request can turn into as many as 4 × 4 × 4 = 64 attempts at the bottom layer (at each layer, 1 original request plus 3 retries)

Core mechanism

Timeouts: the cost of waiting

Waiting is not free. Every request the sign-up service has waiting holds:

  • A thread (or a virtual thread and its memory)
  • A connection to the downstream
  • Possibly a database connection too, if the call happens inside a transaction
  • The patience of the user on the other end

Set timeouts separately:

Timeout Meaning Typical value
Connect timeout Time to establish the TCP (and TLS) connection Within one data center this usually takes a few milliseconds, so set a few hundred milliseconds; failing to connect means the other side is gone, and there is no need to wait long
Read timeout Time to wait for response data after sending the request Set from the downstream’s latency distribution
Overall deadline The most this operation (including all retries) may take Set from the caller’s deadline

Set the read timeout from the downstream’s latency distribution. The payment service’s p99 is 300 milliseconds and its p99.9 is 800 milliseconds, so set the read timeout to 1 second: under normal conditions it almost never misfires, and when the downstream really has a problem, you wait at most 1 second. Set it shorter than p99, and normal slow requests are treated as failures too, which then trigger retries and add load instead.

Timeout budgets: shorter at every layer down

A user’s request has a total deadline, and each layer down has less time left:

flowchart LR
    U[App<br/>waits 3 s] --> G[API gateway<br/>2.8 s timeout]
    G --> R[Sign-up service<br/>2.5 s left]
    R -->|1 s per attempt<br/>at most 2 tries| P[Payment service]

If the sign-up service’s timeout to payments is 5 seconds with 3 retries, it might wait 20 seconds or more, but the gateway gives up at 2.8 seconds, and the user has long since seen an error screen. All the waiting and retrying the sign-up service does after that is wasted, and it keeps holding resources the whole time.

An inner layer’s timeouts plus retries must add up to no more than the time the outer layer has left. gRPC passes the deadline down automatically (REST, gRPC, and GraphQL); HTTP has no standard way to do this, so you compute the remaining time yourself and pass it down in a header when needed.

Which errors can be retried

A retry assumes two things: “trying again might succeed”, and “trying again does no harm”:

Error Retry? Why
Connection refused, connect timeout Yes The request never reached the other side, so retrying is safe
Read timeout Only for idempotent operations The request may already have been processed; only the response did not come back
502, 503, 504 Yes, with backoff Usually temporary; a 503 may carry Retry-After
429 Too Many Requests Yes, waiting as Retry-After says The other side is explicitly asking you to slow down
500 Usually not Mostly a bug; a retry gets the same result
400, 401, 403, 404, 409, 422 No The request itself is the problem; retrying will not change the result

To retry a non-idempotent operation (creating a payment), you must send the same Idempotency Key; otherwise a retry after a read timeout can charge the user twice.

Exponential backoff

Wait between retries, and wait longer each time, to give the downstream time to recover:

text
wait before retry n = min(cap, base × 2^(n-1))
base 100 ms, cap 1 s: 100 ms, 200 ms, 400 ms, 800 ms, 1 s, 1 s...

Jitter: spreading retries out

Say the payment service restarts and 10,000 requests fail at the same instant. If every client retries exactly 100 milliseconds after the failure, the payment service, just back up, receives 10,000 requests in the same millisecond and falls over again; 200 milliseconds later comes another wave. Exponential backoff only spaces the waves further apart. It does not remove the peaks.

Jitter adds randomness to the wait. In a 2015 article, Marc Brooker of AWS compared several approaches. Full jitter is the simplest of them, and also among the most effective:

text
wait = random(0, min(cap, base × 2^(n-1)))

The 10,000 retries spread evenly across 0 to 100 milliseconds, about 100 per millisecond, instead of 10,000 crammed into the same millisecond.

@Retryable in Spring Framework 7 also has a jitter parameter, but its semantics differ: it moves the computed delay up and down, and never goes below the base delay. With delay = 100, jitter = 100, the first retry happens between 100 and 200 milliseconds. As long as jitter is the same order of magnitude as delay, it is enough to break up synchronized retries; a jitter that is too small (say 1% of the delay) does little.

Retry budgets

Backoff and jitter solve “retrying at the same time”, but not “retries add to the total load”. When the downstream is already overloaded, every request still turns into 3 to 4 attempts, even with the retries spread out.

Google’s SRE book proposes a retry budget: each client tracks the share of retries in its total requests and stops retrying once that share goes above 10%. In normal times, the occasional failure can always be retried; when the downstream fails at scale, retries add at most 10% to the load instead of tripling it.

Pair it with the rule of “retry at only one layer”: the gateway and the app do not retry, or retry only connection errors, and the layer that best understands the business semantics (the sign-up service) decides whether to retry.

Hedged requests

A related technique is the hedged request: after sending a request, if no response has arrived by the p95 time, send the same request to another server and use whichever result comes back first. It cuts tail latency rather than handling errors. The cost is about 5% more load, and it works only for idempotent reads.

Comparing options

Strategy What it solves What it does not solve
Timeouts only A slow downstream cannot hold resources Temporary failures turn straight into errors users see
Timeout + immediate retry Occasional failures Adds load when the downstream is overloaded
Exponential backoff Gives the downstream time to recover Many clients retrying in sync
Exponential backoff + jitter Breaks up retry peaks Total load still multiplies
Plus a retry budget Caps the extra load retries bring When the downstream stays down, every request still waits for the timeout before it fails (the circuit breaker in the next post)
Queues and async retries Work that does not need an immediate result can wait longer before retrying (Message Queues) Does not fit when users need an immediate response

In Java

1. Set timeouts on every HTTP client

yaml
spring:
  http:
    clients:
      connect-timeout: 300ms
      read-timeout: 1s

In Spring Boot 4, the spring.http.clients properties apply to every auto-configured HTTP client (clients built from RestClient.Builder, and HTTP service clients). When different downstreams need different timeouts, set them per group with spring.http.serviceclient.<group>.

2. The simple case: @Retryable

java
@Configuration
@EnableResilientMethods
public class ResilienceConfig {
}

@Service
public class SeatQueryClient {

    private final RestClient restClient;

    public SeatQueryClient(RestClient.Builder builder) {
        this.restClient = builder.baseUrl("https://inventory.internal.example.com").build();
    }

    // Retry only connection-level errors and 503; at most 2 retries, waiting 100~200 ms, then 200~400 ms
    @Retryable(includes = {ResourceAccessException.class, HttpServerErrorException.ServiceUnavailable.class},
            maxRetries = 2, delay = 100, jitter = 100, multiplier = 2, maxDelay = 1000)
    public SeatSnapshot fetch(long lectureId) {
        return restClient.get()
                .uri("/v1/lectures/{id}/seats", lectureId)
                .retrieve()
                .body(SeatSnapshot.class);
    }
}
  • By default @Retryable retries on any exception, 3 times, 1 second apart. Always limit the retryable exceptions with includes, or 404 and 400 get retried too
  • maxRetries is the number of retries, not counting the first call, so the method runs at most 3 times
  • Like @Transactional, it works through a proxy, so calls from inside the same class are not intercepted

3. The full case: deadlines, Retry-After, and a retry budget

Looking up payment status needs finer control: respect the time the caller has left, honor Retry-After, and stay within a retry budget. To make each mechanism visible, the retry loop is written out by hand here:

java
/** Caps retries at a fixed share of requests: every request deposits a little credit, every retry takes out one whole unit. */
public final class RetryBudget {

    private static final long TOKEN = 1_000;

    private final long depositPerRequest;
    private final long maxBalance;
    private final AtomicLong balance;

    public RetryBudget(double retryRatio, int maxBurst) {
        this.depositPerRequest = Math.round(retryRatio * TOKEN);
        this.maxBalance = maxBurst * TOKEN;
        this.balance = new AtomicLong(maxBalance);
    }

    public void recordRequest() {
        balance.accumulateAndGet(depositPerRequest, (current, deposit) -> Math.min(maxBalance, current + deposit));
    }

    public boolean tryAcquireRetry() {
        long current;
        do {
            current = balance.get();
            if (current < TOKEN) {
                return false;
            }
        } while (!balance.compareAndSet(current, current - TOKEN));
        return true;
    }
}
java
@Component
public class PaymentStatusClient {

    private static final long BASE_MILLIS = 100;
    private static final long CAP_MILLIS = 1_000;
    private static final long MAX_RETRY_AFTER_MILLIS = 5_000;
    private static final int MAX_ATTEMPTS = 3;

    private final RestClient restClient;
    private final RetryBudget budget = new RetryBudget(0.1, 50);      // retries take at most 10%

    public PaymentStatusClient(RestClient.Builder builder) {
        this.restClient = builder.baseUrl("https://payments.internal.example.com").build();
    }

    /** Looking up payment status is an idempotent read. deadline is the caller's remaining deadline. */
    public PaymentStatus fetch(String paymentId, Instant deadline) {
        budget.recordRequest();
        for (int attempt = 1; ; attempt++) {
            try {
                return restClient.get()
                        .uri("/v1/payments/{id}", paymentId)
                        .retrieve()
                        .body(PaymentStatus.class);
            } catch (RestClientException e) {
                long waitMillis = Math.max(fullJitter(attempt), retryAfterMillis(e));
                boolean giveUp = !isTransient(e)
                        || attempt >= MAX_ATTEMPTS
                        || Instant.now().plusMillis(waitMillis).isAfter(deadline)
                        || !budget.tryAcquireRetry();
                if (giveUp) {
                    throw e;
                }
                sleep(waitMillis);
            }
        }
    }

    private static long fullJitter(int attempt) {
        long ceiling = Math.min(CAP_MILLIS, BASE_MILLIS << (attempt - 1));
        return ThreadLocalRandom.current().nextLong(ceiling + 1);
    }

    private static boolean isTransient(RestClientException e) {
        if (e instanceof ResourceAccessException) {                 // connection failure, timeout
            return true;
        }
        if (e instanceof RestClientResponseException response) {
            int status = response.getStatusCode().value();
            return status == 429 || status == 502 || status == 503 || status == 504;
        }
        return false;
    }

    /** Accepts only the seconds format, with an upper bound: the downstream must not decide how long we wait. */
    private static long retryAfterMillis(RestClientException e) {
        if (e instanceof RestClientResponseException response && response.getResponseHeaders() != null) {
            String value = response.getResponseHeaders().getFirst(HttpHeaders.RETRY_AFTER);
            if (value != null && value.matches("\\d{1,6}")) {
                return Math.min(Long.parseLong(value) * 1_000, MAX_RETRY_AFTER_MILLIS);
            }
        }
        return 0;
    }

    private static void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new IllegalStateException("interrupted while waiting to retry", e);
        }
    }
}
  • There are four conditions for giving up: the error is not temporary, the attempts are used up, waiting would go past the deadline, or the retry budget has run out. A retry past the deadline is pointless, because the caller will no longer use the result
  • Take the larger of Retry-After and full jitter, with an upper bound
  • The budget starts full, so retries work even on a cold start. For a low-traffic service, the budget may take a long time to build up one unit; if needed, add a floor such as “always allow at least a few retries per second”
  • Each attempt’s read timeout is still the 1 second from the configuration, so the last attempt may run slightly past the deadline. For precise control, you need to be able to set the timeout per request

The code above is written from the official Spring Framework 7 and Spring Boot 4.1 documentation; it has not been compiled or run.

Pitfalls and gotchas

  • HTTP clients without a timeout: the most common, and the most fatal. Check the clients for every outbound call, the database, Redis, and message queues
  • An inner timeout longer than the outer one: the outer layer has already given up while the inner layer is still waiting and retrying
  • Retrying at every layer: the retry counts multiply. Retry at only one layer
  • @Retryable without limiting exceptions: by default it retries on every exception, including 400, 404, and bugs
  • Retrying external calls inside a transaction: through the retries and the backoff waits, the database transaction and its connection stay held. Move external calls out of the transaction
  • Retrying non-idempotent operations: retrying payment creation after a read timeout charges the user twice
  • Retries hiding the problem: the retries succeed and monitoring looks fine, but the downstream is already failing heavily. Retry counts need metrics and alerts (Observability in Part 6)
  • Timeouts that are too short: shorter than the downstream’s p99, so normal slow requests are treated as failures and retried, and the downstream’s load goes up instead
  • Jitter set too small: with delay = 1000, jitter = 10, all clients still retry at almost the same time

Security

  • Timeouts are also a defense: if the server has no timeout for reading requests, an attacker can open a large number of connections, each sending headers extremely slowly (slowloris), and fill up every connection. Set server-side connection and read timeouts (such as Spring Boot’s server.tomcat.connection-timeout), and limit request size
  • Retry amplification can be exploited: an attacker finds a request that makes the downstream time out (say an especially expensive query), and every request they send creates several retries inside the system. A retry budget keeps the amplification factor within a manageable range
  • Do not let the downstream decide how long you wait: Retry-After: 86400 stalls the retry loop for a whole day, and Retry-After: 0 makes the client retry nonstop. A compromised or misconfigured downstream can return either value. When parsing it, accept only the expected format, and enforce lower and upper bounds
  • User-supplied URLs: for URLs that users fill in, such as webhooks, an attacker can point at a server that responds extremely slowly on purpose and tie up your threads. These calls need a shorter timeout, a response size limit, and SSRF checks (Part 8)
  • Logging retries: logging the full request on a retry is handy for debugging, but it can write the Authorization header and personal data into the log. Log only the request ID, the destination, and the error type
  • Credentials expiring during retries: a long run of retries may hit an expired access token. After a 401, get a new token instead of retrying with the same one over and over

When to use it, and when not to

  • Always: set a timeout on every call that crosses the network, with inner layers shorter than outer ones
  • Retry: temporary errors and idempotent operations (or ones with an Idempotency Key), with exponential backoff, jitter, and a retry budget, at only one layer
  • Do not retry: 4xx, bugs, and non-idempotent operations without an Idempotency Key; requests the user has already stopped waiting for; and calls to a downstream that is clearly down already (leave that to the circuit breaker)

Further reading: timeouts, retries, and fallbacks when an LLM agent calls a model service, in the Agent series Part 5-1 Exception Handling and Recovery.

References

Comments