AlgoViz

Resilience in distributed systems

medium 28 min

A resilient system keeps doing its most important work while parts of it fail, and returns to normal by itself.

Video lesson · Chapter 1 of 6

Stop waiting before the pool fills

0:00 / 4:37

Resilience in 85 seconds

1:25Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

Resilience is the ability of a system to handle failures and recover from them while still serving people. It does not mean that nothing breaks. It means that a broken part stays a small problem.

In a distributed system every call to another machine can fail, hang, answer late or answer wrongly, and the caller often cannot tell which. Resilience is the set of decisions about what to do then: how long to wait, whether to try again, when to stop asking, and what to give the user instead.

Why it exists

Failures multiply. A request that needs ten parts, each available 99.9% of the time, succeeds only about 99% of the time. And failures spread: one slow part holds the threads of its callers, then the threads of theirs, until something unrelated stops.

A slow part is often worse than a dead one. A dead part answers with an error at once. A slow part makes everyone wait, and waiting costs memory, threads and patience.

A short history

  1. 1976

    Metcalfe and Boggs publish Ethernet. Stations that collide wait a random time whose range doubles: exponential backoff with jitter.

  2. 1982

    Lamport, Shostak and Pease publish The Byzantine Generals Problem, about agreeing when some members lie.

  3. 1985

    Jim Gray asks Why Do Computers Stop and What Can Be Done About It? Software and operations, not only hardware, are the causes.

  4. 2007

    Michael Nygard's book Release It! makes the circuit breaker and the bulkhead well-known software patterns.

  5. 2011

    Netflix describes its Simian Army. Chaos Monkey stops instances in production on purpose; its code is released in 2012.

  6. 2012

    Netflix open-sources Hystrix, a library of breakers, bulkheads and fallbacks. In 2018 it goes into maintenance and Resilience4j takes its place for many Java teams.

  7. 2021

    AWS launches Fault Injection Simulator, a managed service for controlled failure experiments.

Words to know

Transient failure
One that goes away by itself, such as a dropped packet.
Cascading failure
One failure that causes the next, and so on.
Timeout and deadline
The longest one call may take, and the moment the whole request must be done.
Backoff and jitter
Waiting longer before each retry, with a random part.
Circuit breaker
A guard that stops calls to a part that keeps failing.
Bulkhead
A limit that keeps one part from using everything.
Idempotent
Doing it twice has the same effect as doing it once.
Blast radius
How much is affected when something fails.

How it works

Step through the idea, or press Play.

Step 1 of 3

Limit the wait. A timeout on every call and a deadline for the whole request

Understand it

Start here

The doorbell

Imagine you want to play with a friend who does not open the door. You do not ring for an hour, and you do not give up after one second either. You do what a resilient system does. Older tales say the same: the superhero who finds another way when a door is locked or a bridge is broken.

Ringing Lee's bell
3:00DING!

The four rings: 3:00, then 3:02, 3:05 and 3:10, because Sam gives each ring one minute before the next wait begins.

The idea

Four pillars, and one promise

  • Timeout

    Do not wait forever. Set the longest time each operation may take.

  • Retry

    Try again, for failures that pass by themselves, with backoff and jitter.

  • Circuit breaker

    Stop the bleeding. Do not call a part that keeps failing.

  • Bulkhead

    Contain the failure. Keep parts from using each other's resources.

Safety equipment in a car works the same way: try starting again, do not wait forever, a fuse box for the breaker, separate compartments for the bulkhead. The promise to the user is the fifth part, the fallback: what they get when the first plan fails.

With resilience

  • Failures are contained
  • Answers stay quick, because waits are limited
  • Recovery is automatic
  • Users see a little less, not nothing

Without

  • One service fails and the system goes with it
  • One slow service makes every request hang
  • Failures spread from caller to caller
  • Users see errors and lose trust

Why ten good parts are not good enough

0.99910≈0.9900.999^{10} \approx 0.990
If a request needs all ten parts and failures are independent, 99.9% each gives 99.0%: ten times more failures than one part alone. Making some parts optional removes them from the product.

Failure

How things fail

A robot helper can break in three ways a child would notice: it stops, it becomes slow, or it does the wrong thing. Engineers use five names.

