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.

NeedUseRemember
Two async operations, both resultsjoin! / try_join!Concurrency within one task; no new task created
Independent task with a resultspawn + JoinHandleOwn its inputs; handle panic or cancellation
Many tasks with cleanupJoinSetDrain results; drop aborts remaining tasks
Queue jobs with backpressurebounded mpscDrop all senders to close the stream
One replyoneshotSender is synchronous; receiver awaits
Latest state / all eventswatch / broadcastwatch coalesces; broadcast can lag
Short shared mutationArc<std::sync::Mutex<T>>Release guard before .await
Many network requests with a capSemaphoreOwn permits in tasks; drop releases
Multiple shutdown listenersCancellationTokenCancel, then wait for tasks
26 / 26

Feature flags and further reading#

Tokio modules and the Cargo features they require.

Module / cratePurposeRelevant feature
tokio::taskspawn, JoinSet, spawn_blocking, LocalSetrt / rt-multi-thread
tokio::syncchannels, Mutex, RwLock, Semaphore, Notifysync
tokio::timesleep, interval, timeouttime
tokio::ioAsyncRead/AsyncWrite helpersio-util
tokio::netTCP, UDP, Unix socketsnet
tokio::fs, process, signalfiles, children, OS signalsmatching feature name
#[tokio::main], #[tokio::test]runtime entry pointsmacros
tokio::time::advancevirtual-time teststest-util
tokio-util::sync::CancellationTokencooperative cancellationtokio-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.