Cancellation with AbortSignal
When Relay’s worker gets SIGTERM, it has a few seconds to stop. If it is in the middle of a 30 second
sleep between polls, or waiting on a slow notifier, a plain Promise cannot be told to stop. The
process either waits it out or is killed with work half done.
Async ended with this gap: a timeout stops waiting but the work keeps going. The
fix is one object passed through every layer, the AbortSignal. This lesson shows how to create it,
pass it down, and turn “stopped on purpose” into a value instead of an exception.
AbortController and AbortSignal
Section titled “AbortController and AbortSignal”An AbortController owns a signal. The owner calls abort(). Everyone else only gets the
read-only signal, so they can observe cancellation but not trigger it:
const controller = new AbortController()const signal: AbortSignal = controller.signal
signal.aborted // falsesignal.addEventListener("abort", () => console.log("stopping"), { once: true })
controller.abort(new Error("shutdown")) // runs the listenersignal.aborted // truesignal.reason // Error: shutdownreason can be any value. Pass one that says why: "shutdown", a timeout error, a user action.
If you pass nothing, reason is a DOMException named AbortError. A signal aborts once. Later
abort() calls do nothing.
Pass the signal down every layer
Section titled “Pass the signal down every layer”Cancellation only works if every layer that waits can see the signal. A layer that does not take it
becomes a place where the worker blocks. Put signal in the parameters of each function that does
I/O, and hand it on:
interface Job { readonly id: string}declare function takeJob(signal: AbortSignal): Promise<Job | null>declare function send(text: string, signal: AbortSignal): Promise<void>
async function handle(job: Job, signal: AbortSignal): Promise<void> { await send(`done ${job.id}`, signal)}
async function loop(signal: AbortSignal): Promise<void> { while (!signal.aborted) { const job = await takeJob(signal) if (job !== null) await handle(job, signal) }}The standard APIs already accept it: fetch(url, { signal }) rejects when the signal aborts. Your
own ports should too. This is why the QueuePort and NotifyPort from lesson 1
take a signal.
Checking: throwIfAborted
Section titled “Checking: throwIfAborted”A loop that does CPU work between awaits will not notice an abort by itself. Check at the points
where stopping is safe. signal.throwIfAborted() throws signal.reason if the signal is aborted
and does nothing otherwise:
declare function parse(line: string): string
function parseAll(lines: readonly string[], signal: AbortSignal): string[] { const out: string[] = [] for (const line of lines) { signal.throwIfAborted() out.push(parse(line)) } return out}Throwing is right for code that has no way to return “stopped”. Where you can return a value, the
aborted flag is better, as shown next.
Aborted as a value
Section titled “Aborted as a value”A normal shutdown is not a bug, so it should not look like one. If it is thrown, every caller needs
a catch and has to tell it apart from a real failure. Return it instead, the same way
errors as values returns failures, so it shows up in the signature:
type Result<A, E> = | { readonly ok: true; readonly value: A } | { readonly ok: false; readonly error: E }
class Aborted { readonly _tag = "Aborted" constructor(readonly reason: unknown) {}}
declare function pollOnce(signal: AbortSignal): Promise<string | null>
async function waitForResult(signal: AbortSignal): Promise<Result<string, Aborted>> { while (!signal.aborted) { const value = await pollOnce(signal) if (value !== null) return { ok: true, value } } return { ok: false, error: new Aborted(signal.reason) }}A real failure from pollOnce still throws. Only the planned stop becomes Aborted. When this
Aborted is combined with the other errors of a layer, it joins the union from
lesson 2.
A sleep that wakes on abort
Section titled “A sleep that wakes on abort”sleep(30_000) that ignores the signal holds the shutdown for 30 seconds. A cancellable sleep
listens for the abort and cancels its timer. It needs care in three places: check if already
aborted, cancel the timer on abort, and remove the listener when the timer fires:
function sleep(ms: number, signal: AbortSignal): Promise<boolean> { if (signal.aborted) return Promise.resolve(false) return new Promise((resolve) => { const onAbort = () => { clearTimeout(timer) resolve(false) } const timer = setTimeout(() => { signal.removeEventListener("abort", onAbort) resolve(true) }, ms) signal.addEventListener("abort", onAbort, { once: true }) })}It returns true when the full time passed and false when it was cut short. The listener removal
matters: the worker uses one long-lived signal for the whole run, and every sleep adds a listener. If
they are never removed, memory grows with every poll.
The timer is created inside the function. In the exercise it is passed in as a schedule function,
for the same reason sleep was passed in async: a test can then fire it by hand.
Timeouts and combining signals
Section titled “Timeouts and combining signals”AbortSignal.timeout(ms) gives a signal that aborts by itself after ms, with a TimeoutError
reason. AbortSignal.any([a, b]) gives a signal that aborts when any input does. Together they
express “stop on shutdown, or after 5 seconds, whichever comes first”:
declare function send(text: string, signal: AbortSignal): Promise<void>
async function notifyWithDeadline(text: string, shutdown: AbortSignal): Promise<void> { const signal = AbortSignal.any([shutdown, AbortSignal.timeout(5_000)]) await send(text, signal)}signal.reason tells you which one fired: your shutdown reason, or a TimeoutError. That is how a
caller decides between “stopped on purpose” and “too slow, retry”.
Cleaning up listeners
Section titled “Cleaning up listeners”Every addEventListener("abort", ...) on a signal that outlives the work is a leak. Use
{ once: true }, which removes the listener after it runs, and call removeEventListener when the
work ends first, as sleep does above. A listener that captures a large object keeps it alive for
as long as the signal lives.
Disposal from lesson 3 fits here. A scoped resource can remove its listener in
Symbol.dispose, so it cannot be forgotten.
When not to use it
Section titled “When not to use it”An abort is cooperative: it only works if the code you call checks the signal. Passing a signal to a function that ignores it does nothing. For a short call that always finishes quickly, threading a signal through every layer adds parameters for no gain. Add it where work can be long or blocked on I/O: queue reads, network calls, sleeps and loops.
Exercise
Section titled “Exercise”Write sleep(ms, signal, schedule) and a poll loop. schedule starts a timer and returns a
function that cancels it, so the tests fire timers by hand and never wait. The starter ignores the
signal, so a shutdown waits for the whole sleep. Return Aborted as a value for a normal stop.
- The owner keeps the
AbortController. Everyone else gets only thesignal. - Pass
signaldown every layer that waits. One layer that ignores it blocks the shutdown. signal.reasonsays why.throwIfAborted()throws it, andsignal.abortedlets you return a value.- A planned stop is a value (
Aborted), not an exception. A real failure still throws. AbortSignal.anycombines signals.AbortSignal.timeoutmakes a deadline.- Remove abort listeners when the work ends first, or they pile up on a long-lived signal.
- In tests, pass a fake timer and abort a controller by hand.
Further reading
Section titled “Further reading”- AbortSignal.any(): combining several signals.
- AbortSignal:
timeout(),throwIfAborted()and the abort event.