Nguyen Le Phong

Foundations of Software ArchitecturePart 9 of 15

Timeouts, Retries and Circuit Breakers: Stop One Slow Service From Taking Down the Rest

A call that leaves your process can hang, fail or run twice.

Say your checkout service calls a recommendations service to fill a "you might also like" box. One afternoon recommendations gets slow. It isn't down, just slow: every call takes 30 seconds instead of 80 ms. Checkout has no timeout on that call, so each incoming request grabs a thread and waits. A few minutes later every thread is waiting and nobody can pay. A side feature that nobody was watching has just taken down the part of the business that makes money.

That's the bill you sign up for when you split a system into services that talk over the network (the earlier post on moving from a monolith to microservices touches on it). A function call inside one process returns or throws. A network call can be slow, can fail, or can succeed on the other side while your side never hears back. This post covers the small set of patterns that stop one bad dependency from spreading: timeouts, retries with backoff and jitter, idempotency, circuit breakers, bulkheads and fallbacks. For each one you'll get when it helps and when you can skip it.

An engineer points at a live systems dashboard on a large screen while three teammates follow the failure path around a meeting table.
Most resilience work starts with a question like this one: one dependency is slow, so how far can its slowness travel?

The network was never reliable

In 1994, L Peter Deutsch at Sun Microsystems wrote down seven false assumptions people make about distributed systems, building on four that Bill Joy and Dave Lyon had listed earlier. James Gosling added an eighth around 1997 (Fallacies of distributed computing). The first three are the ones that bite in everyday service code:

  • The network is reliable. Packets drop, connections reset, and load balancers restart in the middle of a request.
  • Latency is zero. A call to another service in the same data center costs far more than a function call, and every so often one takes much longer than usual.
  • Bandwidth is infinite. Pull a 5 MB payload on every request and you'll find out it isn't.

The other five (security, changing topology, many administrators, transport cost, mixed networks) are worth reading too, but this post sticks to the first three. The nastiest case is the third possible outcome of a call: you sent the request, the other side may have done the work, and the response never arrived. From where you sit, "it failed" and "it worked but I didn't hear about it" look identical. Most of the patterns below exist because of that gap.

Timeouts: put a limit on every wait

Back to checkout. The fix that would have saved it fits on one line:

// Before: if the other side hangs, this request hangs with it
// const res = await fetch(url)

// After: give up after 800 ms
const res = await fetch(url, { signal: AbortSignal.timeout(800) })   // rejects with a TimeoutError

A call that fails after 800 ms is something you can handle: show a fallback, retry later, return a clear error. A call that hangs holds a thread, a socket and memory for as long as it hangs, and the queue behind it keeps growing. In the browser and in Node, AbortSignal.timeout() rejects the fetch with a TimeoutError you can catch (MDN). Every HTTP client, database driver and queue consumer has its own version of this setting. Find it and set it, because the default is often "wait as long as it takes".

How long is right? Marc Brooker describes Amazon's method in the Builders' Library: pick the rate of false timeouts you can live with, for example 0.1%, then set the timeout at the matching latency percentile of the dependency, here p99.9 (Timeouts, retries, and backoff with jitter). So you need the dependency's latency histogram before you pick a number. Measure first, then tune.

Timeouts along a call chain also have to agree with each other. Google's SRE book suggests passing deadlines down the chain: if a request arrives with 30 seconds to live and you spend 7 before calling the next service, hand it a 23-second deadline. That way nobody downstream keeps working on an answer the caller has already given up on (Addressing Cascading Failures).

Retries: useful, until everyone retries at once

Lots of failures are brief: a node restarts, a connection drops, traffic spikes for a few seconds. Trying again a moment later usually works. The trouble starts when a dependency is slow because it's overloaded. Every caller times out and retries straight away, so the struggling service now gets twice the traffic. It slows down further, the next round of timeouts brings more retries, and a wobble turns into an outage.

Retries also multiply across layers. In Brooker's example, a five-layer call stack where each layer retries three times can put 243 times the load on the database at the bottom. His advice is to retry at a single point in the stack.

The usual safety kit:

  • Exponential backoff. Wait longer after each failure: 100 ms, then 200, then 400, up to a cap.
  • Jitter. Randomize each wait so a thousand clients that failed together don't retry on the same tick. In Brooker's simulations on the AWS Architecture Blog, backoff without jitter was "the clear loser": it made more calls and took longer to finish than the jittered versions (Exponential Backoff And Jitter).
  • A limit per request. A few attempts, then return the error.
  • A budget per process. The SRE book suggests a server-wide retry budget, for example 60 retries per minute in a process, and failing instead of retrying once it's spent. Brooker describes the same idea as a local token bucket, which AWS added to its SDK in 2016.
  • Only retry what's safe to repeat. That's the next section.
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))

