Timeouts and graceful shutdown
Quick answer
A timeout bounds how long a caller waits for an asynchronous operation, provided the operation yields. Graceful shutdown stops accepting work, signals active workers and waits for cleanup under an explicit policy.
Separate a deadline from cleanup
tokio::time::timeout returns an error when the future exceeds the duration; it cannot preempt a poll that never yields. Dropping the timed future is not necessarily cancellation of a spawned task or rollback of I/O. For shutdown, coordinate a stop signal, close inputs, drain accepted work if required and join the workers. Define how to handle a worker that exceeds the shutdown budget.
#[tokio::main(flavor = "current_thread")]async fn main() { let result = tokio::time::timeout(std::time::Duration::from_millis(5), std::future::pending::<()>()).await; println!("timed out: {}", result.is_err());}Manual local Rust/Cargo candidate; not executed. Expected behavior:
timed out: true; elapsed time varies.The inner future never finishes; the timer determines the result.
#[tokio::main(flavor = "current_thread")]async fn main() { let (tx, mut rx) = tokio::sync::mpsc::channel(2); let worker = tokio::spawn(async move { let mut sum = 0; while let Some(n) = rx.recv().await { sum += n; } sum }); tx.send(2).await.unwrap(); tx.send(3).await.unwrap(); drop(tx); println!("drained: {}", worker.await.unwrap());}Manual local Rust/Cargo candidate; not executed. Expected behavior:
drained: 5Closing the last sender signals end-of-input; the worker drains accepted messages.
Common mistake
Do not detach a worker and declare shutdown complete without accounting for its resources.
Try it yourself
Sketch a shutdown sequence with a separate deadline, a drain phase and an escalation policy.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Timeouts and graceful shutdown — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A timed future performs CPU work without yielding. Will Tokio timeout reliably interrupt it at the exact deadline?
Timeouts and graceful shutdown — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust #[tokio::main(flavor = "current_thread")] async fn main() { let result = tokio::time::timeout(std::time::Duration::from_millis(5), std::future::pending::<()>()).await; println!("timed out: {}", result.is_err()); } ``` Which outcome or interpretation best matches this example?
Timeouts and graceful shutdown — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust #[tokio::main(flavor = "current_thread")] async fn main() { let (tx, mut rx) = tokio::sync::mpsc::channel(2); let worker = tokio::spawn(async move { let mut sum = 0; while let Some(n) = rx.recv().await { sum += n; } sum }); tx.send(2).await.unwrap(); tx.send(3).await.unwrap(); drop(tx); println!("drained: {}", worker.await.unwrap()); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.