Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Concept · 20 min · revision 1

Circuit breakers, bulkheads and load shedding

Contain a failing dependency: circuit breakers that stop calling it, bulkheads that cap what it can take from you, load shedding that lets a server refuse work it cannot finish, and fallbacks that fail open or closed on purpose.

Contentsand lesson path

On this page

  1. Why it matters
  2. Circuit breakers
  3. Bulkheads
  4. Load shedding
  5. Graceful degradation and fallbacks
  6. Check your understanding
  7. Apply it
  8. Review prompt

Lessons of Resilience Patterns

  1. How cascading failures happen Concept · 20 min
  2. Timeouts, retries, backoff and jitter Concept · 20 min
  3. Idempotency keys for safe retries Worked example · 25 min
  4. Circuit breakers, bulkheads and load shedding Concept · 20 min
  5. Injecting latency and failures into a call chain Lab · 30 min
  6. Resilience check Knowledge check · 8 questions

What you will learn

  • Apply circuit breakers, bulkheads, load shedding and graceful degradation to contain failures.

01. Why it matters

Timeouts and retry budgets limit the damage of each call. They do not stop a caller from sending thousands of calls, each waiting its full timeout, to a dependency that has been broken for ten minutes, and they do nothing for a server whose callers ignore them. The patterns in this lesson work at a larger scale. A circuit breaker stops calling a dependency that keeps failing. A bulkhead caps how much of a caller's capacity one dependency can take. Load shedding lets a server refuse work it cannot finish in time. Graceful degradation decides what the user sees instead. In the map from lesson 1, these are the patterns that keep a failure inside the part of the system where it started.

02. Circuit breakers

A circuit breaker wraps the calls to one dependency and watches how they end. Michael Nygard's book Release It! and Martin Fowler's article made the idea popular. A breaker has three states:

  • Closed: calls go through, and the breaker records whether they succeed.
  • Open: once failures cross a threshold, calls fail at once, usually with a fallback answer, without touching the network. The caller keeps its workers, and the dependency gets a rest from traffic.
  • Half-open: after a wait, a few trial calls, or probes, go through. If they succeed the breaker closes; if they fail it opens again for another wait.

The details decide whether a breaker helps. Libraries such as Resilience4j count outcomes over a sliding window, either the last N calls or the last N seconds, and open when the failure rate, or the rate of slow calls, crosses a threshold. They also wait for a minimum number of calls before judging at all: without one, a single failure out of a single call is a 100% failure rate. Count only failures that say something about the dependency's health, such as timeouts, connection errors and 5xx responses, not a 404 or a validation error caused by the caller's own request. Scope the breaker to what fails together. One breaker for a service with ten hosts sees only the average: a single bad host, about 10% failures, may never trip it, and when it does trip it cuts off the healthy hosts too. Per-host breakers fit better there, or the load balancer's outlier ejection, which takes a host out of rotation for a while when its own error rate is high. And while a breaker is open, do not retry: a rejected call is not a reason to try again.

The breaker below counts over the last 10 calls, needs at least 5, opens at a 50% failure rate, stays open for 20 s and sends 2 probes when half-open. A fake clock makes one call per second to a dependency that fails from second 10 until second 45.

Python · breaker.py
"""A count-based circuit breaker, driven by a fake clock so the trace repeats."""
from collections import deque