async function withRetry(call, { attempts = 3, baseMs = 100, capMs = 2000 } = {}) {
  for (let i = 0; ; i++) {
    try {
      return await call()
    } catch (err) {
      if (i + 1 >= attempts) throw err        // budget spent: surface the error
      const backoff = Math.min(capMs, baseMs * 2 ** i)
      await sleep(Math.random() * backoff)         // full jitter: anywhere from 0 to backoff
    }
  }
}

This is the shape, not the whole thing. Real code also checks whether the error deserves a retry at all: a timeout or a 503 does, a 400 never will.

Retries can cause the outage

A struggling service needs fewer requests, and a burst of retries sends it more. Before you add a retry, ask what happens if every client does it at the same moment. If the honest answer is "traffic doubles", add backoff, jitter and a budget first.

Idempotency: what makes a retry safe

Retrying a read is harmless. Retrying "charge this card $40" is a different story if the first attempt went through and only the response got lost. Brooker puts it plainly: APIs with side effects aren't safe to retry unless they provide idempotency. Idempotent means doing it twice has the same effect as doing it once.

The usual tool is an idempotency key. The client generates one unique ID per logical operation and sends it with every attempt. The server stores the result of the first attempt under that key and returns the same result for any repeat. Stripe's API works this way: you send an Idempotency-Key header, Stripe saves the status code and body of the first request, replays them for retries with the same key, and returns an error if a retry comes with different parameters. Stripe suggests V4 UUIDs as keys and may prune a key once it's at least 24 hours old (Stripe API: Idempotent requests).

Three engineers review a flow diagram on a table, marking where callers should back off and where repeated requests need deduplication.
Two questions for every arrow on the diagram: where should the caller back off, and where does a repeat have to be harmless?
// The client sends the same key on every attempt. The server replays the first result.
async function charge(req) {
  const saved = await processed.get(req.idempotencyKey)
  if (saved) return saved                       // seen this key: no second charge

  const result = await paymentGateway.charge(req)
  await processed.set(req.idempotencyKey, result)
  return result
}

This sketch has a gap you should know about. If two copies of the same request land at the same moment, both can miss the lookup and both charge. A real system reserves the key first with something atomic, such as an insert against a unique index, and only then calls the payment gateway. Designing idempotent APIs walks through the full version.

When I worked on the partner integrations with Gtel and Napas, idempotent contracts sat right next to the retry queues for exactly this reason. The partner side will resend, and so will yours.

Exactly-once, with fine print

Message brokers deliver at least once, and the relay in the outbox pattern keeps retrying until it gets an acknowledgment. Some tools advertise exactly-once processing, and inside their own boundary they can mean it. Once the effect leaves that boundary (an email, a card charge, a call to a partner API), deduplication is your job again. At-least-once delivery plus idempotent handling is the version you can build and reason about.

Circuit breakers: stop calling what's already down

When a dependency is fully down, retries only waste time. Every call burns a full timeout, holds a thread and ends in the same error. A circuit breaker wraps the call and keeps a little state about recent failures. Michael Nygard popularized the pattern in his book Release It!, and Martin Fowler's short write-up is still the clearest explanation around (CircuitBreaker).

A circuit breaker has three states. Closed lets calls through and counts failures. Too many failures switch it to Open, where calls fail at once. After a cooldown it goes Half-Open and lets one test call through, which decides whether it closes again or re-opens. FAIL FAST, THEN SEND ONE TEST CALL TO SEE IF IT'S BACK CLOSED calls go through OPEN fail at once HALF-OPEN one test call failures > threshold after cooldown test OK → close test fails → re-open
The breaker protects both sides. The struggling service stops getting hammered, and callers stop holding threads for calls that were always going to fail.

The three states come from electrical wiring. Closed: calls go through and the breaker counts failures. Once failures cross a threshold it opens, and calls fail immediately without touching the network. After a cooldown it goes half-open and lets one test call through. If that works, it closes. If it fails, it opens again and the cooldown starts over.

You win on both ends. The sick service gets room to recover, and callers get an answer right away instead of after a timeout, which pairs nicely with a fallback. The cost is tuning: a breaker that trips too easily turns a handful of slow calls into a full outage of that feature. Libraries such as Resilience4j for Java and Polly for .NET ship well-tested breakers, so you rarely need to write your own.

Bulkheads: one leak, one compartment

A ship's hull is split into sealed compartments, so a hole floods one section and the ship stays afloat. Microsoft's Azure Architecture Center describes the software version: give each dependency its own connection pool or thread pool, so when one service stops responding, only the pool for that service fills up and calls to the others carry on (Bulkhead pattern).

