Resilience: timeouts, retries, circuit breakers, bulkheads, load shedding

In a system made of many services, something is always slow or broken. Resilience is the set of techniques that keep one failing part from taking everything down. This lesson covers five of them: timeouts, retries, circuit breakers, bulkheads and load shedding. Each one stops a different way that a small failure becomes a large outage.

1. Why Slow Is Worse Than Down

A hotel site has a search page. For each request it calls three services: pricing, photos and reviews. The page is busy, and the server has 200 threads (the usual Tomcat default).

Now the reviews service becomes slow, taking 10 seconds per call instead of 20 ms. A failed call returns quickly, but a slow call holds a thread the whole time. New requests keep arriving faster than the slow calls finish, so within a second all 200 threads are stuck waiting. The page cannot serve even requests that do not need reviews. Pricing and photos are healthy, yet the site is down.

This is a cascading failure: the problem spreads from the weak service to its callers, and from them to their callers. Every technique below stops that spread. A crash is easy, since callers get an error at once. Slowness quietly eats threads, connections and memory.

2. Timeouts

A timeout limits how long you wait for a call. Without it a hung dependency can hold your thread forever. Many clients have no timeout by default, or a very long one, so always set them yourself. In Spring Boot, set them on the client behind RestClient, as below. The ReviewClient in section 4.2 uses it.

  • Connect timeout: how long to wait to open the connection. Keep it short, for example 200 ms inside a data center.
  • Read (response) timeout: how long to wait for the answer after sending the request.
  • Overall deadline: the total time the user's request may take, including all retries.

How to choose the value: look at the dependency's normal latency and set the timeout a little above its p99. If reviews has a p99 of 80 ms, a timeout of 150 to 300 ms is reasonable. A timeout of 30 s protects nothing. A timeout that is too tight causes false failures and retry storms.

@Bean
public RestClient reviewsClient(RestClient.Builder builder) {
    HttpClient http = HttpClient.newBuilder()
            .connectTimeout(Duration.ofMillis(200))      // time to open the connection
            .build();
    JdkClientHttpRequestFactory factory = new JdkClientHttpRequestFactory(http);
    factory.setReadTimeout(Duration.ofMillis(300));      // time to wait for the response

    return builder.baseUrl("http://reviews").requestFactory(factory).build();
}

Pass the deadline down. If the user's request has 1 second in total and 700 ms are used, the next service should get only 300 ms, not a fresh full timeout. Otherwise the work continues after the caller has given up. Frameworks such as gRPC carry the deadline in the call for this reason.

A timeout alone is not enough. Even with a 500 ms timeout, a busy page can still fill all its threads while it waits. We need the next tools too.

3. Retries

Many failures are short-lived: a dropped packet, a server restarting, a brief overload. Trying again often works. But careless retries turn a small problem into a big one.

3.1 When to Retry

  • Retry only transient errors: timeouts, connection resets, 503. Do not retry a 400 or 404, since the answer will not change.
  • Retry only idempotent operations, or those protected by an idempotency key (see the queue lesson). Retrying "charge the card" without a key may charge twice.
  • Limit the attempts, usually 2 or 3 in total.

3.2 Backoff and Jitter

If a server is struggling and every client retries instantly, the retries add more load to the server that is already struggling. So wait between attempts, and wait longer each time (exponential backoff): 100 ms, 200 ms, 400 ms and so on, up to a cap.

But if 1,000 clients fail at the same moment, they all wait exactly 100 ms and retry together, then again at 200 ms, in synchronized waves. Jitter adds randomness so the retries spread out. The simplest form, "full jitter", picks a random wait between 0 and the backoff value.

<T> T callWithRetry(Callable<T> call) throws Exception {
    int maxAttempts = 3;
    long baseMs = 100;
    long capMs = 2_000;
    for (int attempt = 1; ; attempt++) {
        try {
            return call.call();
        } catch (TransientException e) {
            if (attempt == maxAttempts) {
                throw e;
            }
            long ceiling = Math.min(capMs, baseMs * (1L << (attempt - 1)));
            long waitMs = ThreadLocalRandom.current().nextLong(ceiling + 1);   // full jitter
            Thread.sleep(waitMs);
        }
    }
}