FailureWhat happensExampleDetected bySeverity
CrashStops and stays silentOut of memoryHealth checks, heartbeatsHigh
OmissionSome messages are lostDropped packetsTimeouts, acknowledgementsMedium
TimingToo slow, or too earlyA query takes 30 s instead of 100 msDeadlines, SLOsMedium, often the most damaging
ResponseThe wrong answerAnother user's data, a wrong sumChecksums, validation, reconciliationHigh
ByzantineAnything, including lies that differ per listenerA compromised nodeBFT agreement among 3f + 1 nodesCritical
From easiest to hardest to handle: crash, omission, timing, then arbitrary (Byzantine). A response failure is a wrong value, a different axis from silence or lateness. Inside one company's network most designs assume no Byzantine nodes.

How one slow service stops everything

Checkout never needed reviews. It failed because both shared the same threads.

Little's law shows the cascade

threads busy=requests per second×seconds each50×0.2=10,50×30=1500\text{threads busy} = \text{requests per second} \times \text{seconds each} \qquad 50 \times 0.2 = 10,\quad 50 \times 30 = 1500
At 50 requests a second, a 0.2 s call keeps 10 threads busy. At 30 s it wants 1,500. A pool of 200 is full after 4 seconds.

Pattern 1

Timeouts and deadlines

TimeoutStart with (inside one region)Why
ConnectWell under 1 sConnecting to a healthy server takes milliseconds
Read, one attemptThe dependency's p99.9 plus some room, such as 500 msAbout 1 call in 1,000 is cut off wrongly
Whole requestWhat the user will wait, such as 2 sAttempts and waits must fit inside it
Batch or reportMinutes, asynchronousGive people a progress state, not a spinner
The numbers are starting points. Measure your own latency. Many libraries have no timeout by default, so set one on every client.

Pass the deadline along: if the user's 2 seconds began 1.6 seconds ago, the next service has 0.4 seconds and should refuse work it cannot finish. Work for someone who has left is wasted load.

Pattern 2

Retries that help

Exponential backoff with full jitter

waiti=random(0, min⁡(cap, base⋅2 i))base=1 s: 1, 2, 4, 8 s at most\text{wait}_i = \text{random}\left(0,\ \min(\text{cap},\ \text{base} \cdot 2^{\,i})\right) \qquad \text{base} = 1\text{ s}:\ 1,\ 2,\ 4,\ 8\ \text{s at most}
The limit doubles; the actual wait is random below it, so thousands of clients do not return at the same instant (a thundering herd). Adding plus or minus 50% is a milder version. Apply the cap last.

Retry or not?

SituationRetry?Reason
Connection refused, reset, 503, 429Yes, laterOften temporary. Respect a Retry-After header
Timeout on a readYesReading twice is harmless
Timeout on a paymentOnly with an idempotency keyIt may have succeeded
400, 401, 404, validationNoThe same request fails the same way
Breaker open, bulkhead fullNo, use the fallbackRetrying fights the protection

Decide before you retry

Pattern 3

The circuit breaker

Three states

Closed means electricity flows: calls pass. Open means calls are refused at once. The numbers are typical starting values; many libraries open on a failure rate over a minimum number of calls instead.
  1. 1

    Closed: normal

    Calls pass. Failures are counted, and a success resets the count.

  2. 2

    Open: refuse

    No call leaves. The caller gets an error in microseconds and uses its fallback. The dependency gets a rest.

  3. 3

    Half-open: test

    A few calls are allowed, not all that are waiting. Enough successes close it, one failure opens it again.

Pattern 4

Bulkheads

A ship is divided into compartments, so one hole floods one of them. In software the water is slow calls, and the compartments are pools, semaphores, queues or whole copies of the system.

Three pools in one machine

One shop machine holds three separate pools of 10 threads each, for payments, reviews and search. Reviews is slow and its pool is full. Payments and search keep their own threads and work normally.
Reviews floods its own ten threads. Payments and search do not notice.

Larger bulkheads are cells: complete copies of the service that each serve a share of customers, so a bad release or a poison request reaches only that share. Smaller ones are limits per customer, which is rate limiting.

Pattern 5

Fallbacks and graceful degradation

FeatureWhen its part failsThe user sees
Product reviewsCached copy, or leave them out"Reviews are coming back soon"
RecommendationsA fixed list of popular itemsSlightly less personal
SearchA second, simpler indexFewer filters
PaymentAccept and queue, confirm later, if the business agrees"Payment pending"
Account balanceNo fallbackA clear error, never an invented number
Return cached data, use a default, call a backup service, queue for later, or turn off what is not essential. Say so honestly. A fallback that is never used is untested code, so exercise it.

