javascript / expert
Snippet
Orchestrating Graceful Service Shutdowns
Production Node.js services must handle signals like SIGTERM to close database connections and finish pending requests. This pattern centralizes cleanup logic and ensures all asynchronous teardown tasks are settled before exiting.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const cleanupHooks = [];const registerCleanup = (fn) => cleanupHooks.push(fn);const shutdown = async (signal) => {console.log(`Received ${signal}. Closing resources...`);const results = await Promise.allSettled(cleanupHooks.map(fn => fn()));results.forEach((res, i) => {if (res.status === 'rejected') console.error(`Hook ${i} failed:`, res.reason);});process.exit(0);};process.on('SIGTERM', () => shutdown('SIGTERM'));process.on('SIGINT', () => shutdown('SIGINT'));registerCleanup(async () => db.close());
nodejs
Breakdown
1
await Promise.allSettled(cleanupHooks.map(fn => fn()));
Executes all cleanup functions in parallel and waits for completion, even if some fail.
2
process.on('SIGTERM', ...)
Registers listeners for OS signals typically sent by container orchestrators like Kubernetes.