Cancellation and Graceful Shutdown
local graph
Chapter 20 — Cancellation and Graceful Shutdown
Section titled “Chapter 20 — Cancellation and Graceful Shutdown”Finis coronat opus. (The end crowns the work.)
Concurrent programs do not run indefinitely. Servers receive shutdown signals. Users cancel long-running operations. Timeouts fire. Network connections drop. The question is not whether cancellation will occur but how the program responds when it does. An application that ignores cancellation requests consumes resources endlessly, like a restaurant kitchen that keeps cooking after the customers have left. One that terminates abruptly corrupts state, loses data, leaks connections. The difference between a system that handles cancellation gracefully and one that does not shows in production when operators need to deploy updates, when users abandon slow requests, when dependent services become unavailable.
The challenge intensifies in async systems. An awaiting task can be cancelled at any suspension point. The future that was polling network data vanishes. The half-written transaction hangs incomplete. In languages with garbage collection and finalizers, cleanup might eventually happen through finalizer threads that run at indeterminate times. In Rust, where destruction is deterministic and resources release when values drop, cancellation interacts with ownership in ways that require deliberate design. The same mechanisms that make Rust memory-safe require thought when applied to concurrent cancellation.
OOP languages approach this problem through exception-based interruption (Java’s InterruptedException), cooperative checking (polling a cancellation flag), or both. These mechanisms work but carry limitations. Exceptions can be caught and suppressed. A library that catches and ignores InterruptedException defeats the entire interruption mechanism, and such libraries exist in production written by developers who presumably had reasons that seemed valid at the time. Flags require explicit checking at every potentially long operation; miss one check, and the task runs longer than intended. Neither integrates naturally with async execution where suspension points are implicit. Rust’s approach, building cancellation into the future model itself, offers different trade-offs worth understanding.
The cancellation problem
Consider a task that processes items from a queue, running until the queue empties. The task is straightforward in isolation: receive item, process item, repeat. When shutdown arrives, several things should happen in proper sequence. The task should finish processing its current item to avoid partial state updates or half-completed operations. It should stop accepting new items so the queue can drain. It should release any resources it holds (database connections, file handles, network sockets). It should signal completion so dependent tasks can proceed with their own shutdown. Without explicit cancellation handling, the task continues until the channel closes. If the channel has many pending items, shutdown waits indefinitely. If the task holds database connections or file handles, those remain occupied, potentially blocking other systems.
The same problem appears in request handling, often more acutely. A request handler might fetch data from a database, perform expensive computation on that data, then call an external API to enrich the result. If the client disconnects after the database fetch but before the API call, continuing the work wastes resources. The response will never be sent because no client awaits it. The external API call is pointless.
The computation cycles are lost. In a system handling thousands of requests per second, this waste accumulates. Each abandoned request that continues to completion consumes CPU, memory, network bandwidth, and external service quota that could serve actual users.
Cancellation propagation raises additional concerns that become apparent in real systems. When a parent task spawns children, cancelling the parent should (in most designs) cancel the children. A cancelled database query should not leave orphaned network connections waiting for responses that will never matter. A cancelled file upload should not leave partial files consuming disk space indefinitely. The relationships between tasks create graphs that cancellation must traverse correctly. Parent-child relationships seem obvious, but real systems have more complex topologies: tasks that share resources, tasks that communicate through channels, tasks that have timeouts independent of their parent’s cancellation.
The following diagram illustrates task hierarchies that cancellation must handle:
graph TD
C(("Cancel")) -. propagates .-> RH
subgraph PT["Parent Task"]
RH["Request Handler"]
end
subgraph CT["Child Tasks"]
DB["Database Query"]
CL["Cache Lookup"]
API["API Call"]
end
RH --> DB
RH --> CL
RH --> API
[!visual-conversion] Cancellation propagating through task hierarchy. Print diagram (PDF 516, printed p. 508) recreated in Mermaid; labels verbatim, “propagates” edge dotted in print. The print draws a return arrow from each child back to the handler as well; these are omitted as unlabeled duplicates of the same relation.
Cancellation in async Rust
Rust’s async model makes cancellation implicit rather than explicit. Dropping a future cancels it. This design choice reflects Rust’s broader philosophy: resource management through ownership and deterministic destruction through Drop. When a future goes out of scope without completing, its destructor runs, cleaning up any state the future held.
The mechanics differ depending on how the future was spawned. When a JoinHandle is dropped without being awaited, the spawned task continues running independently. The task was given to the executor when spawned; dropping the handle abandons the ability to await its result but does not affect execution. However, when a future that has not been spawned is dropped, its execution stops at its current await point. The future was being driven by something (perhaps select! or join!) that no longer needs its result. Dropping the future drops any values it holds, running their destructors.
This implicit cancellation has consequences that surprise developers coming from other async systems. A dropped future cannot run code after its last await point. Consider the pattern: acquire resource, perform operation, release resource. In synchronous code, RAII handles this naturally. The resource’s Drop runs when the scope ends, regardless of how control leaves the scope. In async code, if the operation awaits and is cancelled during that await, control never reaches the release code that follows.
async fn problematic_cleanup() { let resource = acquire_resource().await;
// If cancelled during this await, cleanup below never runs let result = long_operation().await; release_resource(resource).await; // May not execute}The Drop trait runs synchronously; it cannot await async cleanup operations. If long_operation is cancelled mid-execution, the synchronous Drop for resource runs, but the async release_resource call never executes. For resources that require only synchronous cleanup, this is fine. For resources that need async cleanup (sending a message to a server, writing to a database, coordinating with other tasks), implicit cancellation leaves cleanup incomplete.
Several patterns address this asymmetry between sync and async cleanup. Structured cleanup uses RAII by wrapping resources in types whose Drop implementations handle synchronous cleanup or delegate to cleanup tasks:
struct ResourceGuard { resource: Option<Resource>, cleanup_tx: mpsc::Sender<Resource>,}
impl Drop for ResourceGuard { fn drop(&mut self) { if let Some(resource) = self.resource.take() { let _ = self.cleanup_tx.try_send(resource); } }}The guard sends resources to a dedicated cleanup task through a channel. The cleanup task can perform async operations at its own pace. The pattern requires infrastructure (a long-running cleanup task and a channel to communicate with it) but ensures async cleanup happens even under cancellation. The try_send avoids blocking in the destructor; if the channel is full, cleanup may not happen, which is a trade-off the design must account for.
Alternatively, tokio::select! with cancellation branches makes cancellation explicit rather than relying on drop:
async fn cancellable_operation(cancel: CancellationToken) { let resource = acquire_resource().await;
tokio::select! { result = long_operation() => process_result(result), _ = cancel.cancelled() => println!("Cancelled, cleaning up"), }
release_resource(resource).await; // Runs regardless of branch}The cleanup runs after the select completes, whether from normal completion or cancellation. The cancellation becomes a cooperative checkpoint: the task explicitly checks for cancellation at a controlled point and ensures cleanup runs after that point. This explicit approach trades the conciseness of implicit cancellation for predictable cleanup behavior. The function advertises (through its CancellationToken parameter) that it supports cooperative cancellation.
Cancellation tokens
Section titled “Cancellation tokens”The tokio-util crate provides CancellationToken, a synchronization primitive designed for signaling cancellation across tasks. A token can be cloned and distributed to multiple tasks; when cancelled, all holders observe the cancellation. The pattern resembles .NET’s CancellationTokenSource and CancellationToken, bringing familiar semantics to Rust’s ownership model.
The CancellationToken is thread-safe (Send and Sync) and cheap to clone because it wraps an Arc internally. Multiple tasks can hold clones of the same token. When any holder calls cancel (), all clones observe the cancellation. The cancelled () method returns a future that resolves when cancellation occurs; tasks typically select between their main work and this cancellation future.
Creating a token and sharing it across workers follows a straightforward pattern. The coordinator creates a token, clones it for each worker, and spawns the workers with their clones. Each worker checks for cancellation in its main loop using select!. The worker either completes a unit of work or observes cancellation, whichever comes first. When the coordinator calls cancel () on the original token, all cancelled () futures resolve immediately. Workers exit their loops, perform any necessary cleanup, and terminate. The coordinator waits for all workers to complete cleanly before proceeding.
async fn worker(id: usize, cancel: CancellationToken) { loop { tokio::select! { _ = do_work(id) => println!("Worker {} completed work", id), _ = cancel.cancelled() => { println!("Worker {} shutting down", id); break; } } }}Child tokens enable hierarchical cancellation. Calling child_token () on a parent creates a linked token. Cancelling the parent automatically cancels all children. However, cancelling a child does not affect the parent or siblings. This asymmetry is intentional and useful: a request handler creates child tokens for sub-operations, and cancelling the request cancels all its operations, but a sub-operation can fail (and cancel its children) without affecting siblings or the parent.
The following pattern structures cancellation through service layers:
graph TD
subgraph APP["Application"]
RT["Root Token"]
end
subgraph SV["Services"]
HS["HTTP Server<br/>(child token)"]
BG["Background Tasks<br/>(child token)"]
end
subgraph RQ["Requests"]
R1["Request 1"]
R2["Request 2"]
end
RT -- "cancel()" --> HS
RT -- "cancel()" --> BG
HS --> R1
HS --> R2
[!visual-conversion] Token hierarchy for structured cancellation. Print diagram (PDF 521, printed p. 513) recreated in Mermaid; labels verbatim. Both request arrows originate at HTTP Server in print.
Cancellation tokens integrate naturally with Rust’s ownership model. Passing tokens to spawned tasks requires no special handling because tokens are Send and Sync. The token becomes another parameter in the concurrent API, making cancellation capability explicit in function signatures. A function that accepts a CancellationToken advertises its ability to be cancelled cooperatively. A function that does not accept a token either cannot be cancelled or uses some other mechanism.
The explicit nature of token-based cancellation has documentation value. When reading code, the presence of a cancellation token parameter indicates where cancellation can occur and how it propagates. When writing code, the need to pass tokens forces consideration of cancellation at design time rather than as an afterthought. I have found this explicitness valuable in complex systems where understanding cancellation flow is essential for reasoning about behavior under failure.
Structured concurrency
Structured concurrency constrains when child tasks can execute relative to their parent. The concept addresses a fundamental tension in concurrent programming: tasks need independence to run concurrently, but unrestricted independence makes reasoning about program behavior difficult. In unstructured concurrency (the default with tokio::spawn), spawned tasks outlive their spawning scope. A function can spawn tasks that continue running after the function returns. This flexibility enables useful patterns like fire-and-forget background work, but it complicates reasoning about lifetimes, cleanup, and error handling.
Structured concurrency enforces that child tasks complete before their parent scope exits. The constraint mirrors how structured programming constrains control flow: a function cannot return while still executing code inside it. This guarantee simplifies several aspects of concurrent programming. Cancellation becomes straightforward: cancelling a scope cancels all tasks within it, and no orphaned tasks continue running. Resource management aligns with scopes: resources released when the scope ends are guaranteed not to be in use by child tasks. Error handling improves: errors from child tasks can be collected and reported because all children complete before the parent.
The JoinSet type provides structured concurrency for dynamic task sets in Tokio. Unlike spawning tasks individually with tokio::spawn, tasks spawned into a JoinSet are tracked collectively:
async fn process_items(items: Vec<Item>) -> Vec<ProcessedItem> { let mut set = JoinSet::new();
for item in items { set.spawn(async move { process_one(item).await }); }
let mut results = Vec::new(); while let Some(result) = set.join_next().await { if let Ok(processed) = result { results.push(processed); } } results}When the JoinSet drops, it aborts all tasks that have not yet completed. The scope cannot exit with tasks still running. This behavior differs fundamentally from bare tokio::spawn, where the spawned task continues independently of its handle.
For tighter control, JoinSet::shutdown() signals all tasks to stop and waits for completion. Combined with timeouts, this enables patterns like processing items with an overall deadline:
async fn with_timeout(items: Vec<Item>, deadline: Duration) -> Vec<ProcessedItem> { let mut set = JoinSet::new(); for item in items { set.spawn(async move { process_one(item).await }); }
match timeout(deadline, collect_all(&mut set)).await { Ok(results) => results, Err(_) => { set.shutdown().await; // Abort remaining, wait for cleanup vec![] } }}The async-scoped crate provides scope-based structured concurrency that allows borrowing from the parent scope. Normal tokio::spawn requires ‘static data because the spawned task might outlive any borrowed data. The compiler cannot verify that borrowed data remains valid for the task’s entire lifetime. Scoped spawning provides a guarantee: all spawned tasks complete before the scope returns. This guarantee enables safe borrowing into tasks. The pattern is particularly valuable when parallelizing operations over slices or iterators without moving data into each task.
Structured concurrency trades flexibility for predictability. Fire-and-forget patterns become impossible or require explicit opt-out. Background tasks that should outlive their spawning context require architectural changes (perhaps spawning them from a longer-lived scope or using unstructured spawning deliberately). In exchange, the relationships between tasks become clearer, cancellation propagates naturally through the task tree, and resource lifetimes align with execution lifetimes. I have found these constraints often improve designs by forcing explicit decisions about task relationships rather than leaving them implicit.
Timeout patterns
Timeouts are a specific form of cancellation triggered by elapsed time rather than explicit signals. They serve multiple purposes in concurrent systems. They prevent unbounded waits that could exhaust resources or hang indefinitely. They enforce service-level objectives (if a request cannot complete in 30 seconds, fail it rather than making the client wait). They provide recovery from stuck operations (a network call that will never complete, a database query that blocked on a lock).
Tokio provides timeout utilities that integrate with the async model. The basic timeout wraps a future, returning an error if the future does not complete within the specified duration:
async fn fetch_with_timeout(url: &str) -> Result<Response, Error> { match timeout(Duration::from_secs(10), fetch(url)).await { Ok(Ok(response)) => Ok(response), Ok(Err(e)) => Err(Error::Fetch(e)), Err(_) => Err(Error::Timeout), }}The nested Result structure deserves attention. The outer Result indicates whether the timeout elapsed: Ok means the inner future completed (successfully or with its own error), Err means the timeout expired. The inner Result is whatever the wrapped future returns. This nesting distinguishes “the operation failed” from “the operation took too long,” which often warrant different handling strategies.
When the timeout triggers, the inner future is dropped, cancelling it at its current await point. This implicit cancellation inherits all the considerations discussed earlier: synchronous cleanup runs, async cleanup after the cancellation point does not. For operations that need cleanup under timeout, the patterns discussed (cleanup tasks, explicit cancellation branches) apply.
Layered timeouts apply different limits to different operation levels. A request handler might have an overall 30-second limit, while individual operations have shorter individual limits:
async fn handle_request(request: Request) -> Result<Response, Error> { timeout(Duration::from_secs(30), async { let data = timeout(Duration::from_secs(5), database_query(&request)).await??; let processed = timeout(Duration::from_secs(10), process(data)).await??; let enriched = timeout(Duration::from_secs(15), external_api(processed)).await??; Ok(format_response(enriched)) }).await?}Each operation has its own timeout, and cumulative time is bounded by the outer limit. If the database takes 4 seconds and processing takes 9 seconds, only 17 seconds remain for the API call despite its 15-second individual limit.
Deadline-based timeouts work better for cumulative limits. Rather than specifying individual durations, all operations share a single deadline instant. The timeout_at function accepts an Instant rather than a Duration:
async fn handle_with_deadline(request: Request) -> Result<Response, Error> { let deadline = Instant::now() + Duration::from_secs(30);
let data = timeout_at(deadline, database_query(&request)).await??; let processed = timeout_at(deadline, process(data)).await??; let enriched = timeout_at(deadline, external_api(processed)).await??;
Ok(format_response(enriched))}As time passes, remaining operations have less time regardless of their individual expectations. This approach prevents cumulative timeouts from exceeding the intended total and makes budget exhaustion explicit.
Retry with timeout handles transient failures while respecting time bounds. The pattern balances resilience (retrying failures that might succeed on another attempt) with bounded resource consumption (not retrying forever):
async fn fetch_with_retry( url: &str, max_attempts: u32, total_deadline: Instant,) -> Result<Response, Error> { let mut attempts = 0;
loop { attempts += 1; let remaining = total_deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() { return Err(Error::TotalTimeout); }
match timeout(remaining.min(Duration::from_secs(10)), fetch(url)).await { Ok(Ok(response)) => return Ok(response), _ if attempts >= max_attempts => return Err(Error::MaxRetries), _ => { sleep(Duration::from_millis(100 * attempts as u64)).await; } } }}Each attempt uses the minimum of a per-attempt timeout and the remaining deadline. Backoff between attempts prevents overwhelming a struggling service. The loop continues until success, exhausted attempts, or deadline expiration.
Graceful shutdown orchestration
Production services require graceful shutdown: stopping work in an orderly manner, completing in-flight operations, releasing resources, and exiting cleanly. The alternative, abrupt termination, creates problems that compound in distributed systems. A database transaction interrupted mid-commit leaves data inconsistent. A file write truncated leaves corrupt data. A client request abandoned mid-response leaves the client confused about whether its operation succeeded. These failures create work for operators, erode trust in the system, and sometimes cause cascading failures in dependent services.
Graceful shutdown orchestrates multiple concerns that must happen in proper sequence. Signal handling catches operating system signals (SIGTERM, SIGINT) that indicate shutdown is requested. Drain periods allow in-flight requests to complete while rejecting new ones (load balancers can be notified to stop sending traffic). Cleanup routines flush buffers, close connections, notify external systems, and release resources. Timeout limits prevent stuck operations from blocking shutdown indefinitely (at some point, the process must exit even if some work is incomplete).
The following diagram shows a typical shutdown sequence:
graph TD
A["Shutdown Signal<br/>(SIGTERM/SIGINT)"] --> B["Stop Accepting<br/>New Work"] --> C["Wait for In-Flight<br/>(with timeout)"] --> D["Cleanup<br/>Resources"] --> E["Exit Process"]
[!visual-conversion] Graceful shutdown phases. Print flowchart (PDF 528, printed p. 520) recreated in Mermaid; labels verbatim. (The OCR had looped on this figure ~300 times; the page’s prose was intact.)
Tokio provides signal handling through tokio::signal. A shutdown signal handler awaits either Ctrl+C or SIGTERM (on Unix), returning when shutdown should begin. Platform differences require conditional compilation: Unix systems have SIGTERM while Windows uses different mechanisms:
async fn shutdown_signal() { let ctrl_c = async { signal::ctrl_c().await.expect("Failed to install Ctrl+C handler"); };
#[cfg(unix)] let terminate = async { signal::unix::signal(signal::unix::SignalKind::terminate()) .expect("Failed to install SIGTERM handler") .recv() .await; };
#[cfg(not(unix))] let terminate = std::future::pending::<()>();
tokio::select! { _ = ctrl_c => {}, _ = terminate => {}, }}The handler becomes the entry point to the shutdown sequence. When it returns, the main function knows shutdown was requested and can begin orchestration.
A shutdown coordinator combines signals, cancellation tokens, and timeouts into a coherent mechanism. The coordinator owns a root cancellation token and potentially a broadcast channel for shutdown notifications:
struct ShutdownCoordinator { cancel: CancellationToken, notify: broadcast::Sender<()>,}
impl ShutdownCoordinator { fn new() -> Self { let (notify, _) = broadcast::channel(1); ShutdownCoordinator { cancel: CancellationToken::new(), notify, } }
fn token(&self) -> CancellationToken { self.cancel.clone() }
async fn shutdown(&self, grace_period: Duration) { self.cancel.cancel(); let _ = self.notify.send(()); sleep(grace_period).await; }}Services use the coordinator to participate in shutdown. A server’s main loop uses select! to accept new connections while watching for cancellation:
async fn run_server(addr: SocketAddr, shutdown: CancellationToken) -> Result<(), Error> { let listener = TcpListener::bind(addr).await?;
loop { tokio::select! { result = listener.accept() => { let (socket, _) = result?; let shutdown = shutdown.clone(); tokio::spawn(handle_connection(socket, shutdown)); } _ = shutdown.cancelled() => { println!("Server stopping"); break; } } } Ok(())}When cancelled, the server stops accepting new connections. Existing connection handlers continue until they observe cancellation or complete naturally. The grace period allows handlers to finish their current work before the final timeout.
Bringing it together, the main function orchestrates the complete lifecycle:
#[tokio::main]async fn main() { let coordinator = ShutdownCoordinator::new();
let server = tokio::spawn(run_server("0.0.0.0:8080".parse().unwrap(),coordinator.token())); let worker = tokio::spawn(background_worker(coordinator.token()));
shutdown_signal().await; println!("Shutdown signal received");
coordinator.shutdown(Duration::from_secs(30)).await;
let _ = timeout(Duration::from_secs(5), server).await; let _ = timeout(Duration::from_secs(5), worker).await;
println!("Shutdown complete");}The orchestration provides ordered shutdown: signal reception, cancellation propagation, grace period, and timeout. Services that cooperate shut down cleanly. Services that hang are abandoned after the timeout, allowing the process to exit. The final timeouts ensure the process terminates even if some tasks are stuck.
In my experience, graceful shutdown receives insufficient attention during development. The happy path works: the application handles requests, processes data, responds to users. But termination is rarely tested. Applications misbehave under shutdown: they hang indefinitely, they corrupt data, they leave external systems in inconsistent states. Testing shutdown requires specific scenarios that normal development does not exercise. Kill the process during database transactions. Disconnect networks mid-request. Exhaust the grace period with slow operations. These tests reveal issues that normal operation never triggers. Investing in shutdown testing, while unglamorous, pays dividends in production reliability. When operators need to deploy updates, when the orchestrator needs to reschedule containers, when the hardware needs maintenance, graceful shutdown is the difference between a routine operation and an incident.
Complete example: task processing service
The following example combines the patterns discussed into a task processing service that demonstrates cancellation tokens, structured concurrency, timeouts, and graceful shutdown working together.
use std::time::Duration;use tokio::sync::mpsc;use tokio::time::{timeout, Instant};use tokio_util::sync::CancellationToken;
struct TaskProcessor { shutdown: CancellationToken, task_rx: mpsc::Receiver<Task>, result_tx: mpsc::Sender<TaskResult>,}
#[derive(Debug)]struct Task { id: u64, payload: String, deadline: Instant,}
#[derive(Debug)]struct TaskResult { task_id: u64, status: TaskStatus,}
#[derive(Debug)]enum TaskStatus { Completed(String), Timeout, Cancelled,}
impl TaskProcessor { async fn run(mut self) { loop { tokio::select! { biased;
_ = self.shutdown.cancelled() => { println!("Processor received shutdown signal"); break; }
task = self.task_rx.recv() => { match task { Some(task) => self.process_task(task).await, None => break, } } } }
self.drain_remaining().await; println!("Processor shutdown complete"); }
async fn process_task(&self, task: Task) { let task_id = task.id; let remaining = task.deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() { let _ = self.result_tx.send(TaskResult { task_id, status: TaskStatus::Timeout, }).await; return; }
let process_future = async { tokio::time::sleep(Duration::from_millis(50)).await; format!("Processed: {}", task.payload) };
let status = tokio::select! { _ = self.shutdown.cancelled() => TaskStatus::Cancelled, result = timeout(remaining, process_future) => { match result { Ok(output) => TaskStatus::Completed(output), Err(_) => TaskStatus::Timeout, } } };
let _ = self.result_tx.send(TaskResult { task_id, status }).await; }
async fn drain_remaining(&mut self) { let drain_deadline = Instant::now() + Duration::from_secs(5);
while let Ok(task) = timeout( drain_deadline.saturating_duration_since(Instant::now()), self.task_rx.recv() ).await { match task { Some(task) => { let _ = self.result_tx.send(TaskResult { task_id: task.id, status: TaskStatus::Cancelled, }).await; } None => break, } } }}
async fn result_collector( mut result_rx: mpsc::Receiver<TaskResult>, shutdown: CancellationToken,) { let mut completed = 0; let mut cancelled = 0; let mut timed_out = 0;
loop { tokio::select! { _ = shutdown.cancelled() => break, result = result_rx.recv() => { match result { Some(r) => { match &r.status { TaskStatus::Completed(_) => completed += 1, TaskStatus::Cancelled => cancelled += 1, TaskStatus::Timeout => timed_out += 1, } println!("Task {}: {:?}", r.task_id, r.status); } None => break, } } } }
println!( "Results: {} completed, {} cancelled, {} timed out", completed, cancelled, timed_out );}
#[tokio::main]async fn main() { let shutdown = CancellationToken::new(); let (task_tx, task_rx) = mpsc::channel(100); let (result_tx, result_rx) = mpsc::channel(100);
let processor = TaskProcessor { shutdown: shutdown.child_token(), task_rx, result_tx, };
let processor_handle = tokio::spawn(processor.run()); let collector_handle = tokio::spawn(result_collector(result_rx,shutdown.child_token()));
for i in 0..20 { let deadline = Instant::now() + Duration::from_millis(200); let task = Task { id: i, payload: format!("Task payload {}", i), deadline, }; task_tx.send(task).await.unwrap(); }
tokio::time::sleep(Duration::from_millis(300)).await; println!("Initiating shutdown"); shutdown.cancel(); drop(task_tx);
let _ = timeout(Duration::from_secs(10), processor_handle).await; let _ = timeout(Duration::from_secs(10), collector_handle).await;
println!("Service shutdown complete");}The TaskProcessor demonstrates several key patterns. The main loop uses biased select! to prioritize checking for shutdown before processing new tasks. Each task processes within its own deadline: process_task converts the deadline into the remaining Duration and passes it to timeout. When shutdown occurs, the processor drains remaining tasks, marking them cancelled rather than dropping them silently.
The result_collector aggregates outcomes, continuing until shutdown is signaled. Child tokens for both processor and collector ensure they observe the parent’s cancellation. The main function orchestrates startup, work submission, shutdown signaling, and final cleanup with timeouts.
This structure handles multiple scenarios correctly. Normal operation processes tasks and collects results. Shutdown during processing cancels the task in flight (reporting it as Cancelled) and then drains the remaining queued tasks, also marked Cancelled. Timeouts expire individual tasks without affecting others. The final timeout on handles prevents hung workers from blocking process exit. Running this example and interrupting it at different points demonstrates how the cancellation flows through the system.
Graceful Endings
Cancellation in concurrent systems requires explicit design. The problem cannot be ignored and does not solve itself. Tasks must observe cancellation signals and respond appropriately. Resources must be cleaned up even when operations are interrupted mid-execution.
Rust’s async model makes cancellation implicit through future dropping. When a future is dropped, it stops executing and its destructor runs. This simplicity has consequences: cleanup code after await points may not execute because async cleanup requires awaiting, which cannot happen in a destructor. Patterns like cancellation tokens, cleanup tasks, and structured cleanup address these limitations by making cancellation cooperative rather than abrupt.
Cancellation tokens provide explicit coordination across tasks. A token can be cloned and distributed; when cancelled, all holders observe the cancellation. Parent tokens propagate cancellation to children. Token hierarchies mirror task hierarchies, enabling organized shutdown of complex systems where cancellation flows from coordinators to workers.
Structured concurrency constrains child task lifetimes to parent scopes. JoinSet collects dynamic task sets with automatic cancellation on drop. Scoped spawning enables borrowing into tasks when lifetime guarantees hold. These constraints trade flexibility for predictability, making concurrent programs easier to reason about.
Timeouts apply time-based cancellation to bound the duration of operations. Layered timeouts limit individual operations while deadline-based timeouts enforce cumulative limits. Retry patterns combine timeouts with resilience for handling transient failures.
Graceful shutdown orchestrates ordered termination of concurrent systems. Signal handling detects shutdown requests. Cancellation tokens propagate through task hierarchies. Grace periods allow in-flight work to complete. Final timeouts prevent hung tasks from blocking process exit. The orchestration transforms shutdown from an abrupt termination into a controlled process.
The next chapter explores concurrent data structures: lock-free collections, atomic operations, and the patterns that enable safe concurrent access without mutex overhead.