Full answer
A real service holds many resources: an HTTP server, message queue consumers, scheduled jobs, a database pool, a cache connection, open files. Closing them in a careless order causes errors, for example closing the database while requests still use it.
Rules for the order: stop accepting new work first (fail the readiness check, close the listener), then wait for in-flight work, then stop background workers, and last close the shared backends. Registering resources as they start and closing in reverse order gives this naturally, because dependencies start before the things that depend on them.
Features of a good manager:
- Idempotent: the second signal (for example an impatient Ctrl+C) does not start a second shutdown. A repeated signal may force exit.
- Per-step timeout: a stuck close function must not block the others. Log it and continue.
- Overall deadline shorter than the platform grace period (Kubernetes default is 30 seconds). When it expires, exit with a non-zero code.
- Error collection: one failing close function does not stop the rest. Report all failures at the end.
- Logging: each step logs start, end and duration, so a slow shutdown can be diagnosed.
- Exit code: 0 for a clean shutdown, 1 when anything failed or timed out. Use process.exitCode and let the loop end if possible.
- Testability: the manager takes a list and a timer function, and does not call process.exit itself, so tests can run it.
This pattern replaces scattered process.on('SIGTERM') handlers across the code base with one place that owns the order.
class ShutdownManager {
#steps = [];
#running = null;
register(name, close, { timeoutMs = 1000 } = {}) {
this.#steps.push({ name, close, timeoutMs });
}
shutdown(reason) {
if (this.#running) return this.#running; // second signal: same promise, no second run
this.#running = this.#run(reason);
return this.#running;
}
async #run(reason) {
const report = { reason, closed: [], failed: [] };
for (const step of [...this.#steps].reverse()) { // reverse order of creation
let timer;
try {
await Promise.race([
step.close(),
new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('timeout after ' + step.timeoutMs + ' ms')), step.timeoutMs); }),
]);
report.closed.push(step.name);
} catch (err) {
report.failed.push(`${step.name}: ${err.message}`); // keep going with the next step
} finally {
clearTimeout(timer);
}
}
report.exitCode = report.failed.length === 0 ? 0 : 1;
return report;
}
}
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const order = [];
const manager = new ShutdownManager();
// Registered in start-up order.
manager.register('database pool', async () => { await wait(5); order.push('database pool closed'); });
manager.register('queue consumer', async () => { await wait(5); order.push('queue consumer stopped'); });
manager.register('stuck cache client', () => new Promise(() => {}), { timeoutMs: 30 }); // never finishes
manager.register('http server', async () => { await wait(5); order.push('http server closed'); });
async function main() {
// Two signals arrive almost together. Only one shutdown runs.
const first = manager.shutdown('SIGTERM');
const second = manager.shutdown('SIGINT');
console.log('same shutdown for both signals:', first === second);
const report = await first;
console.log('closing order:', order.join(' > '));
console.log('closed:', report.closed);
console.log('failed:', report.failed);
console.log('exit code to use:', report.exitCode);
// In a real service: process.exitCode = report.exitCode;
}
main();The cache client never finishes closing, so it times out after 30 ms and the manager continues with the remaining steps. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): same shutdown for both signals: true closing order: http server closed > queue consumer stopped > database pool closed closed: [ 'http server', 'queue consumer', 'database pool' ] failed: [ 'stuck cache client: timeout after 30 ms' ] exit code to use: 1
Key points
- Register resources as they start and close in reverse.
- Make shutdown idempotent.
- Per-step timeouts and an overall deadline.
- Collect errors and choose the exit code.
- Let tests run the manager without exiting.
Common mistakes
- Closing the database before the HTTP server has finished its requests.
- Running the shutdown twice when two signals arrive.
- Letting one failing close function stop the whole sequence.
- Using a deadline longer than the platform grace period.
Follow-ups
- How would you test this manager without sending real signals?
- How does Kubernetes use preStop hooks and readiness probes here?
- What should happen to jobs that are half done?
Tips
- Describe the order rule: stop traffic first, shared backends last.
- Say 'idempotent' and 'timeouts' within the first two sentences.
- Mention the exit code to report health of the shutdown.