Resilience patterns explained: timeouts, circuit breaker, retry with backoff and bulkhead

Failures will happen. Resilience patterns decide whether they stay small. Learn the five patterns every backend uses: timeouts, the circuit breaker, retries with exponential backoff and jitter, the bulkhead, and idempotency, and how they fit together.

A home fuse box with five labelled switches: payments, search, cart, login and recommendations. Four switches are up and green, labelled 'on'. The recommendations switch has tripped down and is red. A light bulb wired to the box is still glowing. A banner at the top says 'Trip one switch. Keep the lights on.'
Fig. 1 — A fuse box cuts off one faulty circuit so the rest of the house keeps working. Resilience patterns do the same for your services.

In the last article we saw how one slow service can drag down everything that calls it. We said the fix is to fail fast and contain the damage.

This article is about how. There are five small patterns that do most of the work:

Pattern The question it answers
Timeout How long will I wait?
Circuit breaker Should I even try calling it right now?
Retry with backoff Should I try again, and when?
Bulkhead How much of my capacity can one dependency use up?
Idempotency Is it safe to do this twice?
“Each pattern is simple on its own. The strength comes from using them together.”

1. Timeouts: never wait forever

A call with no timeout can hang for minutes. While it hangs, it holds a thread. Enough of those, and your service stops answering.

So every call that leaves your process needs a timeout: other services, databases, caches, outside APIs. Two numbers matter:

  • Connect timeout: how long to wait to open a connection. Keep it short, around 1 second.
  • Read timeout: how long to wait for the answer once connected.

How do you pick the read timeout? Look at how slow the call is on a bad day (its p99, the time 99% of calls finish within) and add a little room. If a service usually answers in 80 ms and its p99 is 400 ms, a 1-second timeout is sensible. A 30-second one is not.

One rule people often miss: timeouts must shrink as you go deeper. If the user’s request has 3 seconds in total, the service it calls can’t have 5 seconds, and the database behind that needs even less. Otherwise the outer layer gives up while the inner layers keep working on an answer nobody will read.

2. Circuit breaker: stop calling what’s broken

A timeout makes each call fail in 2 seconds instead of 30. But if a service is clearly down, why keep trying it at all? Every attempt still costs 2 seconds and a thread, and it keeps hitting a service that’s trying to recover.

A circuit breaker works like the one in your house. When too many calls fail, it trips, and further calls fail instantly without touching the broken service. After a short rest, it lets a few test calls through to see if things are better.

It has three states:

Three states drawn as circles with arrows between them. Closed, in green: calls go through normally and failures are counted. When, say, 50% of the last 20 calls fail, it moves to Open, in red: calls fail instantly without reaching the service, and a fallback is used. After a wait of, say, 30 seconds, it moves to Half-open, in amber: a few test calls are let through. If they succeed, it goes back to Closed. If they fail, it goes back to Open.
Closed: normal. Open: fail instantly and rest. Half-open: try a few calls to see if it has recovered.
  • Closed (normal): calls go through. The breaker counts failures.
  • Open (tripped): calls fail at once and use a fallback. The broken service gets a break.
  • Half-open (testing): after a wait, a few calls go through. If they work, back to closed. If not, back to open.

You don’t need to write this yourself. In Spring Boot, the usual choice is Resilience4j:

// Java · Spring Boot + Resilience4j
@CircuitBreaker(name = "recommendations", fallbackMethod = "popularItems")
public List<Product> recommendationsFor(String userId) {
    return recommendationClient.get(userId);
}

// Used when the call fails or the breaker is open
private List<Product> popularItems(String userId, Throwable error) {
    return catalog.mostPopular(10);
}
# application.yml
resilience4j.circuitbreaker.instances.recommendations:
  sliding-window-size: 20                    # look at the last 20 calls
  failure-rate-threshold: 50                 # trip if 50% of them failed
  wait-duration-in-open-state: 30s           # rest for 30 s before testing
  permitted-number-of-calls-in-half-open-state: 3

Give each dependency its own breaker. If payments and recommendations share one, a broken recommendation service can trip the breaker and block payments too. A critical dependency can also use stricter settings than a nice-to-have one.

3. Retries: try again, but politely

Many failures are brief: a dropped packet, a server restarting, a short spike. Trying again a moment later often works. But careless retries are one of the most common causes of big outages.

Here’s why. A database has a one-second hiccup and 1,000 requests fail. If every one retries at once, the database gets 1,000 extra requests the moment it’s trying to recover. It slows down, more requests fail, and they retry too. This is a retry storm.

Safe retries follow three rules:

  1. Retry only errors that might go away. Timeouts, connection errors, 429 Too Many Requests, 502, 503, 504. Never retry a 400 Bad Request or a declined card: it’ll fail the same way every time.
  2. Wait longer each time (exponential backoff). Wait 1 second, then 2, then 4. And stop after a few tries, usually 3.
  3. Add randomness (jitter). Without it, all 1,000 clients wait exactly 1 second and come back together. With a random extra wait, they spread out.
