Skip to lesson

Timeouts and retries with backoff

ShopLite's checkout calls an SMS provider. One day it answers in 3 minutes instead of 3 seconds, and soon every page of ShopLite hangs. How do you protect the app from a slow or failing service?

Your turn: protect checkout from a slow SMS provider

ShopLite's checkout sends an order SMS through an outside provider, and today that provider is slow. Thousands of customers are checking out.

Before you read on, think about these questions and write your plan in a few lines.

  • How long should checkout wait for the provider before it gives up?
  • Which failures are worth trying again, and which will never work however often you try?
  • How long should the app wait between tries, when should it stop, and what could go wrong if a thousand phones retry together?

Every remote call needs a timeout

A timeout is the longest you wait for a remote call before giving up. Without one, a slow service can hold your threads for minutes and stop the whole app.

Without a timeout, a call to a slow service can wait for minutes while the customer's thread is stuck. Java's HttpClient sets two limits, one for connecting and one for the answer.

Java
HttpClient client = HttpClient.newBuilder()        .connectTimeout(Duration.ofSeconds(2))          // opening the connection        .build();
HttpRequest request = HttpRequest.newBuilder(URI.create("https://sms.example.com/send"))        .timeout(Duration.ofSeconds(3))                 // waiting for the response        .POST(HttpRequest.BodyPublishers.ofString(body))        .build();// send(...) throws HttpConnectTimeoutException or HttpTimeoutException when a limit is hit

Example 1 · Giving up on a slow call after 500 ms

