Implement graceful server shutdown handling
✓Works with OpenClaudeYou 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
- Set up signal handlers for
SIGTERMandSIGINTto catch shutdown requests from the OS or container orchestrator - Implement a flag to stop accepting new connections while allowing existing ones to finish
- Add middleware to track active requests and their completion status
- Call
server.close()to stop accepting new connections without terminating existing ones - Set a maximum timeout (typically 30 seconds) to force shutdown if graceful shutdown takes too long
- Close database connections, Redis clients, and other resource pools with their respective close methods
- Log shutdown events with timestamps to track when the process initiated and completed shutdown
- 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
Related Backend Skills
Other Claude Code skills in the same category — free to download.
Express Setup
Scaffold Express.js app with best practices
Fastify Setup
Scaffold Fastify app with plugins
NestJS Module
Generate NestJS modules, controllers, services
Middleware Chain
Create and organize middleware chain
Queue Worker
Set up job queue with Bull/BullMQ
File Upload Handler
Create file upload handling with validation
Email Service
Set up transactional email service
WebSocket Setup
Implement WebSocket server with rooms
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.