Good Code
The good version stops accepting new HTTP work, closes dependencies, and keeps a timeout in case shutdown hangs.
Lesson 08
Stop accepting work and close resources when the process receives shutdown signals.
import type { Server } from "node:http";
export function installShutdown(server: Server, closeDatabase: () => Promise<void>) {
async function shutdown(signal: string) {
console.info("Received " + signal + ", shutting down");
server.close(async () => {
await closeDatabase();
process.exit(0);
});
setTimeout(() => {
console.error("Shutdown timed out");
process.exit(1);
}, 10_000).unref();
}
process.once("SIGTERM", () => shutdown("SIGTERM"));
process.once("SIGINT", () => shutdown("SIGINT"));
}process.on("SIGTERM", () => {
process.exit(0);
});
process.on("SIGINT", () => {
process.exit(0);
});The good version stops accepting new HTTP work, closes dependencies, and keeps a timeout in case shutdown hangs.
The bad version exits immediately, which can drop in-flight requests and leave external work half-complete.