← Lessons

quiz vs the machine

Gold1440

Concurrency

Cancellation And Timeouts

Bound work with deadlines and cooperative cancellation signals.

5 min read · core · beat Gold to climb

Cancellation And Timeouts

A robust concurrent system must stop work that is no longer wanted. Cancellation is the request to abandon a task; a timeout is cancellation triggered automatically after a deadline. Without these, a slow dependency can pin threads and cascade into a full outage.

Most platforms use cooperative cancellation. A cancellation token or context is passed into the task, and the task periodically checks it or watches for a signal at blocking points. Forced thread killing is unsafe because it can leave locks held and state half updated, so cooperation is preferred.

Good practice centers on deadlines rather than per call timeouts. A request enters with a budget, say two hundred milliseconds, and each downstream call gets the remaining time. This prevents the sum of small timeouts from exploding.

  • Propagate Pass the cancellation context through every layer.
  • Check often Poll the token at loop boundaries and before expensive steps.
  • Clean up Release resources in a finally style block when cancelled.

Beware orphaned work: cancelling the caller must also cancel the downstream call, or that work keeps running and wasting capacity. Idempotent operations make retries after a timeout safe.

Key idea

Use cooperative cancellation and propagated deadlines so unwanted work stops promptly without leaving resources in a broken state.

Check yourself

Answer to earn rating on the learn ladder.

1. Why is cooperative cancellation preferred over forcibly killing threads?

2. Why are propagated deadlines better than independent per call timeouts?