3.3 Retry Amplification

Retries multiply across layers. If the gateway, the search service and the reviews client each try 3 times, one user request can become 27 calls to a reviews service that is already down. This is a retry storm. The rules that prevent it:

  • Retry at one layer only, usually the one closest to the failing call. The others pass the error up.
  • Use a retry budget: allow retries to be at most about 10% of normal traffic. Beyond that, stop retrying and fail fast.
  • Honor Retry-After headers.

3.4 Hedged Requests

A hedged request helps with slowness, not errors. It sends the request to one replica, and if there is no answer after the typical p95 time, sends the same request to a second replica and uses whichever answers first. It cuts the slow tail of latency (see the availability lesson) for a little extra load. Use it only for idempotent reads.

4. Circuit Breakers

If reviews is down, trying every request anyway wastes time and threads on calls that will fail. A circuit breaker works like the fuse in a house: after enough failures it opens, and calls fail immediately, without touching the broken service. This gives the dependency time to recover and gives callers an instant answer.

stateDiagram-v2
    [*] --> Closed
    Closed --> Open: failure rate above threshold
    Open --> HalfOpen: wait time passed
    HalfOpen --> Closed: test calls succeed
    HalfOpen --> Open: a test call fails
  • Closed (normal): calls go through. The breaker counts successes and failures in a sliding window.
  • Open: the failure rate crossed the threshold, so every call fails immediately for a set time, for example 30 seconds.
  • Half-open: after the wait, a few test calls are let through. If they succeed, the breaker closes. If one fails, it opens again.

Count slow calls as failures too, since slowness is the more dangerous problem. With the breaker open, the search page makes no calls to reviews, so no threads are held.

4.1 Fallbacks: Degrade Gracefully

When the breaker is open, or a call times out, return something useful instead of an error. In order of preference:

  1. Cached data: show the last known reviews, even if a few minutes old.
  2. A default: a generic ranking instead of a personalized one.
  3. Leave the feature out: render the page without the reviews box.
  4. Fail clearly: for things that must be correct, such as a payment, return an error. Never make up a result.

4.2 In Practice with Resilience4j

Resilience4j is the standard Java library for these patterns (it replaced Netflix Hystrix, which is no longer developed). With Spring Boot, the configuration and usage look like this:

resilience4j:
  circuitbreaker:
    instances:
      reviews:
        slidingWindowSize: 20
        minimumNumberOfCalls: 10
        failureRateThreshold: 50
        slowCallDurationThreshold: 1s
        slowCallRateThreshold: 80
        waitDurationInOpenState: 30s
        permittedNumberOfCallsInHalfOpenState: 3
  bulkhead:
    instances:
      reviews:
        maxConcurrentCalls: 20
        maxWaitDuration: 0
@Service
public class ReviewService {

    private final ReviewClient client;
    private final ReviewCache cache;

    public ReviewService(ReviewClient client, ReviewCache cache) {
        this.client = client;
        this.cache = cache;
    }

    @CircuitBreaker(name = "reviews", fallbackMethod = "cachedReviews")
    @Bulkhead(name = "reviews")
    public List<Review> reviews(long hotelId) {
        List<Review> fresh = client.fetch(hotelId);   // has its own timeout
        cache.put(hotelId, fresh);
        return fresh;
    }

    // called when the breaker is open, the bulkhead is full, or the call fails
    List<Review> cachedReviews(long hotelId, Throwable cause) {
        return cache.getOrEmpty(hotelId);
    }
}

This means: at most 20 concurrent calls to reviews, open the circuit when half of the last 20 calls fail (or 80% are slower than 1 second), stay open for 30 seconds, and serve cached reviews meanwhile.

5. Bulkheads

A ship is divided into watertight compartments, so a hole floods one compartment and not the whole ship. A bulkhead does the same for your resources: each dependency gets its own limited share of threads or connections, so one slow dependency cannot use them all.

In our example, give reviews a limit of 20 concurrent calls. When reviews becomes slow, at most 20 threads get stuck. The call number 21 is rejected immediately and takes the fallback. The other 180 threads keep serving pricing and photos.

