Course contentsShow
← Node.js
Lesson 1483 of 1,98013. Error Handling and Resilient SystemsFree lesson

Handling Disk Full Scenarios

You will monitor disk usage to prevent application crashes when logging or temporary file storage runs out of space.

In this lesson, you will learn how to proactively monitor disk usage to prevent your Node.js application from crashing when it runs out of storage space.

When your application writes logs or handles temporary file uploads, a Disk Full error (often represented by the ENOSPC system error code) can bring your entire process to a screeching halt. Relying solely on try-catch blocks around file writes is often too late, as the damage—corrupted files or failed log entries—is already done.

Proactive Monitoring

Instead of waiting for an error, you should treat disk space as a finite resource, similar to memory. By utilizing the node:fs module in combination with node:child_process, you can periodically check the disk usage of your storage partition. If usage crosses a safety threshold (e.g., 90%), your application can trigger a "graceful degradation" mode: stop accepting new file uploads, switch logs to a memory buffer, or alert your SRE team.

Here is a simplified pattern to check disk usage:

const { exec } = require('child_process');

function checkDiskSpace(threshold = 90) {
  return new Promise((resolve, reject) => {
    // Standard Unix command to check partition usage
    exec('df -h / | tail -1', (err, stdout) => {
      if (err) return reject(err);
      
      const usage = parseInt(stdout.split(/\s+/)[4]);
      if (usage > threshold) {
        // Trigger protective logic here
        console.warn(`Warning: Disk usage at ${usage}%`);
      }
      resolve(usage);
    });
  });
}

Defensive Strategies

Once you detect a high-usage state, implement these resilience patterns:

  1. Stop writing to local disk: Immediately disable non-essential logs or log to an immutable sink (like a remote cloud logging service) instead.
  2. Reject requests early: If your service handles file uploads, return a 507 Insufficient Storage status code to indicate the server cannot process the current request.
  3. Cleanup routines: Trigger a background process to purge temporary files or older log archives before they cause a critical failure.

By implementing this check as a background heartbeat task, you ensure that your application remains a good citizen of the host environment, protecting it from sudden, unrecoverable crashes.

Key Takeaway: Proactively monitor disk thresholds with heartbeat checks and switch to a "degraded mode" before ENOSPC errors occur to maintain service availability.