How systems work

Retries and circuit breakers.

Every call over a network can fail. The other machine may be restarting, overloaded or just slow for a moment, and the packet may never arrive. A service that calls others has to decide, for every call: how long to wait, whether to try again, when, and when to stop calling altogether.

Get it right and brief failures disappear. Get it wrong and a two-second hiccup turns into an hour-long outage, because the clients that were meant to help keep the struggling service down. This page shows both happening.

Each lab is a simulation running in your browser. Each row on the left is a client thread and the call it is holding, and each chip is one attempt at that call. The number on a chip is the call, and the dark badge counts its attempts.

  • read on its way
  • charge on its way
  • came back ok
  • came back failed
  • caller stopped waiting
  • never answered

00 The life of one call

Before the live labs, follow a single call from a client to a struggling service: its timeout, its retry and the circuit breaker that steps in. Step through at your own pace, or press Play all.

Client appOne thread per callthread 1freethread 2call #5thread 3call #6Circuit breakerClosed: calls pass3 of the last 10 failedgateDownstream serviceTwo workers and a waiting lineworker 1worker 2waiting line · front on the rightWhat the user seesAnswer, error or fallbackNothing yetRetry planBackoff with jitter · no retries yetbefore try 20–0.4sbefore try 30–0.8s#1#2#3#4one thread per callcounts recent failuresextra requests wait here

Step 1 of 9

Meet the pieces

A client app calls a downstream service over the network. Each call holds one of the client's threads until it ends. A circuit breaker sits in the client and watches recent results. The service has two workers and a waiting line.

01 Timeouts: never wait forever

A call that is never answered does not fail. It just waits. While it waits it holds a thread, a connection from the pool or a slot in an event loop. Callers have a fixed number of those, so a downstream service that swallows one request in five slowly uses them all up.

Once every thread is waiting, the caller cannot start anything new. It fails every request, including ones that have nothing to do with the broken service. The fix is a timeout on every network call: after a set time, stop waiting, free the thread and treat the call as failed.

Clients · 3/s · 8 threadseach row is a thread holding one callDownstream servicedoes the work: workers and a linefree threadfree threadfree threadfree threadfree threadfree threadfree threadfree threadService20% no replyworker idleworker idleworker idleworker idleWaiting in line · 0Never answered · 0Last six calls · past 4 secondsnow
Threads busy
0 of 8
No thread free
0
Timed out
0
Success, last 5s
100%
Eight client threads. One request in five is never answered, and there is no timeout. Watch the threads fill up.

