Graceful shutdown involves calling worker.disconnect() to stop accepting new connections, waiting for existing requests to finish, and then killing the process if needed. This prevents abrupt connection drops for active clients.
A graceful shutdown is important in production to avoid dropping in-flight requests. Instead of immediately killing a worker with worker.kill(), you first disconnect it so it stops accepting new connections, let it finish processing ongoing requests, and optionally force-kill it if it takes too long using a timeout.
Call worker.disconnect() — closes the IPC channel and stops accepting connections
Wait for the 'disconnect' event to confirm clean disconnection
Set a timeout (e.g., 5s) as a safety net to force-kill if requests hang
Call worker.kill() to forcefully terminate if disconnect timeout is exceeded
Perform cleanup in the worker: close DB connections, flush caches, finalize logs