Graceful process supervision
Prerequisites: previous curriculum lessons on Node streams, HTTP, buffers and asynchronous errors. Local lab baseline: Node.js 22.16.0, Linux, ESM. Use a disposable directory. Static examples are not ByteMind interactive execution. Each example is independent; save the named files together and run node main.mjs. The author harness imposes a five-second process deadline.
How it works
On supported platforms, a SIGTERM handler can initiate shutdown. Registering a handler changes default signal behavior; ensure the handler eventually lets the process exit or enforces a deadline. For an HTTP service, stop accepting connections and drain active requests, then close dependencies. A second signal or an expired deadline may trigger forced cleanup; interruption can leave business effects incomplete, so use durable state and idempotency. Prefer setting exitCode and releasing handles over calling process.exit while output is pending. Restart budgets and backoff prevent crash loops; distinguish planned shutdown from failure. External supervisors such as systemd or PM2 are separate tools, not verified here.
Send SIGTERM to one owned child and observe cleanup
import {spawn} from 'node:child_process';import {once} from 'node:events';const child=spawn(process.execPath,['task.mjs'],{stdio:['ignore','pipe','pipe'],env:{LANG:'C.UTF-8'}});const done=once(child,'close');let output='';let signaled=false;child.stdout.setEncoding('utf8');child.stdout.on('data',chunk=>{output+=chunk;if(!signaled&&output.includes('ready\n')){signaled=true;child.kill('SIGTERM');}});child.stderr.resume();const timer=setTimeout(()=>child.kill('SIGKILL'),1500);try {const [code,signal]=await done;console.log(output.trim());console.log('exit',code,signal);}finally{clearTimeout(timer);if(child.exitCode===null&&child.signalCode===null)child.kill('SIGKILL');}const keepAlive=setInterval(()=>{},100);process.once('SIGTERM',()=>{clearInterval(keepAlive);console.log('cleanup complete');process.exitCode=0;});console.log('ready');Expected output:
readycleanup completeexit 0 nullThe parent waits for explicit readiness before signaling its own child. This is a Linux signal lifecycle fixture, not a full HTTP drain test.
Apply a finite restart budget to synthetic failures
const maxRestarts=2;let restarts=0;function decide(exitCode){if(exitCode===0)return 'stop clean';if(restarts>=maxRestarts)return 'stop exhausted';restarts++;return 'restart after '+(100*2**(restarts-1))+'ms';}for(const exitCode of [1,1,1])console.log(decide(exitCode));Expected output:
restart after 100msrestart after 200msstop exhaustedThis model records at most two retries. A production supervisor also needs a time window, jitter, readiness and cancellation policy.
Common mistakes
Do not keep accepting traffic during teardown, restart without bounds or signal unrelated PIDs. A liveness signal does not prove a worker is ready for requests. Test shutdown independently of startup.
Practice
Change the restart budget to one retry. Explain when the supervisor stops and how you would verify active work was drained.
Further reading
Official documentation: process, child_process. Internal reference candidate: node-graceful-process-supervision-lookup (route not verified).
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Graceful process supervision — knowledge check
Apply the lesson to a fresh scenario and explain the resource or protocol boundary.
What is the first step of graceful shutdown?
Why wait for explicit readiness before signaling the fixture child?
Why impose a restart budget?