Terminology (4)Terms used in this lesson
Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.
- Cooperative cancellation
- Work stops because it checks a cancellation request; nothing forcibly kills it.
- AbortSignal
- Carries a cancellation request. Participating APIs define their response; Node’s promise timer rejects on abort. A signal does not interrupt arbitrary code.
- Deadlock
- A set of tasks cannot progress because their waits depend on one another, such as a cycle of held mutexes or full channels.
- Lock ordering
- Taking distinct mutexes in one consistent order prevents cycles among those acquisitions. It does not prevent other wait cycles, self-locking or starvation.
Who owns a task’s lifetime
Concurrent work needs an owner: the operation that starts tasks must decide when their results are no longer needed, request that they stop, and account for their completion. A cancellation request and completed cleanup are separate events. A task can still hold a lock or keep another task waiting after its owner has returned.
Deadlock is a different lifetime failure: tasks remain alive but cannot progress because their waits depend on one another. To reason about shutdown, track both the path of the stop request and the resources each task must acquire or release before it can finish. The native mechanisms below differ, but each requires participating code.
01Cancellation is a request
Work stops only where it checks
An operator stops an archive-relocation batch, but an in-progress copy keeps its storage shards locked. Once copies run concurrently, two relocations in opposite directions can each hold the shard the other needs. The runner needs cancellation at the copy wait and a lock protocol that also handles same-shard work.
The cancellation mechanisms here are cooperative: they request a stop; participating code decides when to return. Check before beginning a copy, and arrange for an in-progress wait to notice the request. An AbortSignal does not interrupt arbitrary JavaScript, nor does a context or stop token forcibly stop a thread. The probe requests cancellation after 100 ms while comparing a plain 500 ms wait with a cancellation-aware one.
import { setTimeout as delay } from 'node:timers/promises';
const start = performance.now();
const at = () => Math.round((performance.now() - start) / 100) * 100;
async function main(): Promise<void> {
const controller = new AbortController();
setTimeout(() => controller.abort(), 100);
const plain = (async () => {
await delay(500);
console.log(`plain wait noticed the cancel at about ${at()} ms (aborted: ${controller.signal.aborted})`);
})();
const cancellable = (async () => {
try {
await delay(500, undefined, { signal: controller.signal });
} catch {
console.log(`cancellable wait noticed the cancel at about ${at()} ms`);
}
})();
await Promise.all([plain, cancellable]);
}
void main();
npx tsc --noEmit --strict main.ts && node main.ts
02Waiting in a circle
Deadlock needs a cycle; lock order removes it
Parallel relocations reserve source and destination storage shards. If a→b holds a while waiting for b, and b→a holds b while waiting for a, neither can finish its copy or release the first reservation. This is a mutex wait cycle; the bounded-channel cycle in the preceding lesson arose from different resources.
03Practice
Run the relocation batch
The lab uses native mutexes or the supplied asynchronous lock, with native waits modeling archive-copy time; it performs no storage transfer. A watchdog measures a three-second whole-job deadline. The 100 ms cancellation target and 600 ms workload budget are checks on these authored workloads under ordinary scheduling, not operating-system latency guarantees.
The archive relocation batch
Jobs reserve their source and destination storage shards while a modeled archive copy waits. Respect cancellation, preserve earlier completions, then handle overlapping and same-shard jobs without serializing independent copies.
Check this idea later
In the frontend A canceled signal stays canceled. Optional
An archive-preview panel creates one AbortController for its mounted lifetime. Preview starts fetch with that signal; Cancel aborts it. Assume the first request is pending when Cancel is clicked.
Now click Preview again. Does a new fetch call give the same signal a fresh lifetime? Identify who owns a request’s cancellation state before adding retries or component cleanup.
"use client";
import { useState } from "react";
export default function ArchivePreview() {
const [controller] = useState(() => new AbortController());
const [status, setStatus] = useState("Idle");
async function preview() {
setStatus("Loading");
try {
const response = await fetch("/api/archive-preview", {
signal: controller.signal
});
setStatus(await response.text());
} catch (error) {
setStatus(
error instanceof Error && error.name === "AbortError" ? "Canceled" : "Failed"
);
}
}
return (
<section>
<button onClick={preview}>Preview</button>
<button onClick={() => controller.abort()}>Cancel</button>
<output>{status}</output>
</section>
);
}
This handler is under review. An AbortController has a one-shot signal; rerendering or invoking fetch again does not reset it. Passing that signal to fetch also does not interrupt unrelated CPU work or stop an independently managed server task.
Sources: DOM standard: AbortController,Fetch standard: fetch method.
Sign in to keep your read marks on every device. Sign in
Was this helpful?