Skip to content

Signals and graceful shutdown

The first tsbox stop killed containers with SIGKILL. It was fast and it was wrong: a Relay database container had buffered writes in memory, never got the chance to flush them, and came back with the last few seconds missing. The kernel does not ask a SIGKILL victim for anything. The fix is the sequence every container runtime uses: ask nicely, wait a grace period, then force.

A signal is a small message the kernel delivers to a process. Five matter here, and their numbers are the same on macOS and Linux:

Signal Number Meaning Can the program handle it?
SIGHUP 1 the terminal went away; often “reload config” yes
SIGINT 2 Ctrl-C yes
SIGQUIT 3 Ctrl-\, quit and dump core yes
SIGKILL 9 die now no
SIGTERM 15 please shut down (the default of kill) yes

A process that handles SIGTERM can finish the request it is serving, flush its buffers and exit. SIGKILL and SIGSTOP cannot be caught, blocked or ignored, which is exactly why they are the last resort and not the first.

When a process dies from a signal, a shell reports its exit code as 128 + n: 130 for Ctrl-C, 137 for SIGKILL, 143 for SIGTERM. Seeing 137 in a container’s exit status means “killed, probably out of memory or by a forced stop”.

type Signal = "SIGHUP" | "SIGINT" | "SIGQUIT" | "SIGKILL" | "SIGTERM"
const NUMBER: Record<Signal, number> = { SIGHUP: 1, SIGINT: 2, SIGQUIT: 3, SIGKILL: 9, SIGTERM: 15 }
function exitCodeForSignal(signal: Signal): number {
return 128 + NUMBER[signal]
}
console.log(exitCodeForSignal("SIGTERM")) // 143

In the program that should shut down, register a handler. While a handler exists, the default action (die) is replaced by your code:

let stopping = false
process.on("SIGTERM", () => {
if (stopping) return // a second SIGTERM must not start a second shutdown
stopping = true
console.log("draining")
// finish in-flight work, close files, then:
process.exit(0)
})

Do the shutdown once, keep the handler short, and finish with an exit code that tells the truth. A handler that catches SIGTERM and then forgets to exit is a container that can only be stopped with SIGKILL: that is the bug the real test in the exercise reproduces.

Wire it to the cancellation you already have. The handler does not do the work, it only calls abort(), and every layer that waits watches the signal (cancellation):

const shutdown = new AbortController()
for (const name of ["SIGINT", "SIGTERM"] as const) {
process.on(name, () => shutdown.abort(new Error(`received ${name}`)))
}
async function worker(signal: AbortSignal): Promise<void> {
while (!signal.aborted) {
await Bun.sleep(100)
}
}
await worker(shutdown.signal)

tsbox is the parent of the container process. A terminal sends Ctrl-C to every process in the foreground process group, but a container is started in its own session so it can outlive the CLI (lesson 6). Then nothing reaches it unless tsbox forwards the signal, and the container keeps running with nobody to stop it. Forwarding is a listener that calls child.kill(signal), and a function that removes the listeners again, so a long-lived parent does not leak them. The exercise’s forwardSignals(source, child, signals) takes the signal source as a port (process in production, a map in tests).

stopWithGrace(child, graceMs, timers) is a small state machine:

Running --SIGTERM sent, timer started--> Stopping
Stopping --child exits first--> Graceful (timer cleared)
Stopping --timer fires first--> SIGKILL sent --child exits--> Killed
already exited --> AlreadyExited (nothing sent)

The only moving part is time, so time is a port (dependencies as types, and the same idea as testing time):

interface Timers {
setTimeout(fn: () => void, ms: number): number
clearTimeout(handle: number): void
}
interface Stoppable {
readonly exitCode: number | null
readonly exited: Promise<number>
kill(signal: "SIGTERM" | "SIGKILL"): void
}
async function stopWithGrace(child: Stoppable, graceMs: number, timers: Timers): Promise<"graceful" | "killed"> {
child.kill("SIGTERM")
let escalated = false
const handle = timers.setTimeout(() => {
escalated = true
child.kill("SIGKILL")
}, graceMs)
await child.exited
timers.clearTimeout(handle) // the child won the race: no stray SIGKILL later
return escalated ? "killed" : "graceful"
}

Two details cause real incidents. Clearing the timer matters: a leftover timer would send SIGKILL to a pid the kernel may by then have given to an unrelated process. And checking exitCode !== null first matters: signalling a finished child is at best a no-op and at worst the same pid-reuse bug. (The exercise returns a tagged result and handles the already-exited case; this snippet is the core idea only.)