class CircuitBreaker:
    def __init__(self, clock, window=10, min_calls=5, max_failure_rate=0.5,
                 open_seconds=20, probes=2):
        self.clock, self.min_calls = clock, min_calls
        self.max_failure_rate, self.open_seconds = max_failure_rate, open_seconds
        self.probes = probes
        self.recent = deque(maxlen=window)  # True = success, False = failure
        self.state, self.opened_at = "closed", 0.0
        self.probes_sent = self.probes_ok = 0

    def allow(self) -> bool:
        if self.state == "open":
            if self.clock.now - self.opened_at < self.open_seconds:
                return False                  # fail fast: do not call at all
            self._move("half-open")
            self.probes_sent = self.probes_ok = 0
        if self.state == "half-open":
            if self.probes_sent == self.probes:
                return False                  # probes already in flight
            self.probes_sent += 1
        return True

    def record(self, ok: bool) -> None:
        if self.state == "half-open":
            if not ok:
                return self._trip()           # still broken: open again
            self.probes_ok += 1
            if self.probes_ok == self.probes:
                self.recent.clear()
                self._move("closed")
            return
        self.recent.append(ok)
        failures = self.recent.count(False)
        if (len(self.recent) >= self.min_calls
                and failures / len(self.recent) >= self.max_failure_rate):
            self._trip()

    def _trip(self) -> None:
        self.opened_at = self.clock.now
        self._move("open")

    def _move(self, state: str) -> None:
        print(f"  t={self.clock.now:3.0f} s  {self.state} -> {state}")
        self.state = state


class Clock:
    now = 0.0


def dependency_ok(t: float) -> bool:
    return not 10 <= t < 45  # healthy, then down from t=10 s to t=45 s


clock = Clock()
breaker = CircuitBreaker(clock)
called = rejected = 0
for second in range(80):                     # one call per second
    clock.now = second
    if not breaker.allow():
        rejected += 1                        # served by a fallback, in microseconds
        continue
    called += 1
    breaker.record(dependency_ok(second))
print(f"calls sent to the dependency: {called}, rejected fast: {rejected}")
Terminal
python3 breaker.py
Expected output (fake clock, so it matches exactly)
  t= 14 s  closed -> open
  t= 34 s  open -> half-open
  t= 34 s  half-open -> open
  t= 54 s  open -> half-open
  t= 55 s  half-open -> closed
calls sent to the dependency: 42, rejected fast: 38

The breaker opens at second 14, when five of its last ten calls have failed. The probe at second 34 fails, so it opens again. The dependency recovers at second 45, but the next probes only go out at second 54, so for nine seconds users got the fallback from a healthy dependency. That is the trade-off in the open period: a long one sends fewer probes to a sick service, a short one recovers sooner. Over the run, 38 calls were answered at once instead of each waiting for a failure.

03. Bulkheads

A ship's bulkheads divide the hull into sealed compartments, so one leak floods one compartment. In software, a bulkhead gives each dependency, or each class of work, its own limited share of a resource: a separate thread pool, a separate connection pool, or a semaphore that caps concurrent calls. When the reviews service hangs, at most its share of workers waits on it, and checkout keeps the rest.

