DEV Community

Saurav Pandey
Saurav Pandey

Posted on

Don't Let One Broken Service Crash Your Whole App: The Circuit Breaker Pattern

What is the Circuit Breaker Pattern?

The Circuit Breaker Pattern is an architectural design pattern used in software development to detect failures and encapsulate the logic of preventing a failure from cascading throughout a system. It works by wrapping a sensitive network call or database query in a monitoring object that tracks recent failures. When those failures exceed a pre-defined threshold, the breaker trips, automatically blocking subsequent requests to prevent further damage. This prevents a system from repeatedly executing an operation that is almost guaranteed to fail, protecting both the client and the struggling service.

A Real-Life Analogy: The Household Fuse Box

Imagine you are in your kitchen on a weekend morning. You decide to toast some bread, but your toaster has an internal short circuit. When you push down the lever, instead of just warming up, the faulty appliance starts drawing an unsafe, massive surge of electricity. Without a safety device in place, the copper wiring in your kitchen walls would quickly overheat, melt its protective insulation, and potentially start a devastating house fire.

Fortunately, your home features an electrical circuit breaker panel. The breaker detects this dangerous spike in electrical current and instantly trips, cutting off the flow of electricity to the kitchen outlets. The toaster is dead, but your home is completely safe because the danger was isolated. To fix things, you unplug the toaster, run to the garage, and flip the breaker switch back to its original position to restore power to the remaining kitchen appliances.

Why It Matters in Daily Tech Operations

In modern software, apps are rarely self-contained. They rely on microservices—smaller, interconnected applications—and external APIs (Application Programming Interfaces) to run. For instance, an e-commerce platform relies on a product catalog service, a payment gateway, and an email service.

If the payment gateway slows down or crashes during a sale, what happens? Without a circuit breaker, every customer trying to checkout will wait indefinitely. Each waiting user consumes system resources, such as memory and web threads, on your server. As more users click checkout, these resources quickly exhaust. Within minutes, your core checkout service crashes under the pressure, which then causes the inventory service to crash, leading to a complete system outage.

By implementing the Circuit Breaker Pattern, engineers can safeguard their systems. Once the circuit breaker detects that the payment gateway is failing, it immediately trips. New checkout requests instantly receive a friendly message like, "Our payment gateway is busy, please try again in a moment." This spares your servers from waiting on a dead service, allowing the rest of your website to remain online and functional.

The Concept in Action

Here is a simple, lightweight implementation of a circuit breaker in JavaScript to show how this logic looks under the hood:

class SimpleCircuitBreaker {
  constructor(requestFunction, failureThreshold = 3, cooldownMs = 10000) {
    this.requestFunction = requestFunction;
    this.failureThreshold = failureThreshold;
    this.cooldownMs = cooldownMs;
    this.state = "CLOSED";
    this.failures = 0;
    this.nextAttemptTime = 0;
  }

  async execute() {
    if (this.state === "OPEN") {
      if (Date.now() > this.nextAttemptTime) {
        this.state = "HALF-OPEN";
      } else {
        throw new Error("Circuit is OPEN. Request blocked for safety.");
      }
    }

    try {
      const result = await this.requestFunction();
      this.reset();
      return result;
    } catch (error) {
      this.handleFailure();
      throw error;
    }
  }

  reset() {
    this.state = "CLOSED";
    this.failures = 0;
  }

  handleFailure() {
    this.failures++;
    if (this.failures >= this.failureThreshold) {
      this.state = "OPEN";
      this.nextAttemptTime = Date.now() + this.cooldownMs;
      console.log("Circuit breaker tripped! Blocking future requests.");
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

The Takeaway

Building highly reliable modern software systems is not about pretending that failures will never occur; it is about managing those failures gracefully when they inevitably do. The Circuit Breaker Pattern shifts our architectural strategy from fragile, hopeful connections to defensive, self-healing resilience. By failing fast, your application protects its precious memory and computing power, preventing localized outages from snowballing into catastrophic system-wide downtime.


Resources


Originally published on my blog. You can read the alternative breakdown here.

Top comments (0)