
Graceful Shutdown in Node.js: Stop Losing Requests During Deploys
Graceful Shutdown in Node.js: Stop Losing Requests During Deploys Your deploy kills in-flight requests. Users get 502s. Database transactions hang open. The Problem SIGTERM arrives. process.exit() runs. Active connections drop. Users see errors. The Fix import http from " http " ; import { Pool } from " pg " ; const pool = new Pool (); const app = express (); const server = http . createServer ( app ); let isShuttingDown = false ; app . use (( req , res , next ) => { if ( isShuttingDown ) return res . status ( 503 ). json ({ error : " Shutting down " }); next (); }); async function shutdown ( signal : string ) { console . log ( `Received ${ signal } . Starting graceful shutdown...` ); isShuttingDown = true ; server . close (() => console . log ( " HTTP server closed " )); await pool . end (); process . exit ( 0 ); } process . on ( " SIGTERM " , () => shutdown ( " SIGTERM " )); process . on ( " SIGINT " , () => shutdown ( " SIGINT " )); setTimeout (() => { console . error ( " Forced shu
Continue reading on Dev.to DevOps
Opens in a new tab



