Architecture
The Circuit Breaker Pattern: Stop One Failing Service From Taking Down the Rest
By NileVPS Team · Published · 4 min read
اقرأ المقال بالعربيWhen your application calls another service, such as a payment provider, an internal API or a database replica, that service will eventually slow down or fail. The dangerous part is not the failure itself but what your app does next. If every request keeps waiting on a dead dependency until it times out, threads and connections pile up, memory grows and your own service stops answering. One sick component becomes a full outage. The circuit breaker pattern prevents this by noticing repeated failures and failing fast for a while, giving the dependency room to recover and keeping your app responsive.
The idea behind the name
An electrical circuit breaker cuts power when current is dangerous, protecting the wiring. A software circuit breaker wraps calls to a remote dependency and cuts them off when the error rate is dangerous, protecting your own resources. Instead of waiting 30 seconds for a timeout, a call through an open breaker returns an error in microseconds, and your code can show a fallback.
The three states
Closed
Normal operation. Calls pass through, and the breaker counts results. If failures within a window cross a threshold (for example, at least 20 calls and 50 percent failed in the last 10 seconds), the breaker trips to open.
Open
All calls fail immediately without touching the dependency. The breaker stays open for a cool-down period, such as 30 seconds. Nothing is sent to the struggling service, which removes load from it exactly when it needs it.
Half-open
After the cool-down, the breaker allows a small number of trial calls. If they succeed, the breaker closes and traffic resumes. If any fail, it opens again and the cool-down restarts.
| State | Calls reach dependency | Moves to |
|---|---|---|
| Closed | Yes, all | Open when failure threshold is crossed |
| Open | No, fail fast | Half-open after cool-down |
| Half-open | A few trial calls | Closed on success, Open on failure |
What counts as a failure
Decide deliberately. Usually:
- Timeouts and connection errors count.
- HTTP 5xx responses count.
- HTTP 4xx responses usually do not, because they indicate a bad request rather than a sick service. Counting them lets one buggy client trip the breaker for everyone.
- Very slow successful calls can count as "slow call" failures in libraries that support it.
A minimal implementation
The logic fits in a few dozen lines. Here is a simplified Python version to show the mechanics:
import time
class CircuitBreaker:
def __init__(self, threshold=5, cooldown=30):
self.threshold = threshold
self.cooldown = cooldown
self.failures = 0
self.opened_at = None
def call(self, fn, *args, **kwargs):
if self.opened_at is not None:
if time.monotonic() - self.opened_at < self.cooldown:
raise RuntimeError("circuit open")
# cool-down over: half-open, allow one trial
try:
result = fn(*args, **kwargs)
except Exception:
self.failures += 1
if self.opened_at is not None or self.failures >= self.threshold:
self.opened_at = time.monotonic()
raise
self.failures = 0
self.opened_at = None
return resultThis counts consecutive failures, which is the simplest strategy. Production libraries use sliding windows, track rates instead of counts, limit concurrent half-open trials and are thread-safe. Prefer a maintained library: Resilience4j for Java, Polly for .NET, opossum for Node.js, pybreaker for Python, or gobreaker for Go.
Fallbacks: what to do when the circuit is open
Failing fast is only half the value. Decide what the user sees:
- Serve cached or stale data (last known exchange rates, a cached product list).
- Degrade a feature (hide recommendations, keep checkout working).
- Queue the work for later, for example sending an email once the mail service is back. See queue systems.
- Return a clear error quickly, which is still better than a hanging page.
Circuit breaking at the proxy level
You do not always need application code. Nginx has a passive version for upstreams:
upstream api_backend {
server 10.0.0.11:8080 max_fails=3 fail_timeout=30s;
server 10.0.0.12:8080 max_fails=3 fail_timeout=30s;
}
location /api/ {
proxy_pass http://api_backend;
proxy_connect_timeout 2s;
proxy_read_timeout 10s;
proxy_next_upstream error timeout http_502 http_503;
}After three failures within 30 seconds, nginx stops sending requests to that server for 30 seconds, then tries again. HAProxy offers active health checks and observe layer7 with on-error mark-down, and service meshes such as Envoy provide outlier detection with similar behavior. Proxy-level breaking protects whole backends; library-level breaking protects individual calls inside your code. Many systems use both. Our article on load balancers explains the surrounding setup.
Tuning checklist
- Set timeouts first. A breaker without a sensible timeout still lets requests hang until the threshold trips.
- Require a minimum number of calls before evaluating the rate, so two failures at 3 a.m. do not trip it.
- Choose a cool-down long enough for typical recovery, often 10 to 60 seconds.
- Use one breaker per dependency (and sometimes per endpoint), never one global breaker.
- Combine with retries carefully: retry a couple of times with backoff inside the closed state, never retry against an open breaker.
- Log every state change and expose it as a metric, so an open breaker raises an alert.
FAQ
Is a circuit breaker the same as a retry?
No. Retries try again in the hope of success; a circuit breaker stops trying when failure is likely. They complement each other: retries handle brief glitches, and the breaker prevents retries from hammering a dependency that is clearly down.
Where should the breaker live in a microservice setup?
On the caller's side, around each outgoing call to a dependency. Each client protects itself. A service mesh or API gateway can provide this centrally, but the decision about fallbacks still belongs to the calling service.
Can a circuit breaker hide real problems?
It can if nobody watches it. Treat an open breaker as an incident signal: emit metrics, alert on state changes and review how often each breaker opens.