In this lesson, you will learn how to build a circuit-breaker toggle that forces your application into a read-only "Cache-Only Mode" when your primary database becomes unreachable.
The Concept of Cache-Only Mode
When your database suffers an outage or severe latency spikes, standard error handling might leave users staring at blank screens. Graceful degradation allows your Node.js service to detect this instability and immediately switch to serving stale or pre-cached data. By entering "Cache-Only Mode," you trade data freshness for system availability, ensuring that users can still browse or perform read operations while the database recovers.
Implementing the Toggle
To implement this, we use a central flag—often stored in a high-availability key-value store like Redis—that dictates the application state. When your database connection fails, you flip this flag to true.
async function getProductData(productId) {
// Check our degradation state first
const isCacheOnlyMode = await redis.get('system:cache_only_mode');
if (isCacheOnlyMode === 'true') {
return await redis.get(`product:${productId}`); // Serve stale data from cache
}
try {
const data = await db.products.findOne({ id: productId });
await redis.set(`product:${productId}`, JSON.stringify(data)); // Refresh cache
return data;
} catch (error) {
// Trigger the circuit breaker if DB is down
await redis.set('system:cache_only_mode', 'true', 'EX', 60);
return await redis.get(`product:${productId}`);
}
}
Why this works
By checking the cache_only_mode flag, you avoid the overhead of attempting to connect to a dead database, which prevents request timeouts and cascading failures. The EX (expiration) parameter on the flag is crucial here; it acts as a self-healing mechanism, automatically testing if the database is back online after 60 seconds. If the next request succeeds, you can programmatically toggle the flag back to false. This approach keeps your application responsive and prevents the "thundering herd" effect where every request tries to reconnect to a struggling database simultaneously.
Key Takeaway: Graceful degradation via cache-only mode preserves system availability during outages by prioritizing stale, cached responses over expensive, failing database operations.