Tokio / Chapter 6 of 6
Patterns, pitfalls, and feature flags
Avoid blocking the Tokio runtime, holding locks across await, and leaking tasks. Look up feature flags and async Rust patterns.
2 topicsUpdated
25 / 26
Patterns and common mistakes#
Use this table when choosing a primitive or diagnosing a stalled program.
| Need | Use | Remember |
|---|---|---|
| Two async operations, both results | join! / try_join! | Concurrency within one task; no new task created |
| Independent task with a result | spawn + JoinHandle | Own its inputs; handle panic or cancellation |
| Many tasks with cleanup | JoinSet | Drain results; drop aborts remaining tasks |
| Queue jobs with backpressure | bounded mpsc | Drop all senders to close the stream |
| One reply | oneshot | Sender is synchronous; receiver awaits |
| Latest state / all events | watch / broadcast | watch coalesces; broadcast can lag |
| Short shared mutation | Arc<std::sync::Mutex<T>> | Release guard before .await |
| Many network requests with a cap | Semaphore | Own permits in tasks; drop releases |
| Multiple shutdown listeners | CancellationToken | Cancel, then wait for tasks |
- “Cannot borrow across .await”: shorten the borrow or move owned data into the future.
- “Future is not Send”: a non-Send value, such as an
Rcor guard, is live across an await in a spawned task. - “No reactor running”: a Tokio timer or socket was created or polled outside a runtime.
- Hung channel receiver: an extra sender is still alive, so the channel has not closed.
- Slow tasks despite async: check for blocking work, unbounded concurrency, or locks held around I/O.
26 / 26
Feature flags and further reading#
Tokio modules and the Cargo features they require.
| Module / crate | Purpose | Relevant feature |
|---|---|---|
tokio::task | spawn, JoinSet, spawn_blocking, LocalSet | rt / rt-multi-thread |
tokio::sync | channels, Mutex, RwLock, Semaphore, Notify | sync |
tokio::time | sleep, interval, timeout | time |
tokio::io | AsyncRead/AsyncWrite helpers | io-util |
tokio::net | TCP, UDP, Unix sockets | net |
tokio::fs, process, signal | files, children, OS signals | matching feature name |
#[tokio::main], #[tokio::test] | runtime entry points | macros |
tokio::time::advance | virtual-time tests | test-util |
tokio-util::sync::CancellationToken | cooperative cancellation | tokio-util/rt |
Use features = ["full"] for learning; limit features for a smaller dependency graph later. Tokio itself does not provide HTTP routing or a database driver. Choose separate crates for those layers. The official Tokio tutorial, Tokio API reference, and shutdown guide are the primary references for edge cases.
Help improve CodeRef
Allow Google Analytics to measure page visits and use of the guides? It uses cookies after you accept. Your choice won’t affect access to the site. Privacy notice