PeaBox Lab › PeaLang › Learn › Chapter 13 › Lesson 3

Part III — Advanced Systems · Chapter 13 · Lesson 3 of 5 · 4 min read

Lesson 3: Cancellation Tokens, Scopes, Deadlines, and Propagation

Lesson level: Advanced

Purpose: Learn how to stop asynchronous work that is no longer needed, how deadlines bound total waiting time, and how cancellation flows through nested tasks and host calls.

Release note: cancellation API names in this lesson are illustrative. Verify them against your installed v0.63 release.

Learning objectives

By the end of this lesson, you should be able to:

3.1 Why cancel

A user closes a request, a faster replica already answered, or the overall deadline has passed. Work that continues after its result is no longer wanted wastes resources, holds connections, and can produce side effects nobody expects. Cancellation is the signal to stop.

3.2 Cancellation is cooperative

PeaLang does not kill a task in the middle of a statement. Cancellation is requested, and the task notices it at its next suspension point or explicit check. This keeps cancellation as predictable as scheduling: code between two awaits always runs to completion.

3.3 Cancellation tokens

let source = std.async.cancel_source()
let token = source.token()

async function lookup_all(ids, token) {
  let out = []
  for id in ids {
    token.raise_if_cancelled()
    out.append(await host.lookup_tier(id, token))
  }
  return out
}

source.cancel("client disconnected")

The source requests cancellation; the token is what code receives and checks. Passing the token to host awaitables lets the host stop its own work too.

3.4 What cancellation looks like

When a cancelled task reaches an await or a check, a Cancelled error is raised. It unwinds frames like any other error (Chapter 12 Lesson 5), running finally blocks on the way.

3.5 Cancellation scopes

with std.async.cancel_scope() as scope {
  let t = await fetch_tier(order["customer_id"])
  if t == "unknown" { scope.cancel() }
}

A scope cancels everything started inside it when it is cancelled or exits with an error. Scopes give cancellation a visible boundary in the source, the same way blocks give variables a visible scope.

3.6 Deadlines

with std.async.deadline(seconds=2.0) {
  let tier = await host.lookup_tier(id)
}

A deadline is a scope that cancels itself when time runs out. The resulting error is a timeout, which callers can distinguish from an explicit cancellation.

MechanismTriggered byTypical use
Explicit cancelCode or host requestClient disconnect, shutdown
DeadlineElapsed timeRequest time budget
Scope failureError in a sibling taskFail fast in a task group (Lesson 4)

3.7 Propagation

Cancellation flows downward: cancelling a scope cancels every task and host call started within it, including nested scopes. It never flows upward on its own; the parent decides what a cancelled child means. An inner deadline shorter than the outer one wins for its region; an inner deadline longer than the outer one is cut short by the outer.

3.8 Cleanup on cancellation

async function reserve_and_price(order, token) {
  let hold = await host.reserve_stock(order["sku"], order["qty"], token)
  try {
    return await price(order, token)
  } finally {
    await host.release_if_unconfirmed(hold)
  }
}

Finally blocks run during cancellation, so they are the right place to release reservations, close streams, and record audit entries. Keep cleanup short and bounded; it may itself be subject to a short shielded deadline in your host.

3.9 Do not swallow cancellation

Catching every error and returning a default also catches Cancelled. The task then continues working after it was told to stop. Catch specific error types, or re-raise Cancelled explicitly.

try {
  return await host.lookup_tier(id, token)
} catch err {
  if err.kind == "Cancelled" { throw err }
  return "standard"
}

3.10 Worked example

The order_rules API gives each request 3 seconds. Inside, tier lookups run under a 2-second deadline with a fallback to "standard". If the client disconnects, the host cancels the request scope: outstanding lookups stop, stock holds are released in finally blocks, and no reason codes are written for the abandoned request.

3.11 Common mistakes

MistakeConsequenceFix
Not passing tokens to host callsHost keeps working after cancelPass the token through
Catching Cancelled as a generic errorTask ignores the stop requestRe-raise Cancelled
Unbounded cleanupShutdown hangsKeep finally blocks short and time-limited
Missing overall deadlineRequests can wait foreverSet a request-level deadline

3.12 Guided practice

3.13 Hands-on lab

Using a fake host with configurable delay, run the order pricing flow under a request deadline. Cancel it midway, then let it time out. Confirm that all holds are released and no partial results are stored.

Deliverable: the script, a log of cancellation and timeout runs, and a list of cleanup actions observed.

3.14 Review questions

3.15 Applied challenge

Write a cancellation policy for a service with request, per-call, and shutdown deadlines. Specify each value, what is cleaned up, and what is logged.

Lesson summary

Transition to Lesson 4

Starting many tasks safely needs structure. Lesson 4 introduces task groups, structured gathering, and failure handling.

Lesson status: Ready for review.

← Previous Next →