5.1 Thread-Pool Bulkhead

Each dependency gets its own small pool of threads, for example 10 threads and 5 queue places for waiting calls. The caller hands the call to that pool and waits for the result. If all 10 threads are busy and the queue is full, the next call is rejected at once (Resilience4j throws BulkheadFullException), and the caller uses its fallback. Because the call runs on another thread, the caller can also stop waiting after a time limit. The cost is extra threads. The method must return a CompletableFuture:

@TimeLimiter(name = "photos")                                // stop waiting after 500 ms
@Bulkhead(name = "photos", type = Bulkhead.Type.THREADPOOL)  // 10 threads, 5 queued (in the config)
public CompletableFuture<List<Photo>> photos(long hotelId) {
    return CompletableFuture.supplyAsync(() -> client.fetch(hotelId));
}

5.2 Semaphore Bulkhead

This is a counter. A call takes a permit, runs on the caller's own thread, and returns the permit. When no permits are left, the call is rejected. It costs almost nothing, so it is the usual choice. The reviews example above is a semaphore bulkhead. It cannot stop a call that is already running, so it needs a client timeout as well.

5.3 Isolate by Caller

Limit each tenant or traffic class separately, so one heavy customer cannot use up the shared capacity. In Resilience4j this is one bulkhead per tenant, created in code with a bigger limit for paying tenants. When a tenant is over its limit, the call throws BulkheadFullException. Map it to an HTTP 429 or 503, so only that tenant sees errors and the others are not affected.

5.4 Cells

At a larger scale, you run several complete copies of the service and its data, called cells, each serving a fixed group of users. A thin router at the front maps each user or tenant to one cell (a lookup table or a hash of the tenant ID). A bad deploy, a poison request or an overload then affects only the users of one cell. With ten equal cells, a failing cell touches only a tenth of the users. The cost is running more copies.

6. Load Shedding

The techniques above protect the caller from a bad dependency. Load shedding protects a service from too much incoming traffic. When a service is overloaded, it is better to reject some requests quickly than to try all of them and answer all of them slowly or never.

The reason is that latency rises sharply as a server nears full load (the queueing curve from the numbers lesson). Past 100%, queues grow without bound, and by the time a queued request is served, the user has already given up, so the work is wasted. The server spends all its effort on dead requests, and the useful throughput drops towards zero. Load shedding avoids this with five habits:

  • Bound the queues. A limit on waiting requests (and a short wait time) makes the service refuse work it cannot finish in time, instead of building a long line.
  • Reject early and cheaply. Return 503 Service Unavailable with a Retry-After header. A rejection costs almost nothing. A request that fails after 30 seconds of waiting holds a thread and a connection the whole time.
  • Shed by priority. Drop the least important traffic first: recommendations before search, search before checkout, and never the health checks. Background or batch traffic goes before interactive traffic.
  • Limit concurrency adaptively. Instead of a fixed number, the service lowers the allowed concurrent requests when its latency rises and raises it when latency is healthy (like TCP congestion control).

Rate limiting (a quota per client) is a separate tool with its own lesson. Scaling out is the other answer to load, but it takes minutes, while shedding works in milliseconds. Clients must also back off after a 503 (section 3).

6.1 In Spring Boot

Two small pieces are enough to start. Lower Tomcat's server.tomcat.accept-count (the line of waiting connections, 100 by default), so overload shows up as quick refusals and not long waits. Then add a servlet filter that counts requests in flight and returns 503 with a Retry-After header above a limit. Give low-priority paths such as recommendations a lower limit than search and checkout, and never shed health checks. Fixed limits are a simple start. Production systems often adjust them from measured latency.

