TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท distributed systems ยท resilience

Circuit breakers and retries

Keeping one failing dependency from taking down everything that calls it. Retry transient failures with backoff and jitter, and use a circuit breaker to fail fast while a dependency is down.

10 min4 animations

๐Ÿ–จ๏ธ Cheat sheet

A brief flicker

When the toaster gets no power, it's often just a flicker. The sensible thing is to try again, but not frantically: wait a moment, then a little longer each time, and give up after a few tries.

Retries with backoff and jitter

Many failures in distributed systems are transient: a dropped connection, a brief overload, a leader election. Retrying helps, but naive retries make overload worse. Good retries:

  • use exponential backoff (1s, 2s, 4sโ€ฆ) with a maximum,
  • add jitter (randomness), so thousands of clients don't retry at the same instant,
  • are capped in number, with an overall timeout,
  • are only used for idempotent operations, or ones carrying an idempotency key.
Trying again, politely3 steps
๐ŸžToaster๐Ÿ”ŒWall socket
Press play and watch it happen!

The fuse trips

But if the kettle is actually broken, retrying forever just keeps the kitchen waiting. A fuse box notices the repeated faults and trips, cutting that circuit off. Now anything that needs the kettle hears "no" instantly and can use a backup plan, and the rest of the house carries on.

The circuit breaker

When a dependency is down, every call waits for a timeout, holding a thread or connection. Callers pile up, run out of threads, and fail too: a cascading failure. A circuit breaker wraps the calls:

StateBehaviour
ClosedCalls pass through; failures are counted
OpenCalls fail immediately, without touching the dependency
Half-openA few trial calls test whether it has recovered

Failing fast frees resources and gives the struggling service room to recover. Pair it with a fallback: cached data, a default, or queueing the work.

The fuse trips4 steps
๐ŸณKitchenโšกFuse box๐Ÿซ–Broken kettle
Press play and watch it happen!

Testing before switching back

After a while the fuse box lets one careful test through. If it works, everything switches back on. If not, the fuse stays off a while longer.

Recovery, and in Java

After the open wait, the breaker goes half-open. Successful trials close it; a failure reopens it. With Resilience4j in Spring Boot:

1@CircuitBreaker(name = "payments", fallbackMethod = "queueForLater")2@Retry(name = "payments")3public Receipt charge(Order order) {4    return paymentsClient.charge(order);5}

Thresholds, wait durations and backoff are set in application.yml under resilience4j.circuitbreaker and resilience4j.retry.

Testing the fuse3 steps
๐ŸณKitchenโšกFuse box๐Ÿซ–Kettle
Press play and watch it happen!

When the fuse box gets it wrong

Fuses can go wrong too, in three ways:

  • Sometimes every cook tries again at once, and the kitchen asks the cook next door, who asks the cook next door, until one kettle gets twenty-seven requests for one cup. So the kitchen makes only one cook retry.
  • Sometimes the kettle is not broken, only very slow, and the fuse box is set to watch only for sparks, so it never trips while the cooks stand waiting. So the kitchen makes the fuse box watch for slowness as well.
  • And when the fuse does trip, a cook who just hands out yesterday's tea can hide that the kettle is still broken. So the kitchen sets a sign on the tea saying how old it is.