Click a chip or a thread row to follow one call and see what happened to it.

    Try this. Wait until all eight threads are stuck and “No thread free” starts climbing. Then set the timeout to 1 second. Stuck calls are dropped after a second, their threads come back and new calls get through again. The dashed chips left in the service are requests nobody is waiting for any more.

    Every network call needs a timeout, set a little above the slowest normal response. Many client libraries default to none, or to minutes.

    02 Retries turn brief failures into successes

    Many failures are brief: a packet dropped, a server restarting, a load balancer picking a bad host. Try the same call again a moment later and it usually works. If each attempt fails one time in four, two attempts both fail one time in 16, and three attempts one time in 64.

    Clients · 3/s · 8 threadseach row is a thread holding one callDownstream servicedoes the work: workers and a linefree threadfree threadfree threadfree threadfree threadfree threadfree threadfree threadService25% errorsworker idleworker idleworker idleworker idleWaiting in line · 0Last six calls · past 4 secondsnow
    Success, last 5s
    100%
    Retries
    0
    Service load
    0/s
    The service fails a quarter of requests at random. The timeline below shows each call's attempts: red bars failed, green succeeded.

    Click a chip or a thread row to follow one call and see what happened to it.

      Try this. Set attempts per call to 3. Success climbs from about 75% to nearly 100%, and in the timeline you can see calls that failed once and then succeeded. Look at service load too: it went up by about a third, because every retry is another request.

      Retries are cheap insurance against brief, random failures. They cost extra load, and that matters a lot when failures are not brief.

      03 Retry storms: when helping hurts

      Now say the service slows down for a few seconds: a long garbage-collection pause, a slow disk. Requests pile up in its waiting line and start timing out. Each timeout triggers a retry, so the clients now send two, three or four requests for every call, at exactly the moment the service can handle the fewest.

      Worse, the service still works through the requests whose callers gave up. Its line is full of work for nobody, every new request waits behind that line, times out and is retried. The slowdown ends, but the service never catches up. This is a retry storm, and the stuck state is called a metastable failure: the trigger is gone, but the retries keep the overload going.

      Clients · 7/s · no thread limiteach row is a thread holding one callDownstream servicedoes the work: workers and a linefree threadfree threadfree threadfree threadfree threadfree threadfree threadfree threadServiceHealthyworker idleworker idleworker idleworker idleWaiting in line · 0Requests reaching the service, per second · last 10sservice handles about 10/s
      Success, last 5s
      100%
      Service load
      0/s
      Waiting at service
      0
      Work for nobody
      0
      Seven calls a second into a service that handles about ten. Each call tries up to 4 times, retrying at once after a 1.5 second timeout.

      Click a chip or a thread row to follow one call and see what happened to it.

        Try this. Press “Slow the service 5x for 3s”. The load chart jumps past the red line and stays there long after the slowdown ends; success drops to zero. Press Reset, set attempts to 1 and do it again: a few calls fail during the slowdown, then everything recovers within seconds.

        Retries add load when a service is already struggling. Without limits, they can turn a short slowdown into an outage that only ends when someone cuts the traffic.

        04 Retries multiply across layers

        Real requests pass through several services. A browser calls a gateway, the gateway calls an API, the API calls a database. If each layer retries three times, the layers multiply: the API makes 3 database calls for each call it gets, the gateway makes 3 API calls, so one user request becomes 3 × 3 = 9 database requests, and with three layers, 27.

        Clients · 0.5/sa row is one threadDownstream servicedoes the work: workers and a linefree threadfree threadfree threadfree threadfree threadfree threadfree threadfree threadGatewayretries toocalls in0APIretries toocalls in0ServiceHealthyworker idleworker idleworker idleworker idleWaiting in line · 0Requests reaching the service, per second · last 10sservice handles about 10/s
        Requests per failed call
        –
        Service load
        0/s
        Retries
        0
        Clients, a gateway and an API, each trying 3 times in total. The middle boxes count calls arriving at each layer.

        Click a chip or a thread row to follow one call and see what happened to it.

          Try this. Press “Break the service” and wait for the first calls to fail: each one caused 27 requests. Set layers to 2 and the next failures cost 9; set it to 1 and they cost 3. With three layers, half a call per second from users becomes over a dozen requests per second on a service that is already down.

          Retry in one layer only, usually the one closest to the user or the one that knows the call is safe to repeat. The other layers should pass the failure up quickly.

          05 Exponential backoff and jitter

          Retrying at once gives the service no time to recover. Backoff means waiting before each retry. Exponential backoff doubles the wait each time: 1 second, then 2, then 4, up to a cap. Fewer retries land while the service is in trouble, and the ones that do are spread over a longer time.

          But backoff alone has a trap. When many calls fail at the same moment, say a server restarts and drops every connection, they all wait exactly 1 second and come back together. Then 2 seconds, together again. The service gets hit by waves. Jitter fixes this: wait a random time between zero and the backoff, so each client comes back at a different moment.

          Clients · 6/s · no thread limiteach row is a thread holding one callDownstream servicedoes the work: workers and a linefree threadfree threadfree threadfree threadfree threadfree threadfree threadfree threadServiceHealthyworker idleworker idleworker idleworker idleWaiting in line · 0Requests reaching the service, per second · last 10sservice handles about 10/s
          Service load
          0/s
          Retries
          0
          Success, last 5s
          100%
          The service handles about ten requests a second and turns requests away once ten are waiting. Freezing it drops every stuck request at once.

          Click a chip or a thread row to follow one call and see what happened to it.

          Backoff
            Try this. Press “Freeze the service for 3s”. When it wakes up it resets every stuck request at once. They all wait the same backoff, so the load chart shows one tall spike about a second later, and the requests turned away from that spike come back together in a second, smaller wave. Turn jitter on and freeze it again. The same retries now arrive spread over a second, and the spike is far lower.

            Use exponential backoff with a cap, and always add jitter. “Full jitter” (a random wait between zero and the backoff) is a good default.

            06 Retry budgets: cap retries as a share of traffic

            Backoff spaces retries out, but during a long outage every call still makes all its attempts. A retry budget limits retries to a share of normal traffic, say 10%. Each new call earns a tenth of a retry; each retry spends one. When the service is healthy there is always budget for the occasional retry. When everything fails, the budget runs out and extra load stays near 10%, instead of 300%.

            Clients · 5/s · no thread limiteach row is a thread holding one callDownstream servicedoes the work: workers and a linefree threadfree threadfree threadfree threadfree threadfree threadfree threadfree threadServiceHealthyworker idleworker idleworker idleworker idleWaiting in line · 0Requests reaching the service, per second · last 10sservice handles about 10/s
            Retries
            0
            Retries refused
            0
            Service load
            0/s
            Success, last 5s
            100%
            Each call tries up to 4 times, retrying at once. Break the service and compare the load with and without a budget.

            Click a chip or a thread row to follow one call and see what happened to it.

              Try this. Break the service for 10 seconds: the load roughly quadruples while it is down. Turn on the retry budget and break it again. Now most failed calls fail straight away (“Retries refused”), and the load during the outage stays close to normal.

              A budget keeps retries useful for brief failures and harmless during long ones. gRPC, Envoy, Finagle and the AWS SDKs all have a version of it.

              07 Only retry what is safe to repeat

              A timeout tells you that you stopped waiting, not that the work failed. The service may have charged the card and then been slow to reply. Retry that charge and the customer pays twice.

              Reads are safe to retry. Writes are safe only if they are idempotent: running them twice has the same effect as once. “Set the address to X” is idempotent; “charge $20” is not. For writes like that, the caller sends an idempotency key, a unique id for this operation, and the service remembers the keys it has finished. A repeat with the same key gets the first result back, without a second charge.

              Clients · 2/s · 8 threadseach row is a thread holding one callDownstream servicedoes the work: workers and a linefree threadfree threadfree threadfree threadfree threadfree threadfree threadfree threadServiceHealthyworker idleworker idleworker idleworker idleWaiting in line · 0Last six calls · past 4 secondsnow
              Charged twice
              0
              Repeats ignored
              0
              Timed out
              0
              Success, last 5s
              100%
              Every call is a charge. The caller times out after 0.8 seconds and retries up to 3 times.

              Click a chip or a thread row to follow one call and see what happened to it.

                Try this. Slow the service down. Charges now take longer than the timeout: the caller gives up, retries, and the first attempt still goes through. “Charged twice” climbs. Turn on the idempotency key and slow it again: the repeats are recognised and ignored. Or turn off “Retry writes”: no double charges, but those calls simply fail.

                Never retry a non-idempotent call blindly. Give writes an idempotency key, then retry them like reads. The message queue lesson shows the same idea for redelivered messages, and the payments system depends on it.

                08 Circuit breakers: stop calling a service that is down

                Timeouts and retries treat every call on its own. A circuit breaker looks at all of them. It sits in the client and counts recent results. It has three states:

                • Closed: calls go through as normal. The breaker watches the last few results.
                • Open: too many recent calls failed, so the breaker assumes the service is down. Calls fail at once without being sent. Threads are freed straight away and the service gets a rest.
                • Half-open: after a while the breaker lets one call through as a probe. If it succeeds, the breaker closes. If it fails, it opens again for another wait.
                Clients · 4/s · 8 threadseach row is a thread holding one callDownstream servicedoes the work: workers and a linefree threadfree threadfree threadfree threadfree threadfree threadfree threadfree threadclosedbreakerServiceHealthyworker idleworker idleworker idleworker idleWaiting in line · 0Circuit breaker · closedfailures ≥ 50%after 3sprobe failsprobe succeedsClosedOpenHalf-openLast results the breaker counted (closed state)0 of the last 0 failed
                Failed fast
                0
                Wait to fail
                –
                Service load
                0/s
                Success, last 5s
                100%
                The bar beside the client threads is the breaker. It opens when half of the last ten calls failed, and stays open for 3 seconds.

                Click a chip or a thread row to follow one call and see what happened to it.

                  Try this. Break the service for 10 seconds. Watch the result dots fill with red until the breaker opens; calls then fail at the gate without reaching the service. Every 3 seconds one probe goes through and fails, until the service is back and a probe succeeds. Turn the breaker off and repeat: every call goes to the dead service, and “Wait to fail” is higher.

                  A breaker turns slow failures into fast ones and takes the load off a service while it recovers. Pair it with a fallback, so an open breaker means a degraded answer rather than an error.

                  09 Bulkheads and fallbacks

                  A ship is split into watertight compartments, so one hole floods one compartment, not the whole hull. A bulkhead in software does the same with resources: each downstream service gets its own pool of threads or connections. When one service hangs, it can only use up its own pool, and calls to everything else carry on.

                  A fallback is what you return when a call fails: yesterday’s recommendations from a cache, a default value, a page without the broken widget. Not every call has a sensible fallback (a payment does not), but many do, and the user then sees a slightly worse page instead of an error.

                  Clients · 4/s · 8 threadseach row is a thread holding one callServicesdoes the work: workers and a linefree threadfree threadfree threadfree threadfree threadfree threadfree threadfree threadService AHealthyworker idleworker idleWaiting in line · 0Never answered · 0Service BHealthyworker idleworker idleWaiting in line · 0Last six calls · past 4 secondsnow
                  B calls turned away
                  0
                  No thread free
                  0
                  Answered, last 5s
                  100%
                  Threads busy
                  0 of 8
                  Calls alternate between service A and service B, sharing eight threads. The timeout is a generous 6 seconds.

                  Click a chip or a thread row to follow one call and see what happened to it.

                    Try this. Make service A hang. Its calls hold threads for 6 seconds each, soon all eight are A’s, and calls to the healthy service B are turned away too. Reset, turn on bulkheads and try again: A can only fill its own four threads, and B carries on untouched. Add the fallback and every call gets an answer.

                    Isolate each dependency so one failure stays one failure, and decide in advance what each call returns when it fails.

                    10 Where you get these in practice

                    You rarely write these patterns by hand. Libraries add them to your code; a service mesh adds them to the network between services. A rough map:

                    ToolWhere it runsRetriesBreaker and isolation
                    Resilience4jLibrary for JavaRetry with fixed or exponential waits and optional randomnessCircuit breaker with count or time windows and slow-call detection; bulkheads (semaphore or thread pool); time limiter
                    PollyLibrary for .NETRetry with constant, linear or exponential backoff and jitterCircuit breaker by failure ratio over a time window; timeout; fallback; concurrency limiter; hedging
                    EnvoyProxy beside each servicePer-route retry policy with per-try timeout, backoff with jitter and a retry budget“Circuit breaking” is limits on connections, pending requests and retries; outlier detection removes hosts that keep failing
                    IstioService mesh built on EnvoyRetries set on a VirtualService (attempts, per-try timeout, which errors)Connection pool limits and outlier detection set on a DestinationRule
                    AWS SDKsBuilt into each SDKRetry modes: legacy, standard (exponential backoff with jitter and a retry quota) and adaptive (adds client-side rate limiting)None built in; add a library for breakers

                    Defaults differ between tools and versions, and some retry by default. Check the current docs for what yours does, and make sure two layers are not both retrying the same call.

                    11 Check yourself

                    1. A user request passes through a gateway, an API and a database client. Each retries a failed call 3 times in total. The database is down. How many database requests can one user request cause?

                    2. A service restarts and drops 500 connections at once. Every client retries after exactly 1 second, then 2, then 4. What does the service see?

                    3. A charge request times out. What do you know?

                    4. A circuit breaker is open. A new call comes in. What happens?

                    5. Your service calls a recommendations API with no timeout. The API starts hanging. What breaks first?