Interview frequency: …
Short answer
It monitors failures when connecting to external services; if errors exceed a threshold, it opens the circuit and fails requests immediately without sending them, preserving server resources.
Explanation
If an external service such as a payment service goes down, hundreds of requests waiting for timeouts can exhaust your application's connections and memory and bring it down. The Circuit Breaker pattern (using libraries such as opossum) has three states: Closed (normal), Open (fails immediately or returns a Fallback without connecting), and Half-Open (tests recovery with a small number of trial requests).
Code example
import CircuitBreaker from "opossum";
const breaker = new CircuitBreaker(callExternalApi, { timeout: 3000, errorThresholdPercentage: 50 });
breaker.fallback(() => ({ status: "cached_fallback" }));
const result = await breaker.fire();Common mistakes
- Not providing a clear fallback response when the circuit opens.