TimeoutDemo.javaJava
import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.concurrent.TimeUnit;import java.util.concurrent.TimeoutException;
public class TimeoutDemo {    // Pretend remote call: the SMS provider is having a bad day and takes 3 seconds    static String slowSmsProvider() throws InterruptedException {        Thread.sleep(3000);        return "SMS sent";    }
    public static void main(String[] args) throws Exception {        ExecutorService pool = Executors.newSingleThreadExecutor();        Future<String> call = pool.submit(TimeoutDemo::slowSmsProvider);
        try {            System.out.println(call.get(500, TimeUnit.MILLISECONDS));   // wait at most 500 ms        } catch (TimeoutException e) {            call.cancel(true);                                         // stop waiting, free the thread            System.out.println("gave up after 500 ms: SMS provider too slow");            System.out.println("checkout thread is free to answer the customer");        } finally {            pool.shutdownNow();        }    }}
Output
gave up after 500 ms: SMS provider too slow
checkout thread is free to answer the customer

What this code does

  • The pretend SMS provider takes 3 seconds. Future.get(500, TimeUnit.MILLISECONDS) waits at most half a second and then throws TimeoutException.
  • cancel(true) interrupts the stuck task and shutdownNow frees the thread, so the request thread can answer the customer instead of hanging.

When enough threads are stuck, the whole app stops answering, even pages that never call that service.

There are two timeouts. The connect timeout limits how long you wait to open the connection (the server is down or unreachable). The read timeout, or request timeout, limits how long you wait for the answer once connected (the server is up but slow).

Predict the output

Which timeout fires

Predict what the client does with these two limits.

Round 1 of 2

The provider's machine is switched off, so no connection is ever opened. What happens?

HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(2))
.build();
HttpRequest request = HttpRequest.newBuilder(URI.create(url))
.timeout(Duration.ofSeconds(3))
.build();

Which errors to retry

A retry is trying a call again after a temporary failure. It helps only when the failure can go away on its own and repeating the call is safe.

Some failures disappear if you try again and some never will. The example sorts common outcomes into retry and do not retry.

Example 2 · Retry or not, by outcome

RetryDecision.javaJava
public class RetryDecision {    // Is it worth trying the same request again later?    static String decide(String outcome) {        return switch (outcome) {            case "timeout", "connection refused", "502", "503", "504" -> "retry (temporary problem)";            case "429" -> "retry after the Retry-After delay";            case "400", "401", "403", "404", "409", "422" -> "do not retry (the request itself is wrong)";            default -> "do not retry (unknown: log it)";        };    }
    public static void main(String[] args) {        String[] outcomes = {"timeout", "503", "429", "400", "404", "409"};        for (String o : outcomes) {            System.out.printf("%-8s -> %s%n", o, decide(o));        }    }}
Output
timeout  -> retry (temporary problem)
503      -> retry (temporary problem)
429      -> retry after the Retry-After delay
400      -> do not retry (the request itself is wrong)
404      -> do not retry (the request itself is wrong)
409      -> do not retry (the request itself is wrong)

What this code does

  • Temporary problems (timeouts, 502, 503, 504) are worth another try; 429 is too, but only after the server's Retry-After delay.
  • Client errors such as 400, 404 and 409 will fail the same way every time, so retrying only adds load.

Retry only failures that may go away on their own: timeouts, refused connections, 502, 503 and 504 (a server or gateway is overloaded or restarting), and 429 (too many requests, after the time in its Retry-After header). Do not retry 400, 401, 403, 404, 409 or 422: the request itself is wrong, and sending it again gives the same answer.

Also check the method. GET, PUT and DELETE are safe to repeat. A POST that creates or charges something may be retried only with an idempotency key, from the previous lesson.

Find the bug

Find the retry bug

Click the line that retries when it should not.

This code retries too much. Which line is the bug?

Round 1 of 3

Exponential backoff with jitter and a maximum

Exponential backoff means waiting longer after each failed try: base x 2^n, for example 100, 200, 400 and 800 ms, up to a cap. A maximum number of attempts makes the client give up in the end.

Retrying at once usually hits the same overloaded server again. The example prints the waits for 6 retries, with and without jitter.

Example 3 · Exponential delays, capped, with full jitter

BackoffSchedule.javaJava
import java.util.Random;
public class BackoffSchedule {    static final long BASE_MS = 100;    static final long CAP_MS = 2000;
    // Exponential: 100, 200, 400, 800 ... but never more than the cap    static long exponential(int retry) {        return Math.min(CAP_MS, BASE_MS * (1L << retry));    }
    // "Full jitter": a random wait between 0 and the exponential value    static long withJitter(int retry, Random random) {        return (long) (random.nextDouble() * exponential(retry));    }
    public static void main(String[] args) {        Random clientA = new Random(11);      // fixed seeds so the output repeats;        Random clientB = new Random(97);        System.out.println("retry  exponential  client A  client B");        for (int retry = 0; retry < 6; retry++) {            System.out.printf("%5d  %8d ms  %5d ms  %5d ms%n",                    retry + 1, exponential(retry), withJitter(retry, clientA), withJitter(retry, clientB));        }    }}
Output
retry  exponential  client A  client B
    1       100 ms     73 ms     72 ms
    2       200 ms     85 ms    137 ms
    3       400 ms    251 ms    382 ms
    4       800 ms     21 ms    345 ms
    5      1600 ms    302 ms    812 ms
    6      2000 ms     87 ms   1208 ms

What this code does

  • exponential doubles from 100 ms and stops at the 2,000 ms cap. withJitter picks a random wait between 0 and that value.
  • Two clients with different random numbers wait different times, so their retries do not arrive together. Seeds are fixed here only to make the output repeatable.

Exponential backoff doubles the wait after each failure, up to a cap such as 2 seconds. A maximum attempt count (often 3 to 5) makes sure the client eventually gives up and reports an error.

Jitter adds randomness to each wait. Without it, a thousand phones that failed at the same moment all retry at the same moment again. With "full jitter" each client waits a random time between 0 and the exponential value, which spreads the retries out.

Predict the output

Work out the wait

Base 100 ms, cap 2,000 ms. Predict the wait before each retry.

Round 1 of 2

What is the exponential wait before the 4th retry?

int attempt = 4;
long delay = Math.min(2000, 100L * (1L << (attempt - 1)));
System.out.println(delay);

Simulation: a retry helper against a flaky service

A retry helper wraps any call: try it, and on a temporary failure wait with backoff and jitter and try again, up to the limit. The service below fails 60% of the time.

Example 4 · A generic retry helper with backoff, jitter and a limit

RetryHelperDemo.javaJava
import java.util.Random;import java.util.function.Supplier;
class TemporaryFailure extends RuntimeException {    TemporaryFailure(String message) {        super(message);    }}
class Retry {    private final int maxAttempts;    private final long baseMs;    private final long capMs;    private final Random random;    long totalWaitMs = 0;
    Retry(int maxAttempts, long baseMs, long capMs, Random random) {        this.maxAttempts = maxAttempts;        this.baseMs = baseMs;        this.capMs = capMs;        this.random = random;    }
    <T> T call(Supplier<T> action) {        for (int attempt = 1; ; attempt++) {            try {                return action.get();            } catch (TemporaryFailure e) {                if (attempt == maxAttempts) {                    System.out.println("  attempt " + attempt + ": " + e.getMessage() + ", giving up");                    throw e;                }                long exp = Math.min(capMs, baseMs * (1L << (attempt - 1)));                long wait = (long) (random.nextDouble() * exp);       // full jitter                totalWaitMs += wait;                                  // a real client would Thread.sleep(wait)                System.out.println("  attempt " + attempt + ": " + e.getMessage() + ", waiting " + wait + " ms");            }        }    }}
public class RetryHelperDemo {    public static void main(String[] args) {        Random flaky = new Random(108);               // the stock service fails 60% of the time        Supplier<String> stockService = () -> {            if (flaky.nextInt(100) < 60) {                throw new TemporaryFailure("503 Service Unavailable");            }            return "200 stock=40";        };
        Retry retry = new Retry(5, 100, 2000, new Random(7));        for (int request = 1; request <= 3; request++) {            System.out.println("request " + request + ":");            try {                System.out.println("  result: " + retry.call(stockService));            } catch (TemporaryFailure e) {                System.out.println("  result: failed, show \"try again\" to the user");            }        }        System.out.println("total time spent waiting: " + retry.totalWaitMs + " ms");    }}
Output
request 1:
  attempt 1: 503 Service Unavailable, waiting 73 ms
  attempt 2: 503 Service Unavailable, waiting 149 ms
  result: 200 stock=40
request 2:
  result: 200 stock=40
request 3:
  attempt 1: 503 Service Unavailable, waiting 34 ms
  attempt 2: 503 Service Unavailable, waiting 179 ms
  attempt 3: 503 Service Unavailable, waiting 283 ms
  attempt 4: 503 Service Unavailable, waiting 281 ms
  attempt 5: 503 Service Unavailable, giving up
  result: failed, show "try again" to the user
total time spent waiting: 999 ms

What this code does

  • Retry.call takes a Supplier<T>, catches only TemporaryFailure and waits a jittered, growing delay between attempts. It records the waits instead of calling Thread.sleep so the demo runs instantly.
  • Request 1 succeeds on the 3rd attempt, request 2 at once, and request 3 gives up after 5 attempts and shows "try again". The limit protects both the user and the struggling service.

In Java the helper takes a Supplier<T> (a lambda that returns the result), so one helper works for every call. The simulation uses a seeded Random to repeat the same failures, and it records the waits instead of sleeping so it runs instantly.

Notice that one request still fails after five attempts: retries reduce errors, they do not remove them.

Retry storms: retries multiply the load

A retry storm happens when retries at several layers multiply the load on a service that is already failing. It can keep the service down long after the first problem is fixed.

Retries multiply load. If three layers each try 3 times, one click can become 27 calls to a payment service that is already struggling.

RetryStormMath.javaJava
public class RetryStormMath {    public static void main(String[] args) {        int attemptsPerLayer = 3;      // each layer tries up to 3 times        int layers = 3;                // app -> order service -> payment service        int users = 1000;        long calls = (long) Math.pow(attemptsPerLayer, layers);        System.out.println("worst case per user click: " + calls + " calls to payments");        System.out.println("for " + users + " users: " + calls * users + " calls to a service that is already down");    }}
Output
worst case per user click: 27 calls to payments
for 1000 users: 27000 calls to a service that is already down

Retry at one layer only, usually the one closest to the failing call, and keep attempt counts small. A thousand users then send 3,000 calls at worst, not 27,000.

Common mistake: adding a retry in the app, in the order service and in the payment client, each unaware of the others. Look for the same call being retried at every layer.

The circuit breaker: stop calling a failing service

A circuit breaker watches the failures of a call. When there are too many, it opens and rejects calls at once for a cool-down time, instead of sending more load to a failing service.

A circuit breaker stops calls to a service that keeps failing. The example uses a fake clock to show it closed, open and half-open.

A circuit breaker has three states. Closed: calls go through and failures are counted. After 3 failures in a row it opens: calls fail at once. When the cool-down ends it is half-open and lets one trial call through. A working trial closes it; a failing trial opens it again.

Example 5 · A circuit breaker: closed, open, half-open

CircuitBreakerDemo.javaJava
class CircuitBreaker {    enum State { CLOSED, OPEN, HALF_OPEN }
    private final int failureThreshold;    private final long openForMs;    private State state = State.CLOSED;    private int failures = 0;    private long openedAt = 0;
    CircuitBreaker(int failureThreshold, long openForMs) {        this.failureThreshold = failureThreshold;        this.openForMs = openForMs;    }
    // nowMs comes from a fake clock so the run is repeatable    String call(long nowMs, boolean serviceIsUp) {        if (state == State.OPEN) {            if (nowMs - openedAt < openForMs) {                return "OPEN      -> rejected at once, no call made";            }            state = State.HALF_OPEN;                       // time to test the service again        }        if (serviceIsUp) {            String before = state.toString();            state = State.CLOSED;            failures = 0;            return String.format("%-9s -> call OK, circuit CLOSED", before);        }        failures++;        if (state == State.HALF_OPEN || failures >= failureThreshold) {            String before = state.toString();            state = State.OPEN;            openedAt = nowMs;            return String.format("%-9s -> call failed, circuit OPEN for %d s", before, openForMs / 1000);        }        return "CLOSED    -> call failed (" + failures + " of " + failureThreshold + ")";    }}
public class CircuitBreakerDemo {    public static void main(String[] args) {        CircuitBreaker breaker = new CircuitBreaker(3, 10_000);        long[] times = {0, 100, 200, 300, 400, 5_000, 10_300, 20_400, 30_500};        boolean[] up = {false, false, false, false, false, false, false, true, true};
        for (int i = 0; i < times.length; i++) {            System.out.printf("t=%5d ms  %s%n", times[i], breaker.call(times[i], up[i]));        }    }}
Output
t=    0 ms  CLOSED    -> call failed (1 of 3)
t=  100 ms  CLOSED    -> call failed (2 of 3)
t=  200 ms  CLOSED    -> call failed, circuit OPEN for 10 s
t=  300 ms  OPEN      -> rejected at once, no call made
t=  400 ms  OPEN      -> rejected at once, no call made
t= 5000 ms  OPEN      -> rejected at once, no call made
t=10300 ms  HALF_OPEN -> call failed, circuit OPEN for 10 s
t=20400 ms  HALF_OPEN -> call OK, circuit CLOSED
t=30500 ms  CLOSED    -> call OK, circuit CLOSED

What this code does

  • After 3 failures the circuit opens and calls at 300, 400 and 5,000 ms are rejected at once, giving the service a rest. The fake clock makes the run repeatable.
  • At 10,300 ms one half-open trial fails, so it opens again. At 20,400 ms the trial succeeds and the circuit closes.

A circuit has three states:

  • Closed: calls go through and failures are counted.
  • Open: after too many failures, calls fail at once without touching the service, for a cool-down time.
  • Half-open: after the cool-down, one trial call is let through. Success closes the circuit; failure opens it again.

Libraries such as Resilience4j provide retries and circuit breakers for Java and Spring.

Order of execution

Order a circuit breaker cycle

Put the life of one circuit in order.

Next step

Check your understanding

12 quick questions