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

snippet
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};}