In this lesson, you will learn how to prevent cascading system failures by using a circuit breaker to stop requests to an unresponsive database.
Why Circuit Breakers?
When your database struggles under load or goes offline, your Node.js application might keep trying to send queries. This consumes memory, holds onto event loop cycles, and creates a "thundering herd" effect that can crash your entire service. A Circuit Breaker acts like an electrical fuse: if the database fails too often, the breaker "trips," and the application immediately stops sending requests, returning an error or a cached response instead.
The Three States
A circuit breaker exists in one of three states:
- Closed: Normal operation. Requests flow to the database.
- Open: The database is failing. Requests are rejected immediately without reaching the database.
- Half-Open: After a timeout, the system allows a limited number of "test" requests to see if the database has recovered.
Conceptual Implementation
You can implement this using a library like opossum. Here is how it looks in practice:
const CircuitBreaker = require('opossum');
// Define the function that talks to your DB
const dbQuery = async (id) => await User.findById(id);
// Configure the breaker
const options = {
timeout: 3000, // If query takes > 3s, trigger failure
errorThresholdPercentage: 50, // Trip if 50% of requests fail
resetTimeout: 30000 // Wait 30s before trying again
};
const breaker = new CircuitBreaker(dbQuery, options);
// Usage
breaker.fire('user_123')
.then(console.log)
.catch((err) => console.error("Database unavailable, serving fallback!"));
By using this pattern, you stop the application from drowning in pending promises when the database is struggling. Once the resetTimeout passes, the breaker moves to the "Half-Open" state to verify if the database is healthy again. If it is, the circuit closes, and normal traffic resumes. This ensures your Node.js application remains resilient and responsive, even when your persistence layer is having a bad day.
Key Takeaway: A circuit breaker protects your Node.js event loop by "failing fast" when the database is unavailable, preventing the system from wasting resources on doomed operations.