In this lesson, you will learn how to use the Circuit Breaker pattern to protect your Node.js application from cascading failures when a downstream service goes down.
The Problem: Cascading Failures
When your application relies on an external microservice, a slow or unresponsive dependency can cause your own system to "hang" while waiting for timeouts. If many requests pile up, you exhaust your resources, leading to an application-wide crash. Much like a physical electrical circuit breaker that cuts power during a surge, this pattern stops the flow of requests to a failing service before it drags your entire system down.
How the Circuit Breaker Works
A Circuit Breaker acts as a gatekeeper between your service and a dependency. It exists in three states:
- Closed: Requests flow normally to the downstream service. The breaker monitors for errors.
- Open: If the failure rate exceeds a threshold, the breaker "trips." It immediately rejects all incoming calls to the service with a fallback response, preventing further strain on the failing dependency.
- Half-Open: After a cooldown period, the breaker allows a single test request to pass. If it succeeds, the breaker resets to "Closed." If it fails, it returns to "Open."
Basic Implementation Concept
You can implement this in your middleware stack to wrap external API calls:
let state = 'CLOSED';
let failureCount = 0;
async function requestWrapper(serviceCall) {
if (state === 'OPEN') {
return { error: 'Service temporarily unavailable (Circuit Open)' };
}
try {
const result = await serviceCall();
failureCount = 0; // Reset on success
return result;
} catch (err) {
failureCount++;
if (failureCount > 5) state = 'OPEN'; // Trip the breaker
throw err;
}
}
By failing fast, you save your own server's memory and CPU cycles that would otherwise be wasted waiting for a service that you already know is unhealthy. This allows your application to remain responsive for other requests while giving the downstream service time to recover.
Key Takeaway: The Circuit Breaker pattern protects system stability by failing fast and preventing requests from reaching a failing downstream service.