In the checkout story, a small separate pool for recommendation calls would have capped the damage. Those calls would queue and fail, and payments would still have their own threads. The same doc is upfront about the cost: resources get used less efficiently, and you add complexity you might not need yet.

Fallbacks: a worse answer beats a blank page

Staying up is half the job. The other half is staying useful when a piece is missing. For each dependency, decide ahead of time what the page does without it:

  • Serve stale data. A product description cached an hour ago beats an error message.
  • Use a default. Recommendations down? Show the bestsellers.
  • Drop the extras. Hide the live stock badge and let people check out.

Some dependencies have no honest fallback: you can't take a payment without the payment provider. For those, fail fast, say clearly what happened and keep the cart so the customer can try again. Settle which dependencies get a fallback in a design review, not at 2 a.m. during the incident.

Make the patterns visible

Every pattern above hides symptoms on purpose. A retry that works on the third try looks like success. An open breaker serving fallbacks looks like a working page. That's great for users and risky for the team, because a dependency can be failing for days before anyone notices.

So give each pattern a metric: timeouts per dependency, retry counts, breaker state changes, how often fallbacks get served. Add distributed tracing so you can follow one slow request across every hop and see which service added the latency. Alert when a breaker opens or the retry rate climbs, not only when users see errors. Observability at scale goes deeper on tracing.

An engineer at two monitors in the evening compares latency charts, traces and logs side by side.
Put retry counts and breaker state on the same dashboard as latency, and you see a dependency in trouble before your users do.

The cheat sheet

None of these patterns is exotic. The skill is matching the right one to the failure in front of you, and not adding all of them on day one.

The failure you seeThe pattern that answers it
A dependency is slow or hangsA timeout on every outbound call, set from measured latency
A short, passing failureA retry with exponential backoff, jitter and a budget, in one layer only
A dependency is fully downA circuit breaker: fail fast, send a test call now and then
The same request arrives twiceAn idempotency key, reserved atomically
One slow dependency eats every threadBulkheads: a separate pool per dependency
A non-critical piece is missingA fallback decided before the incident
"Is any of this happening right now?"Metrics for timeouts, retries and breaker state, plus tracing

What to do at each stage

  • Small team, a few services: timeouts on every outbound call, plus idempotency keys on anything that moves money or sends a message to a person. Those two cover the failures that hurt most, for very little code.
  • Growing team: retries with backoff, jitter and a budget, in one place in the stack. Breakers around your flakiest dependencies. Tracing as soon as a latency bug takes more than an hour to pin down. Written fallbacks for your top user flows.
  • Large organization: bake these defaults into shared client libraries or a service mesh so every team gets them for free. Set SLOs, and run fault-injection tests that break dependencies on purpose to check that the breakers and fallbacks really work.

Try this week

  • Search your code for outbound HTTP and database calls with no timeout. Add one to the call your main flow depends on most.
  • Find every place that retries. If more than one layer retries the same call, keep one.
  • Add jitter to any backoff that doesn't have it.
  • Pick your most important write endpoint and check what happens when the same request arrives twice.
  • Write down the fallback for one dependency on your main user flow, or write down that it has none.

Timeouts and retries keep one call honest. When a business action spans several services and fails halfway, you need a plan for the data too, and the saga pattern picks up from there.

What did you think?

Frequently asked questions

What's the difference between a timeout and a circuit breaker?
A timeout limits how long one call can wait. A circuit breaker watches many calls, and once failures cross a threshold it stops calling that dependency for a cooldown period and fails those calls at once. Every outbound call needs a timeout. Breakers belong around dependencies that fail often enough to hurt.
How many times should I retry a failed request?
A few times at most, with exponential backoff and jitter, and in only one layer of the call stack. Amazon's Marc Brooker shows that five layers each retrying three times can multiply the load on the bottom service by 243. Google's SRE book also suggests a retry budget per process, for example 60 retries per minute.
Why add jitter to exponential backoff?
Without jitter, clients that failed at the same moment also retry at the same moment, so the recovering service keeps getting hit by spikes. In simulations published on the AWS Architecture Blog, backoff without jitter made more calls and took longer to finish than the jittered versions.
What is an idempotency key?
A unique ID the client generates for one logical operation and sends with every retry. The server stores the first result under that key and returns it for repeats, so a retried payment doesn't charge twice. Stripe's API uses an Idempotency-Key header this way and returns an error when a repeat arrives with different parameters.
Do small systems need circuit breakers and bulkheads?
Usually not at first. Timeouts on every outbound call and idempotency on endpoints that move money or send messages cover the most painful failures. Add breakers and separate pools once a specific dependency has shown it can drag the rest of the system down.