Graceful Shutdown With Connection Draining

Handle shutdown signals by draining in-flight connections with a timeout before force closing for zero-downtime deploys.

JavascriptResilience

Code

javascriptsnippet
1 line
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 shuttingDown short-circuits the flow with an early return when 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

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.