Two timelines. Top, retries without jitter: after a failure at time zero, all clients retry together at 1 second, then again together at 2 seconds and at 4 seconds, drawn as three tall spikes that hit the struggling service. Bottom, exponential backoff with jitter: the same retries are spread out as low, wide bumps between 1 and 1.5 seconds, 2 and 3 seconds, and 4 and 6 seconds. The service gets a gentle trickle instead of waves.
Backoff spaces out the tries. Jitter stops everyone from coming back at the same moment.
// Java · retry with exponential backoff and jitter
<T> T withRetry(Supplier<T> call) throws InterruptedException {
    for (int attempt = 1; ; attempt++) {
        try {
            return call.get();
        } catch (TransientException e) {               // only errors that may go away
            if (attempt == 3) throw e;                 // give up after 3 tries
            long base = 1000L << (attempt - 1);        // 1 s, then 2 s
            long jitter = ThreadLocalRandom.current().nextLong(base / 2);
            Thread.sleep(base + jitter);               // wait, with a random extra
        }
    }
}

One more thing: retries and timeouts multiply. If three layers each retry three times, one user click can become 27 calls at the bottom. Retry in one layer only, usually the one closest to the caller.

4. Bulkhead: keep each problem in its own room

Ships are split into sealed sections called bulkheads. If the hull is holed, one section floods and the ship stays afloat.

In a service, the “water” is threads and connections. Imagine one pool of 200 threads shared by every outgoing call. The recommendation service gets slow, and soon all 200 threads are waiting on it. Now payments, login and search have no threads left, even though those services are perfectly healthy.

Two panels. Left, one shared pool of 200 threads: a slow recommendation service has taken every thread, drawn as red blocks, so payments, search and login can't get one and fail. Right, separate pools: payments has 50 threads, search 50, login 30 and recommendations 20. The recommendation pool is full and red, but the other pools have free green threads and keep working normally.
With one shared pool, one slow dependency takes everything. With a pool per dependency, it can only use up its own.

The bulkhead pattern gives each dependency its own limit. With Resilience4j, that’s one setting per dependency:

resilience4j.bulkhead.instances:
  payments:
    max-concurrent-calls: 50      # payments can use at most 50 at a time
  recommendations:
    max-concurrent-calls: 20      # a slow recommender can only tie up 20
    max-wait-duration: 0          # if full, reject at once and use the fallback

When a bulkhead is full, extra calls are rejected right away. That sounds harsh, but a fast “no” plus a fallback is far better than every user waiting.

5. Idempotency: make “twice” safe

Retries have a hidden danger. Say the payment gateway does charge the card, but the reply is lost on the way back. Your code sees a timeout, retries, and charges the customer again.

An action is idempotent if doing it twice has the same effect as doing it once. “Set the balance to ₹500” is idempotent. “Add ₹500 to the balance” is not.

For actions that can’t be naturally idempotent, like charging a card, use an idempotency key:

  1. The client creates a unique ID for the action, such as a UUID, once, before the first attempt.
  2. It sends the same ID with every retry, often in an Idempotency-Key header. (Stripe’s payment API works this way.)
  3. The server stores each key with its result. If a key arrives again, it returns the saved result instead of doing the work again.

Without idempotency, retries aren’t safe. That’s why these two patterns always go together. We covered this in more depth in message delivery semantics.

How they fit together

A real call to another service usually goes through all of them, in this order:

  • The bulkhead checks there’s room for this dependency.
  • The circuit breaker checks the service isn’t known to be down.
  • The timeout limits how long this one try can take.
  • On a brief error, the retry waits (with backoff and jitter) and tries again, with the same idempotency key.
  • If it still fails, a fallback gives the user something useful.

What breaks, and how to fix it

What breaks What you see The fix
No timeout on one client Threads pile up behind one slow dependency A timeout on every outside call, based on its p99
One shared circuit breaker Broken recommendations trip the breaker and block payments One breaker per dependency, with its own settings
Retry storm A small hiccup turns into a long outage Few retries, exponential backoff, jitter, and retry in one layer only
Retrying permanent errors Wasted calls and slow failures on bad input Retry only timeouts, connection errors, 429 and 5xx
Retry without idempotency Customers are charged twice An idempotency key, created once and sent on every try

Puzzle 1: the timeout that charged twice

The mistake was treating a timeout as “it failed”. A timeout really means “I don’t know”. The work may have finished, may still be running, or may never have started.

The fix: send an idempotency key with the charge, so a retry with the same key can’t charge again. And after a timeout, ask the gateway for the status using that key before deciding anything. If the status is still unclear, mark the payment as “pending” and check again later, rather than charging blindly.

Puzzle 2: the bulkhead that blocked the sale

A bulkhead also limits throughput. With 10 slots and 2 seconds per call, you can finish at most 10 ÷ 2 = 5 payments a second. The other 95 a second are turned away.

To handle 100 a second, you need about 100 × 2 = 200 calls in flight at once. You could run 20 servers with 10 slots each, or 10 servers with 20 each, as long as the payment provider allows that many connections. A useful rule: in-flight calls = requests per second × seconds per call. Size bulkheads from your expected peak, not a guess.

Key takeaways

  1. Timeouts on every outside call, based on p99, and shorter the deeper you go.
  2. Circuit breakers stop calls to a service that’s clearly down: closed, open, half-open. One per dependency.
  3. Retries need limits, exponential backoff and jitter, and only for errors that may go away.
  4. Bulkheads give each dependency its own pool, so one slow service can’t take all your threads.
  5. Idempotency keys make retries safe. A timeout means “I don’t know”, not “it failed”.
  6. Use them together, with a fallback at the end.

Next in the Reliability & fault tolerance thread: disaster recovery. What happens when a whole region goes down, and how backups, RPO and RTO decide how much data and time you can afford to lose.

Comments

LEAVE A COMMENT
No sign-up. Comments appear after a quick review.