Together

Layers of defence

One protected call

Users reach a gateway with a rate limit, then the orders machine, which contains retry, breaker, bulkhead and timeout. It calls the payment company, drawn outside our system. If that fails, it writes to a queue of pending payments, the fallback.
Protection sits on the caller's side. The payment company is outside our system and can do anything.

From the outside in

  1. 1

    Rate limit and load shedding

    Refuse extra work at the door, cheaply, before it uses anything.

  2. 2

    Fallback

    Wraps the rest: whatever fails inside, the user gets something sensible.

  3. 3

    Retry

    With backoff, jitter, a budget and the request's deadline.

  4. 4

    Circuit breaker

    Each attempt asks it first. A refusal is not retried.

  5. 5

    Bulkhead

    Each attempt needs a place in this dependency's pool.

  6. 6

    Timeout

    The innermost: each single attempt is limited.

Six design principles

  • Design for failure

    Engineers of earthquake-safe buildings do not hope for calm ground. Every network call can fail, every disk can fill, every service can crash. Plan for it.

  • Fail fast

    Do not hide errors. Stop early instead of writing corrupt data. Short feedback, clear messages.

  • Degrade gracefully

    Show cached data, switch off extras, queue for later, tell people.

  • No single points

    Several load balancers, database replicas, more than one zone, N+1 capacity. See high availability.

  • Automate recovery

    Restart on crash, replace on failed health checks, scale with load. People handle what is new.

  • Test failure

    Chaos experiments, load tests, failover drills, game days.

Proof

Chaos engineering

A fire drill has no fire. People practise, so that they know what to do in a real one. Chaos engineering does this for software: controlled experiments that build confidence that a system can withstand trouble in production. The definition is kept at principlesofchaos.org, started by people at Netflix.

  1. 1

    Define steady state

    A number for normal, such as 99.9% of checkouts succeed.

  2. 2

    Form a hypothesis

    "If one zone disappears, it stays above 99.5%."

  3. 3

    Inject the failure

    The smallest useful one, for a small share of users, with a stop button.

  4. 4

    Observe

    Compare with a control group. Stop at once if the limit is crossed.

  5. 5

    Learn and fix

    Repair, then run it again. Automate the ones that pass.

May this experiment go on?

The stop rule is written before the start, and it stops the experiment without a meeting.

Experiments and tools

ExperimentWhat you doExample tool
Instance terminationStop random serversChaos Monkey (Netflix, the first well-known one)
Network latencyDelay callsToxiproxy (Shopify)
Resource exhaustionFill a disk, use memoryGremlin (commercial platform)
Dependency failureMake an API return errorsLitmus (Kubernetes, CNCF)
DNS failureBreak name lookupsChaos Mesh (Kubernetes, started at PingCAP)
Zone outageRemove a zoneAWS Fault Injection Service
Most of these tools do several kinds. Start in a test environment.

A game day

BeforeDuringAfter
Define the blast radiusWatch the dashboardsBlameless review
Tell the people involved and get agreementCheck that the alerts fireActions with owners and dates
Have a stop button and a rollback planWrite down what you see, with timesShare what was learned

Checklist

Is this design resilient?

  1. 1

    Timeouts on every external call

    And a deadline for the whole request.

  2. 2

    Retries with backoff, jitter and a budget

    Only where a repeat is safe.

  3. 3

    Breakers for dependencies

    With their state visible.

  4. 4

    Bulkheads

    The optional parts cannot starve the essential ones.

  5. 5

    Health checks

    Separate liveness and readiness. See operability.

  6. 6

    Degradation paths

    A written answer for each dependency: what does the user get?

  7. 7

    Monitoring

    Error rate, latency, retries, breaker state, queue length.

  8. 8

    Regular failure tests

    A date in the calendar, not an intention.

Summary

The whole topic in one minute.

Assume every call can fail, hang or lie. Give each a timeout, retry only what is safe and temporary, wait longer each time with a random part, stop calling what keeps failing, and cap what one dependency may use.

Decide in advance what the user gets when a part is missing. Then prove it: break things on purpose, in a small area, with a stop button, and repair what you learn.

  • Every call can fail, hang, answer late or lie.
  • Slow is worse than dead: limit every wait.
  • Retry only temporary failures of safe calls, with backoff, jitter and a budget.
  • Breaker: closed, open, half-open. Bulkhead: one part cannot use everything.
  • Write the fallback down, and test it by breaking things on purpose.

Sources