Skip to content

Cancellation Has an Owner

The Course
•
18 min study

The decision

When a caller leaves, work that exists only for that caller should usually stop. A request-scoped abort signal lets dependencies cooperate; background jobs need a separate owner and lifecycle.

Read, predict, run

This policy chooses whether a task should accept a result. It takes cancellation as an explicit input. For real I/O, pass request.signal or a derived signal to fetch and clean up timers and listeners when the operation finishes:

JavaScript
export function run({ cancelled, finished }) {
  return cancelled ? "discard" : finished ? "accept" : "wait";
}

Before pressing Run, predict what run returns for {"cancelled": true, "finished": true} and {"cancelled": false, "finished": false}, from the code above. Write your answers down first: after Run, the case table shows the expected values beside the actual ones.

Cancellation Has an Owner Next.js · 5 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Review Queue · Practice lab</strong> </header> {children} </body> </html> ); } import Cases from "./Cases.jsx"; export default function Page() { return ( <main> <h1>Cancellation Has an Owner</h1> <p> Read the input and predict the result before running. Change lib/contract.js for the exercise. </p> <Cases /> </main> ); } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } export function run({ cancelled, finished }) { return cancelled ? "discard" : finished ? "accept" : "wait"; } export const examples = [ [{ cancelled: true, finished: true }, "discard"], [{ cancelled: false, finished: false }, "wait"], ];
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Check your prediction
  • Input {"cancelled": true, "finished": true} → "discard".
  • Input {"cancelled": false, "finished": false} → "wait".

The case table computes these results on the server side of the simulation. It compares values; it does not prove a production deployment or database works.

The failure to avoid

An abort is not necessarily a server failure worth showing as an alert. Conversely, ignoring every exception named AbortError can hide a real failure if classification is untrusted.

Trace an abandoned request. A reader opens a slow report, then leaves after one second. Without cancellation the handler keeps waiting on its downstream queries for the full time and renders a page nobody receives. With request.signal passed to each fetch, the abort reaches them: they reject with an AbortError, the handler stops, and the policy above returns discard, so nothing is reported as a failure. A background job started by the same request, such as sending a confirmation email, should not take that signal: its owner is the job queue, not the reader.

Exercise

Extend the contract

Return timeout when the deadlineExpired flag is true, unless the caller already cancelled.

Decide the precedence first: write a case where cancelled and deadlineExpired are both true, with the result you want and one sentence on why. Then implement it.

Edit lib/contract.js, then rerun the original cases. If the requested rule changes an earlier result, update that expected value deliberately. Keep the other cases. Add the acceptance cases to examples so the preview checks them too.

  • Input {"cancelled": false, "finished": false, "deadlineExpired": true} must return "timeout".
Your working space Next.js · 5 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Review Queue · Practice lab</strong> </header> {children} </body> </html> ); } import Cases from "./Cases.jsx"; export default function Page() { return ( <main> <h1>Cancellation Has an Owner</h1> <p> Read the input and predict the result before running. Change lib/contract.js for the exercise. </p> <Cases /> </main> ); } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } export function run({ cancelled, finished }) { return cancelled ? "discard" : finished ? "accept" : "wait"; } export const examples = [ [{ cancelled: true, finished: true }, "discard"], [{ cancelled: false, finished: false }, "wait"], ];
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Hint 1: the idea

A timeout and a cancellation both stop the work, but they mean different things: the server gave up, versus the caller left. When both happened, the caller leaving explains everything.

Hint 2: a first step

Decide which reason takes precedence, then keep that order explicit.

Show one solution

Replace the exported run function and any constants shown here; keep the examples export underneath it. Compare the result with your own approach.

JavaScript
export function run({ cancelled, finished, deadlineExpired }) {
  return cancelled
    ? "discard"
    : deadlineExpired
      ? "timeout"
      : finished
        ? "accept"
        : "wait";
}

cancelled is still checked first, so a caller who left gets discard even if the deadline also passed, and nobody is alerted about a timeout no one saw. deadlineExpired comes before finished: a result that arrives after the deadline is no longer wanted. A timeout is worth logging and counting; a discard usually isn't.

Explain it without the code

For an import started by a button press, write which work should stop when the reader closes the tab, and which should carry on.

Going further

Read the Next.js guide for the framework boundary around this rule. The preview runs code-playpad's Next.js simulation. Real caching, hydration, authentication and persistence require the real-server checks described on Day 7.

Was this article helpful?

Your response is saved on this device.