7. Other Tools Interviewers Ask About

  • Health checks and self-healing. A liveness check says "restart me, I am stuck". A readiness check says "do not send me traffic yet", for example during startup or overload. Load balancers and Kubernetes use them to remove bad instances and restart them. Keep checks cheap: one that calls the database can take the whole fleet out of rotation when the database is slow.
  • Backpressure. When a consumer cannot keep up, tell the producer to slow down instead of buffering without limit. Examples are bounded queues, 429 responses and scaling on Kafka consumer lag.
  • Queue-based load leveling. Put a queue between a bursty producer and a slower worker, so the worker runs at a steady pace (see the queue lesson). It suits work that can wait.
  • Redundancy and failover. No single point of failure: several instances across zones, replicated data and a tested failover (see the availability and multi-region lessons). Redundancy handles a dependency that is gone. The patterns above handle one that is slow or failing.
  • Gentle recovery. When a service comes back, do not send it full traffic at once, because a cold cache and empty connection pools make it fall over again. Ramp up slowly, as the half-open state does.
  • Service mesh. A mesh (Istio, Linkerd) can apply timeouts, retries and circuit breaking in a sidecar proxy. Do not retry in both the mesh and the application, or the retries multiply (section 3.3).

8. How the Pieces Fit

Technique Protects against Cost or risk
Timeout A call that never returns Too tight causes false failures
Retry with backoff and jitter Short-lived failures Retry storms, duplicate side effects
Circuit breaker Repeatedly calling a broken service Needs a good fallback and tuning
Bulkhead One dependency using all resources Unused capacity in each partition
Load shedding Overload from too much traffic Some users get errors on purpose

From the outside in, a call goes through the bulkhead (is there room?), the circuit breaker (is the dependency healthy?), the retry (transient error?) and the timeout (never wait forever), with a fallback at the end. Then test it: inject slowness and failures in staging, or in controlled experiments in production (chaos engineering), to confirm it works.

9. Common Pitfalls

  • No timeouts, or default ones that are far too long.
  • Retrying non-idempotent calls without an idempotency key.
  • Retries without jitter, or at every layer, creating storms.
  • Retrying on overload, which makes the overload worse.
  • A circuit breaker with no fallback, so users just get faster errors.
  • Fallbacks that hide wrong data in critical paths such as money.
  • One shared thread pool or connection pool for all dependencies.
  • Deep health checks that call every dependency, so one slow dependency removes every instance from service.
  • Unbounded queues, which turn overload into long delays and then a crash.
  • Never testing failure. Settings that look fine on paper often fail in the first real incident.

10. Interview Questions This Lesson Prepares You For

  • What is a cascading failure, and how do you prevent it? A slow or failing service exhausts its callers' threads and spreads the failure. Prevent it with timeouts, circuit breakers, bulkheads, fallbacks and load shedding.
  • How do you choose a timeout? A little above the dependency's p99 latency, with an overall deadline passed down the chain so downstream calls do not outlive the caller.
  • How should retries be done? Only for transient errors on idempotent operations, with a small attempt limit, exponential backoff, jitter, a retry budget, and at one layer only.
  • Explain the circuit breaker states. Closed (normal), open (fail fast for a wait time), half-open (a few test calls decide whether to close or reopen).
  • What is a bulkhead? A separate limit of threads or connections per dependency or tenant, so one slow part cannot use all the resources.
  • What is load shedding, and how does it differ from rate limiting? Shedding rejects work when the service itself is overloaded, usually by priority. Rate limiting applies a per-client quota regardless of overall load.
  • How would you make a service resilient? Set timeouts and pass a deadline down. Retry only transient errors on idempotent calls, with backoff, jitter and a budget. Add circuit breakers with fallbacks, bulkheads, load shedding and bounded queues. Run several instances across zones with health checks, and test failures.
  • What is the difference between liveness and readiness checks? Liveness decides whether to restart an instance. Readiness decides whether it receives traffic, without a restart.
  • What is backpressure? A slow consumer pushing back on a fast producer, with bounded queues or rejections, instead of buffering until memory runs out.
  • Should resilience live in the code or in a service mesh? A mesh gives consistent timeouts, retries and breaking with no code changes. Code knows the business, so it chooses fallbacks and which calls are safe to retry. Use the mesh for the basics, code for the meaning, and never retry in both.
  • A downstream service is slow. What happens to yours, and what do you do? Threads pile up (rate × latency). Set a timeout, add a bulkhead and breaker, return a cached fallback, and alert on the dependency.