Your payment service is down. Every request to it times out after 30 seconds. 100 requests per second means 3000 threads waiting on a dead service. Your entire system cascades.
Three States
Closed = normal, requests pass. Open = failing, reject immediately. Half-Open = testing recovery with one probe.
Implementation
type State = "closed" | "open" | "half-open";
class CircuitBreaker {
private state: State = "closed";
private failures = 0;
private lastFailure = 0;
constructor(private threshold = 5, private timeout = 60000) {}
async call(fn) {
if (this.state === "open") {
if (Date.now() - this.lastFailure > this.timeout) this.state = "half-open";
else throw new Error("Circuit is OPEN");
}
try {
const result = await fn();
this.reset();
return result;
} catch (err) { this.recordFailure(); throw err; }
}
private reset() { this.state = "closed"; this.failures = 0; }
private recordFailure() { this.failures++; this.lastFailure = Date.now();
if (this.failures >= this.threshold) this.state = "open";
}
}
Usage
const paymentBreaker = new CircuitBreaker(5, 60000);
app.post("/charge", async (req, res) => {
try {
const result = await paymentBreaker.call(() => stripe.charges.create(req.body));
res.json(result);
} catch (err) { res.status(503).json({ error: "Service unavailable" }); }
});
When to Trip the Circuit
Trip on: timeouts, 5xx responses, connection refused. Do NOT trip on: 4xx responses (client errors), validation failures.
Monitoring
Log every state transition. Alert on open circuits. Track: failure rate, trip count, recovery time.
Part of my Production Backend Patterns series. Follow for more practical backend engineering.
If this was useful, consider:
- Sponsoring on GitHub to support more open-source tools
- Buying me a coffee on Ko-fi
You Might Also Like
- Feature Flags from Scratch: Build a Runtime Toggle System in TypeScript (2026)
- Graceful Degradation Patterns: Keep Your Backend Running When Dependencies Fail (2026)
- Request Validation at the Edge: Zod Schemas, OpenAPI, and Type-Safe APIs (2026)
Follow me for more production-ready backend content!
If this helped you, buy me a coffee on Ko-fi!
Top comments (0)