Size each compartment from expected concurrency, which is calls per second times normal latency, plus headroom (Little's law again). Too small, and it rejects traffic on a normal day; too large, and it no longer protects anything. When a compartment is full, reject at once or wait for a short, bounded time. The same idea works at larger scale: separate instance pools for critical and best-effort traffic, or cells that each serve a subset of customers.

The example puts a semaphore with two slots in front of a slow reviews call. Five product pages arrive together.

Python · bulkhead.py
"""A semaphore bulkhead: at most 2 calls to a slow dependency; the rest are rejected."""
import threading
import time

reviews_slots = threading.BoundedSemaphore(2)  # the bulkhead for one dependency
gate = threading.Barrier(5)                    # start five requests together
outcomes: list[str] = []


def product_page(i: int) -> None:
    gate.wait()
    if not reviews_slots.acquire(blocking=False):  # full: do not queue, reject now
        outcomes.append("page without reviews (bulkhead full, no wait)")
        return
    try:
        time.sleep(0.5)                            # the reviews service is slow
        outcomes.append("page with reviews (after the 500 ms call)")
    finally:
        reviews_slots.release()


threads = [threading.Thread(target=product_page, args=(i,)) for i in range(5)]
for t in threads:
    t.start()
for t in threads:
    t.join()
for outcome in sorted(set(outcomes)):
    print(f"{outcomes.count(outcome)} x {outcome}")
Terminal
python3 bulkhead.py
Expected output
2 x page with reviews (after the 500 ms call)
3 x page without reviews (bulkhead full, no wait)

Two pages wait for the slow call; for the other three the bulkhead is full, so they skip the call at once and render without reviews. Without the bulkhead all five would wait, and with enough traffic they would take every worker in the process.

04. Load shedding

Breakers and bulkheads live in the caller. Load shedding lives in the server, and it is the only one of these patterns that protects a service from callers it does not control. The goal is to keep goodput high when the offered load exceeds capacity: finish the requests you accept within their deadlines, and refuse the rest early and cheaply, before spending work on them. A server that accepts everything ends up answering nobody in time.

Useful signals for when to shed:

  • Concurrency: requests in progress, compared with a limit found by load testing. Some libraries adjust that limit as latency changes, which is called adaptive concurrency.
  • Queue time: how long a request waited before a worker took it. If it waited longer than its caller's timeout, drop it, because nobody is listening any more. A propagated deadline makes this exact.
  • CPU or memory pressure: easy to read but indirect. The right threshold depends on the service, so a figure such as 85% CPU is a starting point for testing, not a rule.

Refuse with 503 Service Unavailable or 429 Too Many Requests, with a Retry-After header when you can estimate one, and make the refusal far cheaper than the work. Shed by priority when requests differ in value: background prefetches before user clicks, and health checks never, or the load balancer removes a busy instance and pushes its load onto the others. Rate limiting is related but different: it enforces each client's fair share, while shedding protects the server's total capacity.

05. Graceful degradation and fallbacks

Graceful degradation means deciding in advance what users get when part of the system is unavailable, so the core of the product keeps working. Common fallbacks are a cached or slightly stale value, a static default such as popular items instead of personal ones, hiding an optional section, or a read-only mode.

Two rules keep fallbacks honest. First, decide per feature whether it fails open, carrying on without the missing part, or fails closed, refusing the request. Recommendations, avatars and recently viewed lists can fail open. Authorisation must fail closed, because carrying on without it gives away exactly what it protects. Fraud checks and spending limits usually fail closed too, or fail open only within a limit agreed in advance, such as small amounts from known customers. Second, a fallback must not depend on the thing that failed, and it must be cheaper than the normal path. A fallback that calls the same database, or that nobody has ever exercised, tends to fail at the worst moment, so test it, for example with the fault injection in the lab.

06. Check your understanding

Practice check · 3 questions

Containing a failing dependency

Three design situations for breakers and fallbacks.

Q1. A breaker opens when at least 50% of the calls in its window of the last 20 have failed, and it has no minimum number of calls. The calling service restarts at 03:00, when traffic is one call a minute, and its first call after the restart fails on a brief network blip. What happens?
Q2. A client keeps one circuit breaker for the whole inventory service, which runs on two hosts that the client balances between. Host 1 is healthy; host 2 fails every call, so half of all calls fail and the breaker opens at its 50% threshold. What is the effect?
Q3. A document API checks every read with a permissions service. That service is down, its breaker is open, and there is no cached decision for this user and document. Which fallback is the most defensible?
Practice only: not graded, not saved, not evidence.

07. Apply it

For the practice project, put a circuit breaker on the catalog's calls to the stock service, with a fallback that returns the product marked as degraded. Give the edge a bulkhead for its catalog calls. Then list every endpoint in your chain and decide, in writing, whether it fails open or fails closed, and why. In the lab, steps 7 and 9 show the bulkhead and the breaker separately, so you can see where each one stops the cascade.

08. Review prompt

Without looking back, describe the three states of a circuit breaker and what moves it between them. Explain why a breaker needs a minimum number of calls and a sensible scope. Then explain how a bulkhead differs from load shedding, which side of a call each one lives on, and how you decide whether a feature fails open or fails closed.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check