The circuit breaker pattern in system design interviews
A circuit breaker sits around calls to a dependency and stops making them once that dependency is clearly failing, so callers fail fast instead of waiting on timeouts and piling more load on a struggling service. It has three states: closed (calls pass and failures are counted), open (calls are rejected at once for a cool-down period) and half-open (a few trial calls decide whether to close again).
By Evin JohnPublished 7 min read
1. What a circuit breaker is
The name comes from the electrical device that cuts a circuit when current is dangerous. In software, the "current" is requests to a remote dependency: another service, a database, a payment provider. When that dependency starts timing out, every caller that keeps trying holds a thread or connection for the full timeout, retries, and adds load to a system that is already failing. The breaker notices the pattern and short-circuits: for a while, calls return an error or a fallback immediately, without touching the network. The pattern was popularised for service calls by Michael Nygard's book Release It!, and many service frameworks and service meshes offer an implementation.
2. Why interviewers ask about it
Any design with more than two services eventually meets the question "what happens when this dependency is slow?" A candidate who answers with timeouts, bounded retries and a breaker, and who can say what the user sees while it is open, shows they have thought about cascading failure. Interviewers also use it to probe for the common mistake of retrying everything at every layer.
3. How it works: the three states
| State | What happens to a call | Leaves the state when |
|---|---|---|
| Closed | The call goes through; its success or failure is recorded in a sliding window | The failure rate over the window passes a threshold (say 50% of the last 50 calls, with at least 20 calls) |
| Open | The call is rejected immediately with an error or a fallback | The cool-down (say 30 seconds) expires |
| Half-open | A small number of trial calls go through; others are rejected | All trial calls succeed (back to closed) or any one fails (back to open) |
Count timeouts and 5xx-style errors as failures. Do not count a caller's own mistakes, such as a 404 for a missing record or a validation error, or one bad client can open the breaker for everyone. Slow successes can count too: some breakers trip when too many calls exceed a latency threshold.
import time
from collections import deque
class CircuitOpen(Exception):
pass
class CircuitBreaker:
def __init__(self, failure_rate=0.5, min_calls=20, window=50,
open_seconds=30.0, probes=3, clock=time.monotonic):
self.failure_rate, self.min_calls = failure_rate, min_calls
self.results = deque(maxlen=window) # True = success, last N calls
self.open_seconds, self.probes, self.clock = open_seconds, probes, clock
self.state, self.opened_at, self.probe_ok, self.in_flight = "closed", 0.0, 0, 0
def call(self, fn, *args):
if self.state == "open":
if self.clock() - self.opened_at < self.open_seconds:
raise CircuitOpen() # fail fast, no remote call
self.state, self.probe_ok, self.in_flight = "half_open", 0, 0
if self.state == "half_open":
if self.in_flight >= self.probes:
raise CircuitOpen() # only a few trial calls at once
self.in_flight += 1
try:
result = fn(*args)
except Exception:
self._record(False)
raise
self._record(True)
return result
def _record(self, ok):
if self.state == "half_open":
self.in_flight -= 1
if not ok:
self._trip()
else:
self.probe_ok += 1
if self.probe_ok >= self.probes: # dependency looks healthy again
self.state = "closed"; self.results.clear()
return
self.results.append(ok)
failures = self.results.count(False)
if len(self.results) >= self.min_calls and failures / len(self.results) >= self.failure_rate:
self._trip()
def _trip(self):
self.state, self.opened_at = "open", self.clock()This version is single-threaded and treats every exception as a failure. A production breaker filters which errors count, uses locks or atomics for concurrent callers, and exports its state as a metric so an open breaker shows up on a dashboard.
4. The patterns that make it work
- Timeouts first. A breaker counts failures, and without a timeout a hung call never fails. Set each call's timeout from the dependency's normal latency (a little above its p99), and keep the whole request's deadline in mind: pass the remaining time downstream.
- Retries, bounded. Retry only idempotent calls, at most once or twice, with exponential backoff and random jitter. Retries at every layer multiply: three layers that each try four times can turn one user request into 4 x 4 x 4 = 64 calls at the bottom. Retry at one layer, or use a retry budget (say, retries may add at most 10% to traffic).
- Bulkheads. Give each dependency its own connection pool or concurrency limit. If the recommendations service hangs, it can exhaust only its own pool, and checkout calls to the payment service still have threads.
- Fallbacks. Decide what the user gets while the breaker is open: cached data, a default (no recommendations shown), a degraded mode, or a clear error. A fallback that calls another fragile service is not a fallback.
- Load shedding on the callee. The breaker protects callers; the struggling service should also protect itself by rejecting excess work early, for example with a rate limiter or a bounded queue.
5. Where to put it, and how many
| Where | How | Trade-off |
|---|---|---|
| In the calling code | A library wraps each client call | Fine-grained fallbacks per call; every service team must configure it |
| In a sidecar or service mesh | The proxy next to each service applies outlier detection and connection limits | Uniform and language-independent; fallbacks are limited to errors |
| At the API gateway | The gateway stops routing to a failing backend | Protects the edge; inner service-to-service calls still need their own |
Scope matters. One breaker per dependency is the usual default. If a dependency has many instances and only one is bad, a per-instance breaker (or the load balancer's outlier ejection) removes that instance without cutting off the healthy ones. A shared breaker would open for everyone because of one bad host.
6. Trade-offs
- Sensitivity. A low threshold or a short window opens the breaker on brief blips and causes needless errors; a high threshold reacts too late to protect anything.
- Cool-down length. Short cool-downs probe a sick service often; long ones keep a recovered service unused. Some implementations grow the cool-down after repeated failed probes.
- Synchronised recovery. If thousands of callers half-open at the same moment, their probes arrive as a burst. Jitter the cool-down per instance.
- Partial failure. A breaker sees the aggregate. When one shard of a dependency fails, a per-key or per-shard view can avoid blocking healthy keys.
7. How it shows up in common prompts
| Prompt | Dependency to guard | What the user sees while it is open |
|---|---|---|
| Payment system | External payment provider | Payment queued or a clear retry message; never a silent double charge |
| Notification system | Email or push provider | Messages wait in the queue and go out when the breaker closes |
| Proximity service | Detail cache or ratings service | Results with names but without ratings |
| Hotel reservation | Payment authorisation | Reservation stays pending briefly, then is released |
| Web crawler | A single slow website | That host is skipped for a while; others are crawled normally |
8. Interview questions on circuit breakers
| Question | A strong answer covers |
|---|---|
| What are the states of a circuit breaker? | Closed, open, half-open, and what moves it between them |
| How is a circuit breaker different from a retry? | Retries try again on the assumption the failure is brief; the breaker stops trying when it is not |
| What should count as a failure? | Timeouts and server errors, not client errors; optionally slow calls |
| What happens to requests while it is open? | A named fallback per call, or a fast, clear error |
| How do you stop retry storms? | One retry layer, backoff with jitter, retry budgets, idempotency for retried writes |
| Library or service mesh? | Mesh for uniform outlier ejection, library when fallbacks need business logic |
| How would you test it? | Fault injection in staging: add latency and errors to a dependency and watch the breaker and fallbacks |
9. Mistakes to avoid
- A breaker without timeouts. It never sees a failure if calls hang.
- Tripping on one error. Use a rate over a window with a minimum call count.
- Retrying everywhere. Each layer multiplies the load on the failing service.
- No fallback story. "It returns an error" is fine only if you say what the user then sees.
- One breaker for a whole cluster of instances when only one host is bad.
10. How to talk about it in the interview
Fictional example
- Interviewer
- Your product page calls a recommendations service. During a sale it starts taking ten seconds per call. What happens?
- Candidate
- Each call has a 300 ms timeout, so the page never waits ten seconds. Calls go through a separate pool for recommendations, so a backlog there cannot take threads from cart or pricing. Once more than half of the last fifty calls fail, the breaker opens and the page renders without recommendations for thirty seconds.
- Interviewer
- And then?
- Candidate
- It lets a couple of trial calls through. If they succeed it closes; if not it waits again. I would not retry these calls at all: a missing recommendations strip is a better outcome than doubling the load on a service that is already struggling.
Practicing with Natively
Resilience questions often arrive as a quick "and what if that service is slow?" near the end of a design round, which is easy to fumble when time is short. In a mock interview, Natively transcribes both sides and can suggest points such as bulkheads or retry budgets as the question comes in. Afterwards, the transcript shows whether you named the fallback or only the breaker.
Questions people ask
What is the circuit breaker pattern?
A wrapper around calls to a dependency that stops calling it when it is clearly failing. While closed it counts failures, when the failure rate passes a threshold it opens and rejects calls at once, and after a cool-down it lets a few trial calls through (half-open) to decide whether to close again.
What is the difference between a circuit breaker and a retry?
A retry assumes a failure is brief and tries again. A circuit breaker assumes repeated failures mean the dependency is unhealthy and stops trying for a while. They work together: bounded retries with backoff and jitter for brief blips, a breaker for sustained failure.
What is a half-open state?
After the open period ends, the breaker allows a small number of trial calls. If they succeed it closes and normal traffic resumes; if any fails it opens again for another cool-down.
What is a bulkhead in microservices?
A separate pool of threads or connections, or a concurrency limit, for each dependency. If one dependency hangs it can only exhaust its own pool, so calls to healthy dependencies keep working.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
