Node.js › Background Jobs & Queues
How do you implement graceful shutdown for a Node.js background worker process to avoid losing or corrupting in-progress jobs?
AdvancedAnswer
Graceful shutdown means the worker stops accepting new jobs immediately upon receiving a termination signal (SIGTERM), but is given a grace period to finish any job(s) currently in progress before the process actually exits -- without this, a deployment or auto-scaling event that abruptly kills a worker mid-job can leave data half-written, or (depending on the queue's acknowledgment model) cause the job to be silently lost or retried in a corrupted, partially-completed state.
process.on('SIGTERM', async () => {
console.log('Received SIGTERM, closing worker gracefully...');
await worker.close(); // BullMQ waits for in-progress jobs to finish before resolving
await connection.quit();
process.exit(0);
});Real-world example A Kubernetes deployment sends SIGTERM to worker pods during a rolling update; because the worker's SIGTERM handler waits for BullMQ's worker.close() to resolve (letting in-flight jobs complete) before actually exiting, no in-progress image-processing job is ever interrupted mid-write during routine deployments.