Free 40-page Claude guide — setup, 120 prompt codes, MCP servers, AI agents. Download free →
CLSkills
Backendintermediate

Graceful Shutdown

Share

Implement graceful server shutdown handling

Works with OpenClaude

You are a backend engineer implementing production-ready server shutdown handling. The user wants to implement graceful shutdown that allows in-flight requests to complete, cleans up resources, and exits cleanly.

What to check first

  • Verify your server framework (Express, Fastify, etc.) and Node.js version with node --version
  • Check if you're using a process manager (PM2, systemd, Docker) that will send SIGTERM/SIGINT signals
  • Confirm all database connections, cache clients, and external service connections are initialized before shutdown

Steps

  1. Set up signal handlers for SIGTERM and SIGINT to catch shutdown requests from the OS or container orchestrator
  2. Implement a flag to stop accepting new connections while allowing existing ones to finish
  3. Add middleware to track active requests and their completion status
  4. Call server.close() to stop accepting new connections without terminating existing ones
  5. Set a maximum timeout (typically 30 seconds) to force shutdown if graceful shutdown takes too long
  6. Close database connections, Redis clients, and other resource pools with their respective close methods
  7. Log shutdown events with timestamps to track when the process initiated and completed shutdown
  8. Exit the process with code 0 (success) after cleanup or code 1 if timeout is exceeded

Code

import express from 'express';
import http from 'http';

const app = express();
const server = http.createServer(app);

let isShuttingDown = false;
const activeRequests = new Set();

// Middleware to track active requests
app.use((req, res, next) => {
  if (isShuttingDown) {
    res.setHeader('Connection', 'close');
  }

  activeRequests.add(req);

  res.on('finish', () => {
    activeRequests.delete(req);
  });

  res.on('close', () => {
    activeRequests.delete(req);
  });

  next();
});

// Example route
app.get('/health', (req, res) => {
  res.json({ status: 'ok' });
});

const SHUTDOWN_TIMEOUT = 30000; // 30 seconds

function gracefulShutdown(signal) {
  console.log(`\n${signal} received. Starting graceful shutdown...`);
  isShuttingDown = true;

  server.close(() => {
    console.log('HTTP server closed');
    process.exit(0);
  });

  // Force shutdown after timeout
  setTimeout(() => {
    console.error(
      `Graceful shutdown timeout. Forcing exit. Active requests: ${activeRequests.size}`
    );
    process.exit(1);
  }, SHUTDOWN_TIMEOUT);

  // Notify existing connections they should finish up
  activeRequests.forEach((req) => {
    if (!req.socket.destroyed) {
      req.socket.end();
    }
  });
}

process.on('SIG

Note: this example was truncated in the source. See the GitHub repo for the latest full version.

Common Pitfalls

  • Treating this skill as a one-shot solution — most workflows need iteration and verification
  • Skipping the verification steps — you don't know it worked until you measure
  • Applying this skill without understanding the underlying problem — read the related docs first

When NOT to Use This Skill

  • When a simpler manual approach would take less than 10 minutes
  • On critical production systems without testing in staging first
  • When you don't have permission or authorization to make these changes

How to Verify It Worked

  • Run the verification steps documented above
  • Compare the output against your expected baseline
  • Check logs for any warnings or errors — silent failures are the worst kind

Production Considerations

  • Test in staging before deploying to production
  • Have a rollback plan — every change should be reversible
  • Monitor the affected systems for at least 24 hours after the change

Quick Info

CategoryBackend
Difficultyintermediate
Version1.0.0
AuthorClaude Skills Hub
backendshutdownreliability

Install command:

curl -o ~/.claude/skills/graceful-shutdown.md https://claude-skills-hub.vercel.app/skills/backend/graceful-shutdown.md

Related Backend Skills

Other Claude Code skills in the same category — free to download.

Want a Backend skill personalized to YOUR project?

This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.