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?
AdvancedAnswer
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.