In tests, Timers is a fake whose timers fire when the test says so, and a fake child records which signals it got. Then “SIGTERM first, SIGKILL only if the timer fires” is an assertion about a list, and takes no time.

Local, because the last two tests spawn a real child. Copy the starter into the Relay project as main.ts and the tests next to it. The tests also run on macOS: signals work the same way there.

The starter sends SIGKILL at once and ignores the timer. Your version passes the fake-timer tests (one timer of exactly graceMs, cleared when the child exits first, SIGKILL once and only after it fires, no signal for an already-exited child, listeners removed by forwardSignals) and then two real ones: a child that traps SIGTERM and ignores it must be killed after the grace period (code 137), and a child that exits on SIGTERM must not be.

main.ts
// `tsbox stop` first killed containers with SIGKILL straight away. A database container lost its
// last writes because it never got to flush. The fix is a grace period: ask with SIGTERM, wait,
// and only then force with SIGKILL. Your version must be testable without waiting, so time comes
// in as a `Timers` port. This version has bugs.
//
// Rules:
// - exitCodeForSignal(signal) is 128 + the signal number (SIGHUP 1, SIGINT 2, SIGQUIT 3,
// SIGKILL 9, SIGTERM 15): what a shell reports for a killed process.
// - stopWithGrace(child, graceMs, timers):
// - child already exited (exitCode not null): send nothing, return AlreadyExited with its code.
// - otherwise send SIGTERM and schedule ONE timer of exactly `graceMs`.
// - child exits before the timer fires: Graceful with its code, the timer is cleared, SIGKILL is
// never sent.
// - the timer fires first: send SIGKILL once and return Killed with the code it exits with.
// - forwardSignals(source, child, signals): each listed signal received by `source` is forwarded
// to the child; the returned function removes exactly those listeners.
export type Signal = "SIGHUP" | "SIGINT" | "SIGQUIT" | "SIGKILL" | "SIGTERM"
export function exitCodeForSignal(signal: Signal): number {
return signal === "SIGKILL" ? 137 : 143
}
export interface Stoppable {
readonly exitCode: number | null
readonly exited: Promise<number>
kill(signal: "SIGTERM" | "SIGKILL"): void
}
export interface Timers {
setTimeout(fn: () => void, ms: number): number
clearTimeout(handle: number): void
}
export type StopOutcome =
| { readonly _tag: "AlreadyExited"; readonly code: number }
| { readonly _tag: "Graceful"; readonly code: number }
| { readonly _tag: "Killed"; readonly code: number }
export async function stopWithGrace(child: Stoppable, _graceMs: number, _timers: Timers): Promise<StopOutcome> {
child.kill("SIGKILL")
return { _tag: "Killed", code: await child.exited }
}
export interface SignalSource {
on(signal: Signal, listener: () => void): void
off(signal: Signal, listener: () => void): void
}
export function forwardSignals(
source: SignalSource,
child: { kill(signal: Signal): void },
signals: readonly Signal[],
): () => void {
for (const signal of signals) source.on(signal, () => child.kill(signal))
return () => {}
}
export function realTimers(): Timers {
throw new Error("not implemented")
}
main.test.ts
import { expect, test } from "bun:test"
import { exitCodeForSignal, forwardSignals, realTimers, stopWithGrace } from "./main.ts"
import type { Signal, SignalSource, Stoppable, Timers } from "./main.ts"
function fakeChild(exitCode: number | null = null) {
const signals: string[] = []
let finish: (code: number) => void = () => {}
const exited = new Promise<number>((resolve) => {
finish = resolve
})
const child: Stoppable & { signals: string[]; exit(code: number): void } = {
get exitCode() {
return exitCode
},
exited,
kill(signal) {
signals.push(signal)
},
signals,
exit(code) {
exitCode = code
finish(code)
},
}
return child
}
function fakeTimers() {
const scheduled = new Map<number, { fn: () => void; ms: number }>()
const cleared: number[] = []
let next = 1
const timers: Timers & { scheduled: typeof scheduled; cleared: number[]; fireAll(): void } = {
setTimeout(fn, ms) {
const id = next++
scheduled.set(id, { fn, ms })
return id
},
clearTimeout(id) {
cleared.push(id)
scheduled.delete(id)
},
scheduled,
cleared,
fireAll() {
for (const [id, timer] of [...scheduled]) {
scheduled.delete(id)
timer.fn()
}
},
}
return timers
}
test("exit codes for signals are 128 + the signal number", () => {
expect(exitCodeForSignal("SIGHUP")).toBe(129)
expect(exitCodeForSignal("SIGINT")).toBe(130)
expect(exitCodeForSignal("SIGQUIT")).toBe(131)
expect(exitCodeForSignal("SIGKILL")).toBe(137)
expect(exitCodeForSignal("SIGTERM")).toBe(143)
})
test("an already exited child gets no signal and no timer", async () => {
const child = fakeChild(0)
const timers = fakeTimers()
expect(await stopWithGrace(child, 1000, timers)).toEqual({ _tag: "AlreadyExited", code: 0 })
expect(child.signals).toEqual([])
expect(timers.scheduled.size + timers.cleared.length).toBe(0)
})
test("SIGTERM first, with exactly one timer of graceMs", async () => {
const child = fakeChild()
const timers = fakeTimers()
const outcome = stopWithGrace(child, 2500, timers)
expect(child.signals).toEqual(["SIGTERM"])
expect([...timers.scheduled.values()].map((t) => t.ms)).toEqual([2500])
child.exit(0)
await outcome
})
test("a child that exits within the grace period is Graceful and the timer is cleared", async () => {
const child = fakeChild()
const timers = fakeTimers()
const outcome = stopWithGrace(child, 1000, timers)
child.exit(0)
expect(await outcome).toEqual({ _tag: "Graceful", code: 0 })
expect(timers.scheduled.size).toBe(0)
expect(timers.cleared.length).toBe(1)
timers.fireAll()
expect(child.signals).toEqual(["SIGTERM"])
})
test("a child that ignores SIGTERM gets SIGKILL when the timer fires", async () => {
const child = fakeChild()
const timers = fakeTimers()
const outcome = stopWithGrace(child, 1000, timers)
expect(child.signals).toEqual(["SIGTERM"])
timers.fireAll()
expect(child.signals).toEqual(["SIGTERM", "SIGKILL"])
child.exit(137)
expect(await outcome).toEqual({ _tag: "Killed", code: 137 })
})
test("a Graceful exit reports the child's own non-zero code", async () => {
const child = fakeChild()
const outcome = stopWithGrace(child, 1000, fakeTimers())
child.exit(143)
expect(await outcome).toEqual({ _tag: "Graceful", code: 143 })
})
test("forwardSignals forwards listed signals and removes its listeners", () => {
const listeners = new Map<Signal, Set<() => void>>()
const source: SignalSource = {
on: (signal, fn) => void (listeners.get(signal) ?? listeners.set(signal, new Set()).get(signal))?.add(fn),
off: (signal, fn) => void listeners.get(signal)?.delete(fn),
}
const received: Signal[] = []
const stop = forwardSignals(source, { kill: (s) => void received.push(s) }, ["SIGINT", "SIGTERM"])
for (const fn of listeners.get("SIGINT") ?? []) fn()
for (const fn of listeners.get("SIGTERM") ?? []) fn()
expect(received).toEqual(["SIGINT", "SIGTERM"])
expect(listeners.get("SIGHUP")).toBe(undefined)
stop()
expect(listeners.get("SIGINT")?.size).toBe(0)
expect(listeners.get("SIGTERM")?.size).toBe(0)
})
async function spawnReady(script: string) {
const child = Bun.spawn([process.execPath, "-e", script], { stdout: "pipe", stderr: "ignore" })
const reader = child.stdout.getReader()
await reader.read()
reader.releaseLock()
return child
}
test("real child that ignores SIGTERM is killed after the grace period", async () => {
const child = await spawnReady("process.on('SIGTERM', () => {}); console.log('ready'); setInterval(() => {}, 1000)")
const started = performance.now()
const outcome = await stopWithGrace(child, 200, realTimers())
expect(outcome).toEqual({ _tag: "Killed", code: 137 })
expect(child.signalCode).toBe("SIGKILL")
expect(performance.now() - started >= 150).toBe(true)
})
test("real child that handles SIGTERM exits on its own, no SIGKILL", async () => {
const child = await spawnReady("process.on('SIGTERM', () => process.exit(7)); console.log('ready'); setInterval(() => {}, 1000)")
const outcome = await stopWithGrace(child, 5000, realTimers())
expect(outcome).toEqual({ _tag: "Graceful", code: 7 })
})
  • SIGTERM asks, SIGKILL forces. A process can handle the first, never the second.
  • Death by signal reads as 128 + n: 130, 137, 143.
  • A handler should be short, run once, and end with an honest exit. Turn the signal into an AbortController.abort().
  • A parent that does not forward signals leaves its child running after Ctrl-C.
  • Graceful stop is SIGTERM, a timer, SIGKILL. Inject the timer, clear it when the child wins, skip children that already exited.
  • signal(7): what each signal means and which ones cannot be caught.