Async Task Cancellation Runbook — Python, JS, Go, Java
Runbook for cancelling long-running async tasks without leaks: cooperative signals, cleanup budgets, propagation, and verification in Python, JS, Go, Java.
Overview
A pod receives SIGTERM during a deploy. A user clicks “cancel” on a report that’s been running for three minutes. A request hits its deadline and the caller is long gone, but the worker keeps burning CPU and holding a database connection. If your async tasks can’t be stopped cleanly, every one of those situations leaves something behind: open connections, half-written files, locks that never release.
This runbook is the operational procedure for cancelling async work without the leaks. It covers the two cancellation styles (cooperative vs. hard kill), how to propagate the signal, per-language implementations for Python, JavaScript, Go, and Java, and a step-by-step procedure with verification checks. If what you actually need is to shut down a whole service gracefully — not a single task — use the graceful shutdown recipe instead; this runbook is about the task-level contract.
Every cancellation design answers two questions: when to abort (cooperative checkpoints vs. immediate kill) and how to clean up (release locks, close connections, flush writes). Graceful cancellation is a cooperative protocol — the task periodically checks a signal and exits cleanly. Hard cancellation kills the task and leaves cleanup to whoever owns the resource. Most production systems want graceful with a hard timeout as the fallback.
Cancellation propagates two ways: down (the parent cancels children it owns) and up (a child reports its own cancellation so the parent can react). Skip the down-propagation and you leak tasks; skip the up-propagation and the parent thinks the work finished.
When to Trigger This Runbook
Reach for this procedure when any of these are true:
- A deploy or scale-down event is coming and in-flight tasks must finish their cleanup before the process exits.
- A user-facing “cancel” or “stop” action exists for work that runs longer than a few seconds.
- A task exceeded its deadline but keeps running — the caller timed out, the worker didn’t notice.
- A parent workflow was cancelled and its child tasks need the same signal.
- You’ve found leaked tasks, orphaned goroutines, or dangling connections in production and need to close the loop.
When not to bother: sub-second tasks don’t need cooperative checkpoints (the overhead of checking a token exceeds the cost of letting them finish), and fire-and-forget writes like metrics emission are usually better served by a short timeout than by a full cancellation protocol.
1. Cancellation Concepts
1.1 How Each Runtime Cancels
Language | Cancellation mechanism | Propagation method
────────────┼───────────────────────────────┼──────────────────────────
Python | asyncio.CancelledError | task.cancel() + try/finally
JavaScript | AbortSignal / AbortController | signal.aborted + listeners
Go | context.Context | ctx.Done() channel
Java | CompletableFuture.cancel() | future.cancel(true) + interrupt
1.2 The Cancellation Token
A cancellation token is a signal object that travels from the caller to the callee and says “stop when it’s safe.” The task doesn’t get killed — it polls or observes the token at well-defined points, runs its cleanup, and reports the cancellation back up the chain. Most token implementations also carry a timeout (auto-cancel after N seconds) or a deadline (cancel at a specific time), which is what turns a manual mechanism into a self-limiting one.
Safe points to check cancellation:
- Before I/O operations (database calls, HTTP requests, file writes)
- Inside loops that process batches
- Before acquiring locks
- At the start of each pipeline stage
The corollary: a task that never checks its token can’t be cancelled cooperatively. A while loop with a blocking call inside — say, a synchronous requests.get() inside an async function — will ignore cancel() until the call returns, which may be never.
2. Cancellation Procedure
This is the runbook proper. The steps are language-agnostic; the code sections below show the concrete implementation.
Step 1 — Emit the signal once
The parent or supervisor emits cancellation exactly once. task.cancel(), controller.abort(), cancel(), and future.cancel(true) are all idempotent — calling them twice is harmless but pointless. What’s not harmless is cancelling and then awaiting the task without a try/except: in Python and Java, the cancelled task raises, and an unhandled CancelledError in main() will terminate your program with a traceback instead of a clean exit.
Step 2 — Let the task reach a checkpoint
Cancellation lands at the next await, select, or explicit check — not mid-statement. Design tasks so the longest gap between checkpoints is bounded by your responsiveness requirement. If a task must react within 100 ms, no single uninterruptible stretch should exceed that.
Step 3 — Run cleanup under a budget
Give cleanup 5–10 seconds and enforce it with its own timeout — cleanup that blocks forever is how graceful shutdown turns into a hung process. Inside cleanup: close connections, release locks, flush or roll back partial writes, and detach listeners. Whatever you skip, whoever owns the resource inherits.
Step 4 — Propagate the result
Re-raise the cancellation after cleanup (Python: bare raise; Go: return ctx.Err(); JavaScript: rethrow the AbortError). Swallowing it makes the task look successful to gather() or await, which is the quietest way to lose track of what actually stopped.
Step 5 — Verify
After the procedure runs, confirm: the task object is done (not pending), connections released (watch your pool metrics for a dip), no child tasks still running (asyncio.all_tasks() should show only expected entries), and the cancellation reason was logged. If the task ignored the signal past the hard timeout, escalate to a hard kill — process.exit() after the grace period, or the platform’s own mechanism like Kubernetes’ SIGKILL after terminationGracePeriodSeconds.
Graceful vs. hard cancellation
| Graceful (cooperative) | Hard (kill) | |
|---|---|---|
| Mechanism | Token checked at safe points | Thread.stop, SIGKILL, process exit |
| Cleanup | Task runs its own cleanup | Owner/OS reclaims resources |
| Risk | Task may ignore the signal | Partial writes, orphaned children |
| Use when | Always, first | Fallback after cleanup budget expires |
Companion files: the async-task-cancellation-runbook companion repo has each language example below as a standalone runnable file, so you can watch the cancel→cleanup→propagate path execute instead of reading it.
3. Python (asyncio)
task.cancel() doesn’t preempt the coroutine — it arranges for asyncio.CancelledError to be raised at the task’s next await point. A task stuck in a long synchronous call won’t respond; the interrupt arrives only when it awaits again.
3.1 Basic Cancellation
import asyncio
async def long_running_task(task_id: str):
try:
for i in range(1000):
# Check for cancellation at safe points
await asyncio.sleep(0.1)
print(f"Task {task_id}: processing item {i}")
except asyncio.CancelledError:
print(f"Task {task_id}: cancelled, cleaning up...")
# Perform cleanup here
await cleanup_resources(task_id)
raise # Re-raise to propagate cancellation
async def cleanup_resources(task_id: str):
print(f"Task {task_id}: closing connections...")
await asyncio.sleep(0.05) # Simulate cleanup
print(f"Task {task_id}: cleanup complete")
async def main():
task = asyncio.create_task(long_running_task("worker-1"))
# Cancel after 2 seconds
await asyncio.sleep(2)
task.cancel()
try:
await task
except asyncio.CancelledError:
print("Task was cancelled successfully")
asyncio.run(main())
Two details that bite people: asyncio.gather(*tasks) without return_exceptions=True propagates the first CancelledError and abandons the rest — pass return_exceptions=True so every task gets to run its cleanup. And asyncio.create_task() doesn’t keep a strong reference; if the task object is garbage-collected mid-run it may get cancelled implicitly. Keep a reference in a set, like the GracefulShutdown class below does.
3.2 Timeout-Based Cancellation
asyncio.wait_for wraps a coroutine and cancels it when the deadline passes. On Python 3.11+, asyncio.timeout() is the context-manager equivalent and composes better with nested deadlines.
import asyncio
from urllib.parse import urlparse
async def fetch_with_timeout(url: str, timeout: float = 5.0):
try:
result = await asyncio.wait_for(
fetch_data(url),
timeout=timeout,
)
return result
except asyncio.TimeoutError:
print(f"Request to {url} timed out after {timeout}s")
return None
async def fetch_data(url: str):
host = urlparse(url).hostname or url
reader, writer = await asyncio.open_connection(host, 80)
try:
writer.write(f"GET / HTTP/1.1\r\nHost: {host}\r\n\r\n".encode())
await writer.drain()
data = await reader.read(4096)
return data
finally:
writer.close()
await writer.wait_closed()
3.3 Graceful Shutdown with Signal Handling
import asyncio
import signal
class GracefulShutdown:
def __init__(self):
self.shutdown_event = asyncio.Event()
self.tasks: set[asyncio.Task] = set()
def setup_signal_handlers(self):
loop = asyncio.get_running_loop()
for sig in (signal.SIGINT, signal.SIGTERM):
loop.add_signal_handler(sig, self._signal_handler)
def _signal_handler(self):
print("\nShutdown signal received, cancelling tasks...")
self.shutdown_event.set()
async def run_with_shutdown(self, worker_func, num_workers: int = 4):
self.setup_signal_handlers()
# Start workers
for i in range(num_workers):
task = asyncio.create_task(worker_func(i, self.shutdown_event))
self.tasks.add(task)
task.add_done_callback(self.tasks.discard)
# Wait for shutdown signal
await self.shutdown_event.wait()
# Cancel all tasks
for task in self.tasks:
task.cancel()
# Wait for all tasks to finish cleanup
await asyncio.gather(*self.tasks, return_exceptions=True)
print("All tasks shut down gracefully")
async def worker(worker_id: int, shutdown: asyncio.Event):
try:
while not shutdown.is_set():
print(f"Worker {worker_id}: processing...")
await asyncio.sleep(1)
except asyncio.CancelledError:
print(f"Worker {worker_id}: cleaning up...")
await asyncio.sleep(0.1)
print(f"Worker {worker_id}: done")
raise
asyncio.run(GracefulShutdown().run_with_shutdown(worker))
Note that loop.add_signal_handler is Unix-only — on Windows, SIGINT/SIGTERM handling needs signal.signal() with a thread-safe fallback, which is a common portability bug when this pattern gets copied into services that run on both.
4. JavaScript (Node.js)
The DOM AbortController/AbortSignal pair is the standard token in modern Node. Unlike Python’s exception-driven model, the signal is a flag your code polls (signal.aborted) or subscribes to ('abort' event), so every async primitive you build on top of it — like the sleep below — has to wire the signal through.
4.1 AbortController Cancellation
async function longRunningTask(signal, taskId) {
try {
for (let i = 0; i < 1000; i++) {
// Check for cancellation at safe points
if (signal.aborted) {
throw new DOMException('Task cancelled', 'AbortError');
}
await sleep(100, signal);
console.log(`Task ${taskId}: processing item ${i}`);
}
} catch (err) {
if (err.name === 'AbortError') {
console.log(`Task ${taskId}: cancelled, cleaning up...`);
await cleanupResources(taskId);
throw err;
}
throw err;
}
}
function sleep(ms, signal) {
return new Promise((resolve, reject) => {
if (signal?.aborted) {
reject(new DOMException('Aborted', 'AbortError'));
return;
}
const onAbort = () => {
clearTimeout(timer);
reject(new DOMException('Aborted', 'AbortError'));
};
const timer = setTimeout(() => {
signal?.removeEventListener('abort', onAbort);
resolve();
}, ms);
signal?.addEventListener('abort', onAbort, { once: true });
});
}
async function cleanupResources(taskId) {
console.log(`Task ${taskId}: closing connections...`);
await sleep(50); // signal is optional — cleanup runs even without one
console.log(`Task ${taskId}: cleanup complete`);
}
// Usage
const controller = new AbortController();
const task = longRunningTask(controller.signal, 'worker-1');
setTimeout(() => controller.abort(), 2000);
try {
await task;
} catch (err) {
if (err.name === 'AbortError') {
console.log('Task cancelled successfully');
} else {
throw err;
}
}
Two things worth copying from this example: sleep takes the signal as optional (signal?.aborted) because cleanup code calls it after the abort and shouldn’t reject on an already-fired signal. And each sleep call removes its own 'abort' listener on resolve — forget that and a long-lived signal accumulates hundreds of listeners, which Node will warn about as a possible leak.
4.2 Fetch with Cancellation
async function fetchWithTimeout(url, options = {}, timeout = 5000) {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeout);
try {
const response = await fetch(url, {
...options,
signal: controller.signal,
});
return await response.json();
} catch (err) {
if (err.name === 'AbortError') {
console.error(`Request to ${url} timed out after ${timeout}ms`);
return null;
}
throw err;
} finally {
clearTimeout(timeoutId);
}
}
Create one controller per operation, not one shared controller for the whole app — aborting a shared signal cancels every in-flight request at once, which is rarely what a timeout intends.
4.3 Graceful Shutdown in Express
const express = require('express');
const app = express();
const server = app.listen(3000);
let connections = new Set();
server.on('connection', (conn) => {
connections.add(conn);
conn.on('close', () => connections.delete(conn));
});
function gracefulShutdown(signal) {
console.log(`\n${signal} received, shutting down...`);
server.close(() => {
console.log('HTTP server closed');
// Force-close idle connections after 10s
setTimeout(() => {
connections.forEach((conn) => conn.destroy());
process.exit(0);
}, 10000);
});
// Destroy idle connections immediately
connections.forEach((conn) => {
if (!conn.writableEnded) return;
conn.destroy();
});
}
process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
process.on('SIGINT', () => gracefulShutdown('SIGINT'));
server.close() stops accepting new connections but waits for existing ones to end — that’s why the tracked-connections set and the 10-second force-close exist. Without them, a keep-alive connection can hold the process open past the orchestrator’s patience.
5. Go (context.Context)
Go’s cancellation contract is context.Context: every blocking or long-running function takes ctx as its first argument and selects on ctx.Done(). context.WithCancel, WithTimeout, and WithDeadline all return a cancel function — and go vet will flag you for not calling it, because an uncancelled context leaks the goroutine that watches the timer.
5.1 Basic Cancellation
package main
import (
"context"
"fmt"
"time"
)
func longRunningTask(ctx context.Context, taskID string) error {
for i := 0; i < 1000; i++ {
// Check for cancellation at safe points
select {
case <-ctx.Done():
fmt.Printf("Task %s: cancelled, cleaning up...\n", taskID)
cleanupResources(taskID)
return ctx.Err()
default:
}
time.Sleep(100 * time.Millisecond)
fmt.Printf("Task %s: processing item %d\n", taskID, i)
}
return nil
}
func cleanupResources(taskID string) {
fmt.Printf("Task %s: closing connections...\n", taskID)
time.Sleep(50 * time.Millisecond)
fmt.Printf("Task %s: cleanup complete\n", taskID)
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
err := longRunningTask(ctx, "worker-1")
if err != nil {
fmt.Printf("Task ended: %v\n", err)
}
}
5.2 Propagating Context Through HTTP Handlers
func handler(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
select {
case <-ctx.Done():
// Client disconnected
fmt.Println("Client cancelled request")
return
default:
}
result, err := processWithTimeout(ctx, r.URL.Query().Get("id"))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
json.NewEncoder(w).Encode(result)
}
func processWithTimeout(ctx context.Context, id string) (Result, error) {
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
type result struct {
data Result
err error
}
ch := make(chan result, 1)
go func() {
data, err := slowDatabaseQuery(id)
ch <- result{data, err}
}()
select {
case <-ctx.Done():
return Result{}, ctx.Err()
case res := <-ch:
return res.data, res.err
}
}
The buffered channel ch := make(chan result, 1) matters: without it, the spawned goroutine blocks forever writing to ch after the handler has already returned on ctx.Done() — a classic orphaned goroutine. One slot of buffer lets it finish its send and exit even when nobody’s listening.
6. Java (CompletableFuture)
future.cancel(true) sets the interrupt flag on the executing thread; it doesn’t stop the task by force. The task cooperates by checking Thread.currentThread().isInterrupted() or by using interruptible calls like Thread.sleep(), which throw InterruptedException and clear the flag.
6.1 Basic Cancellation
import java.util.concurrent.*;
public class TaskCancellation {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(() -> {
for (int i = 0; i < 1000; i++) {
if (Thread.currentThread().isInterrupted()) {
System.out.println("Task cancelled, cleaning up...");
cleanupResources();
throw new InterruptedException("Task cancelled");
}
Thread.sleep(100);
System.out.println("Processing item " + i);
}
return "done";
});
Thread.sleep(2000);
future.cancel(true);
try {
future.get();
} catch (CancellationException e) {
System.out.println("Task was cancelled");
}
executor.shutdown();
}
static void cleanupResources() {
System.out.println("Closing connections...");
try { Thread.sleep(50); } catch (InterruptedException ignored) {}
System.out.println("Cleanup complete");
}
}
6.2 CompletableFuture with Timeout
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(10000);
return "result";
} catch (InterruptedException e) {
throw new CompletionException(e);
}
});
try {
String result = future.orTimeout(5, TimeUnit.SECONDS).get();
System.out.println("Result: " + result);
} catch (ExecutionException e) {
if (e.getCause() instanceof TimeoutException) {
System.out.println("Task timed out after 5 seconds");
future.cancel(true);
}
}
Worth knowing: future.cancel(false) completes the future as cancelled but does not interrupt the running task — the work continues in the background while callers believe it stopped. For cooperative cancellation you almost always want cancel(true).
7. Timeout and Cleanup Budgets
These are starting points, not gospel — adjust to your SLOs and what your downstream can tolerate:
| Work type | Cancellation responsiveness | Cleanup budget | Notes |
|---|---|---|---|
| HTTP request handler | < 100 ms between checkpoints | 2–5 s | Client is already gone; don’t over-invest |
| Database batch job | Each batch item | 5–10 s | Roll back or commit the current batch, don’t leave it half-written |
| Message consumer | Each message | 5 s | Let the broker redeliver rather than blocking on cleanup |
| Service shutdown (SIGTERM) | Immediate | 5–10 s, then force | Kubernetes default grace is 30 s — budget inside it |
| User-facing “cancel” button | < 500 ms perceived | 2–5 s | Confirm cancellation to the UI; clean up in background |
8. Common Mistakes
Swallowing CancelledError. Catching asyncio.CancelledError for cleanup and forgetting raise makes gather() report success for a task that was cancelled. The parent then assumes the work finished. Always re-raise after cleanup — it’s the “propagate up” half of the protocol.
Cancelling gather() tasks without return_exceptions=True. The first raised CancelledError short-circuits the gather and the remaining tasks never run their cleanup. This one ships to production constantly.
Fire-and-forget create_task without a reference. CPython may garbage-collect the task mid-run, and the GC cancels it silently. Keep a strong reference (self.tasks.add(task) in the example above isn’t decoration — it’s load-bearing).
Checking the token only once per outer iteration. If the loop body contains a long uninterruptible call — a synchronous HTTP request, a CPU-heavy computation — the task can’t observe cancellation until it returns. Bound the longest stretch between checks to your responsiveness budget.
Uncancelled context.Context in Go. WithTimeout/WithCancel spawn a timer goroutine that lives until cancel() runs. defer cancel() on entry is the idiom; skipping it leaks goroutines, and go vet will tell you.
future.cancel(false) in Java. It marks the future cancelled but leaves the thread running — the worst of both worlds. Use cancel(true) unless the task genuinely can’t respond to interrupts (e.g., blocked on uninterruptible I/O, which needs a different strategy anyway).
Cleanup that awaits the cancelled task’s own deadline. If cleanup reuses the cancelled context or signal — await fetch(url, { signal }) after abort — it fails immediately. Cleanup needs its own short timeout, not the expired token.
See Also
- Complete Guide to Python Asyncio
- Concurrency Patterns Guide
- Async Patterns with Promises, Futures, and Coroutines
- Thread-Safe Collections: Blocking Queues and Concurrent Maps
Further Reading
- asyncio — Task Cancellation — the asyncio model
- Go — context.Context — the standard cancellation contract
- Java CompletableFuture — the reference implementation
Frequently Asked Questions
What is a cancellation token and why do I need one?
A cancellation token is an object that signals when a task should stop. Without it there's no safe way to stop a long-running operation — killing threads abruptly can leave resources open, data inconsistent, and connections leaked. A token lets the task check for cancellation at safe points and perform cleanup in finally blocks or defer statements. It also supports timeouts and deadlines, so tasks auto-cancel if they run too long.
How do I handle cancellation in a pipeline of async stages?
Pass the cancellation token through every stage of the pipeline. Each stage checks the token before starting work and propagates cancellation to downstream stages. In Python, use asyncio.Task objects and cancel the root task — or better, asyncio.TaskGroup, which propagates cancellation and failure to all children automatically. In Go, pass context.Context to every function and use errgroup for the fan-out. In JavaScript, pass AbortSignal to each stage. When any stage is cancelled, all upstream and downstream stages should stop and clean up.
What happens if I don't propagate cancellation?
The task keeps running in the background, burning CPU, memory, and connections. This is called a "leaked task" or "orphaned goroutine." Over time, leaked tasks exhaust resources and cause the process to hang or crash. Always propagate cancellation — if a parent is cancelled, cancel all children. Use structured concurrency patterns (TaskGroups in Python, errgroup in Go) to ensure automatic cancellation propagation.
How long should cleanup take after cancellation?
Give cleanup a 5–10 second budget. Set a hard timeout on cleanup — if it takes longer, force-close resources. In Python, use asyncio.wait_for(cleanup(), timeout=5). In Go, use context.WithTimeout for cleanup. In JavaScript, use Promise.race([cleanup(), timeout(5000)]). If cleanup exceeds the timeout, log the issue and force-exit. Cleanup can't block forever — it would stop the process from shutting down.
Should I use cancellation or just kill the process?
Use cancellation for graceful shutdown — it allows tasks to finish current work, flush buffers, close connections, and write final state. Kill the process only as a last resort when cancellation doesn't work within a timeout. In Kubernetes, set terminationGracePeriodSeconds to 30 (default) — the pod receives SIGTERM, your code should cancel tasks and cleanup, and if it doesn't exit within 30s, Kubernetes sends SIGKILL. Always handle SIGTERM for graceful shutdown.
Does cancelling a task guarantee the underlying work stops?
No. task.cancel() and controller.abort() stop your code at the next checkpoint — they don't reach into a C-level blocking call or a remote system. An in-flight HTTP request made through fetch honors the signal because fetch is wired for it; a synchronous DNS lookup or a native library call may not. For work you don't control, the practical move is to abandon the result (check the token before using it) and put a hard timeout around the whole operation.
Related Resources
Thread Pool Sizing Template
Worksheet for documenting thread pool sizing per service: formulas, queue and rejection strategies, and monitoring for Java, Python, Go, and Node.js.
DocRace Condition Debugging Checklist
Checklist for identifying, reproducing, and fixing race conditions: symptoms, debugging tools, common patterns, and fixes with locks, atomics, and channels.
RecipeImplement Graceful Shutdown and Zero-Downtime Restarts
How to implement graceful shutdown and zero-downtime restarts for web servers, workers, and containers
GuideComplete Guide to Python Asyncio
Learn asyncio for real workloads: coroutines, tasks, event loops, cancellation, backpressure, HTTP clients, websockets, testing, debugging, and running it in production.
GuideConcurrency Patterns Guide
Production-ready concurrency patterns: thread pools, async/await, producer-consumer, semaphores, actors, circuit breakers in Python, Java, JS, Go, Elixir.