Back to results for “Error Handling”
Node.js › Architecture & Design Patterns

What is a Circuit Breaker pattern, and why is it important when a Node.js service calls an unreliable downstream dependency?

Advanced

Answer

A Circuit Breaker wraps calls to an external dependency and tracks recent failure rates -- when failures exceed a threshold, the breaker 'opens' and immediately rejects further calls (without even attempting them) for a cooldown period, preventing a struggling downstream service from being overwhelmed further and preventing the calling service from wasting resources on calls likely to fail or time out; after the cooldown, it allows a limited number of test requests through in a 'half-open' state to check if the dependency has recovered.
const CircuitBreaker = require('opossum');

const breaker = new CircuitBreaker(callExternalApi, {
  timeout: 3000,
  errorThresholdPercentage: 50,
  resetTimeout: 30000,
});

breaker.fallback(() => ({ cached: true, data: getCachedResponse() }));
breaker.fire(requestParams).then(handleResponse);
Real-world example A checkout service calling a flaky third-party shipping-rate API wraps that call in a circuit breaker with a fallback to a cached flat rate, so that when the shipping API starts timing out under its own load, the checkout flow degrades gracefully instead of piling up slow, doomed requests.

Common follow-ups: How do you choose appropriate threshold and cooldown values for a circuit breaker in a real system?;How does a circuit breaker interact with retry logic -- should they be used together or is that redundant?