← Runtimes
Runtimes

Cancellation, deadlocks, and task lifetime

Stop work promptly, and never let tasks wait on each other in a circle.

A task’s lifetime includes stopping its work and releasing the resources it holds.

Outcome

Make work honor cancellation at boundaries and inside waits, explain how waiting dependencies form a deadlock, and order locks so that cycles cannot form without losing concurrency.

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.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
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();
terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
npx tsc --noEmit --strict main.ts && node main.ts
In the recorded run, with cancellation requested near 100 ms and ordinary scheduling, when does each task notice it? These rounded times are observations, not latency guarantees.

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.

Three jobs run at once: a→b, b→c, c→a. Each locks its source, pauses, then locks its destination. Which change prevents this mutex-order cycle while allowing unrelated jobs to overlap, assuming distinct shards and eventual completion of each critical section?

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.

  1. easy · R-STOP-V4-1 Respect a cancel
  2. medium · R-STOP-V4-2 Stop while waiting
  3. hard · R-STOP-V4-3 No waiting in circles
Check this idea later
A Go worker checks ctx.Err() before each iteration, which then calls time.Sleep(30 * time.Second). Ignoring additional scheduling delay, how much of that sleep may remain after cancellation?
Two functions lock accounts in parameter order: transfer(a, b) and transfer(b, a) run concurrently. What prevents a deadlock without one global lock?
A std::jthread’s joinable function has only a sleep_for(10s) left before it returns, ignoring its stop_token. Its destructor now runs. Ignoring additional scheduling delay, what happens?
Sources
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.

Example.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
"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.

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.