Course contentsShow
← Node.js
Lesson 875 of 1,9808. Data Persistence and ORM IntegrationFree lesson

Circuit Breaker Implementation for Persistence

You will prevent application hangs when the persistence layer enters an error state.

Circuit Breaker Implementation for Persistence

In this lesson, you will learn how to prevent your Node.js application from hanging indefinitely when your database becomes unresponsive.

The Problem: Cascading Failure

When your persistence layer (like a MongoDB or Redis instance) starts failing or experiences high latency, your Node.js application might keep trying to send queries. These pending requests accumulate, consume memory, and hold open connections, eventually causing your entire service to crash. This is known as a cascading failure.

The Solution: The Circuit Breaker

A Circuit Breaker acts like an electrical fuse for your database calls. It monitors the health of your database operations and wraps them in a state machine:

  1. Closed: The circuit is healthy. Requests are sent to the database normally.
  2. Open: The database has encountered too many errors. The circuit "trips," and all requests are immediately rejected before they even hit the database.
  3. Half-Open: After a cool-down period, the breaker allows a few "test" requests through to see if the database is healthy again.

Implementation Example

Using a simple approach, you can track failures in your repository layer:

let failureCount = 0;
let circuitOpen = false;

async function saveDocument(data) {
  if (circuitOpen) {
    throw new Error("Circuit is OPEN: Database currently unreachable");
  }

  try {
    const result = await db.collection.insertOne(data);
    failureCount = 0; // Reset on success
    return result;
  } catch (err) {
    failureCount++;
    if (failureCount > 5) {
      circuitOpen = true; // Trip the circuit
      setTimeout(() => { circuitOpen = false; }, 30000); // Wait 30s
    }
    throw err;
  }
}

By failing fast, you protect your application’s memory and CPU resources. Instead of waiting for a network timeout (which can take 30+ seconds), the application returns a clear error immediately, allowing you to provide a graceful fallback response to the user or triggering an alert for the operational team to investigate the database state.

Key Takeaway: A Circuit Breaker protects your application from resource exhaustion by "failing fast" whenever the persistence layer demonstrates a sustained period of instability.