Graceful Shutdown With Connection Draining
Handle shutdown signals by draining in-flight connections with a timeout before force closing for zero-downtime deploys.
Code
export function gracefulShutdown(server,{timeout=10000,onShutdown=async()=>{}}={}){let shuttingDown=false;async function shutdown(signal){if(shuttingDown)return;shuttingDown=true;console.log('received '+signal+', draining...');server.close();const forceTimer=setTimeout(()=>{console.error('force shutdown after timeout');process.exit(1);},timeout);try{await onShutdown();clearTimeout(forceTimer);process.exit(0);}catch(e){console.error('shutdown error',e);process.exit(1);}}process.on('SIGTERM',()=>shutdown('SIGTERM'));process.on('SIGINT',()=>shutdown('SIGINT'));return{isShuttingDown:()=>shuttingDown};}How it works
Graceful Shutdown With Connection Draining keeps everything in the functions gracefulShutdown and shutdown.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
What to watch for
- The guard
shuttingDownshort-circuits the flow with an earlyreturnwhen its condition holds.
Using it
The main signature reads export function gracefulShutdown(server,{timeout=10000,onShutdown=async()
Output lines are prefixed (received, force shutdown after timeout, shutdown error), making each step’s effect easy to spot.
Callers only need gracefulShutdown — everything else stays internal.
Interactive Tools for This Topic
DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- Does this work in a bare project with no dependencies file?
- Yes — a bare project runs it as-is, since nothing needs declaring. The file defines `gracefulShutdown`, `shutdown` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.