DEV Community

Young Gao
Young Gao

Posted on

Implementing the Circuit Breaker Pattern in TypeScript (2026 Guide)

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";
  }
}
Enter fullscreen mode Exit fullscreen mode

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" }); }
});
Enter fullscreen mode Exit fullscreen mode

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:


You Might Also Like

Follow me for more production-ready backend content!


If this helped you, buy me a coffee on Ko-fi!

Top comments (0)