Backend Case Studies

Topic B15

Service dependencies and circuit breakers

When a dependency dies: timeouts, failing fast, and carefully trying again.

10 min · advanced

Watch: when the payment service is down, the first way keeps waiting for answers. The breaker stops asking for a while, then carefully tries again.

payments1order service2345678910
  • moving now
  • being checked
  • finished / the result
  • no longer used
Step 1 of 12

The order service calls the payment service for every order, with a 3-second timeout.

Waiting on a dead service uses up your own service's resources. A circuit breaker stops asking for a while, then carefully tries again.

Like an electrical fuse box

When there's a short circuit, the breaker in your fuse box cuts the power so the wiring in the whole house doesn't burn. You don't keep switching on the faulty appliance. Once it's fixed, you flip the breaker back. A software circuit breaker works the same way: cut off the broken part so the damage doesn't spread, then reconnect carefully.

Three states

  • Closed: calls go through. Failures are counted.
  • Open: after N failures (or a high failure rate), every call fails immediately without touching the dependency, for a cooldown period.
  • Half-open: after the cooldown, one trial call is let through. Success means closed again; failure means open again.
Code, for programmersA circuit breaker with opossum (Node.js)
import CircuitBreaker from "opossum";

const breaker = new CircuitBreaker(callPaymentService, {
  timeout: 3000,                 // a call slower than 3 s counts as a failure
  errorThresholdPercentage: 50,  // open when half the recent calls fail
  resetTimeout: 10_000,          // after 10 s, let one trial call through
});
breaker.fallback(() => ({ status: "pending", message: "Payment is delayed, we'll confirm by email" }));

app.post("/orders", async (req, res) => {
  const payment = await breaker.fire(req.body);   // fails fast while open
  res.json(payment);
});

Its companions

  • Timeouts: every outbound call needs a time limit. Many HTTP clients default to no limit, meaning they can wait forever.
  • Retries with backoff and jitter: retry brief failures, with longer and slightly random pauses. Retries without a breaker while a dependency is down only multiply the load.
  • Fallbacks: a sensible backup answer. Recommendations from an old cache, "payment is being processed", or hiding the feature that depends on that service.
  • Bulkheads: cap how many connections or threads one dependency may use, so a slow one can't take them all.

Quiz

  1. The payment service is down and there's no circuit breaker. Why can the order service go down too?

  2. What happens while the breaker is open?

  3. What is the half-open state for?

0 of 3 answered.