What can go wrong

  • Retry amplification. Each layer retries on its own: with 3 attempts at each of 3 layers, one user request can become 3 x 3 x 3 = 27 calls to the bottom service, just when it is struggling. The same happens when an inner timeout is longer than the caller's own: the caller gives up and retries while the first call is still running. Observe: dependency traffic several times the user traffic, rising during an incident. Fix: retry in one layer only, keep backoff with jitter, and give each inner call a shorter timeout than the one above it.
  • Retrying a non-idempotent call. A timeout does not mean the call failed; the charge may have succeeded and only the reply was lost. Retrying creates a duplicate. Observe: double charges, duplicate rows. Fix: send an idempotency key so the server ignores the repeat, or only retry safe calls (see idempotency).
  • A breaker that never opens. Resilience4j defaults: minimumNumberOfCalls is 100, so a low-traffic service isn't judged until 100 calls have been recorded (and with a time-based window, maybe never); slowCallRateThreshold is 100 (percent), so slow calls only open it when every call is slow; slowCallDurationThreshold is 60 seconds. A dependency that answers in 8 seconds with no errors looks healthy. Observe: breaker stays CLOSED while threads block and latency climbs. Fix: lower the minimum calls, set a realistic slowCallDurationThreshold and a slowCallRateThreshold below 100, and add a timeout.
  • Flapping and a probe stampede. Half-open allows permittedNumberOfCallsInHalfOpenState trial calls (default 10) and admits the first 10 calls that arrive, concurrently, so under load a just-recovering dependency gets a burst; if enough of them fail (failureRateThreshold, default 50%), the breaker reopens; repeat. Observe: state transitions OPEN, HALF_OPEN, OPEN in the metrics, with latency oscillating. Fix: fewer trial calls, a longer or growing open wait (waitIntervalFunctionInOpenState), and a larger sliding window.
  • A fallback that hides the outage. Returning cached or default data keeps pages loading, but nobody notices the dependency is down, and users may act on stale or wrong data (an old price, an empty cart). Observe: no errors, yet a breaker stuck open or fallback counters rising. Fix: alert on breaker state and fallback use, mark fallback data as stale, and only fall back where wrong data is harmless.
ChoiceYou gainYou pay
More retriesRecovers more transient failuresMore load on a struggling service, longer waits, duplicates if unsafe
Short timeoutsThreads freed fast, quick failureSlow but valid calls get cut off, more retries
Fallback instead of fail fastThe page still worksHidden outages, stale or wrong data
Per-instance breaker stateNo shared store, no extra failure pointEach instance learns the outage alone, so the dependency still gets probes from all of them

Resilience4j keeps breaker state inside each JVM. Calls rejected by an open breaker throw CallNotPermittedException, which a retry should not keep retrying.

A slow dependency, with and without a trip5 steps
Cooks waiting0123๐ŸณKitchenโšกFuse box๐Ÿซ–Kettle
Press play and watch it happen!
๐Ÿ”ง Going deeper

Timeouts first: without a timeout on every network call, neither retries nor breakers can help, because a call can hang forever.

Bulkheads limit how many concurrent calls go to each dependency, so one slow service can't take every thread.

๐Ÿ—๏ธ Design it in CloudArch

Build the architecture on a canvas, push load through it and see what breaks.

  • ๐Ÿ›ก๏ธFlash sale (resilient)The same shop with a queue, caching and pre-warming, so the spike is survived.guided design

๐Ÿงฉ Quick quiz

Quick quiz! 5 questions about Circuit breakers and retries, told the same way as the story.
  1. The toaster gets no power for a moment. What's the sensible thing to do?
  2. The kettle is broken and keeps failing. What does the fuse box do?
  3. After a while, what does the fuse box do before switching back on?
  4. Three cooks in a row each try up to three times in all when the kettle is slow. How many requests can the kettle get for one order?
  5. The kettle answers every order, but takes eight seconds each time, and cooks pile up waiting. The fuse box stays on. Why?
Answer every question to check.Passing marks Circuit breakers and retries as done.
Got the hang of Circuit breakers and retries? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

๐ŸŽฏ Backend interview prepStep 6 of 9

โ† Previous on the path๐ŸŽก Load balancingNext on the path โ†’๐Ÿ“‹ Distributed caching

๐Ÿš€ Shipping to productionStep 8 of 10

โ† Previous on the path๐ŸŽก Load balancingNext on the path โ†’๐Ÿฌ Rate limiting

๐Ÿ‘‰ Read next

  • ๐Ÿ”˜IdempotencyPressing a lift button five times still calls one lift: the system remembers each press.