Lesson 4 of 9 · 26m
Channels, Queues, and Backpressure That Actually Works
Choose between mpsc, broadcast, watch, and oneshot channels while making capacity, loss, and queue growth explicit.
Every production async system eventually becomes a queueing system whether you design it or not. The only question is whether the queues are visible, bounded, and measured. Tokio channels are excellent tools, but they do not create backpressure by magic. Capacity policy is application design.
Pick the channel by delivery semantics
Tokio's channels solve different problems:
mpsc many producers to one consumer, each item delivered once
broadcast many receivers each see items after subscribing, with lag policy
watch receivers care about the latest value, not every update
oneshot exactly one response sent to exactly one receiverIf you choose by habit, you inherit semantics you did not intend. broadcast is not a work queue. watch is not an event log. mpsc does not distribute work across multiple consumers unless you add a dispatcher or multiple clones around shared state.
Unbounded channels hide memory exhaustion
An unbounded mpsc channel is tempting because producers never wait. It removes producer waiting, which means overload moves into heap growth. During a downstream outage, messages accumulate silently until the process is killed. Bounded channels make the pressure visible at the producer:
let (tx, mut rx) = tokio::sync::mpsc::channel(1_024);
tx.send(job).await?; // waits when the consumer cannot keep upThat wait is backpressure. It propagates load upstream instead of pretending the work disappeared.
Sometimes waiting is the wrong policy
Metrics sampling, cache invalidation hints, and best-effort notifications may prefer dropping over blocking:
match tx.try_send(metric) {
Ok(()) => {}
Err(TrySendError::Full(_)) => dropped_metrics.fetch_add(1, Ordering::Relaxed),
Err(TrySendError::Closed(_)) => return,
}The important part is not try_send; it is the explicit decision. Can this item be dropped? Must it be retried? Does ordering matter? Is a full queue a signal to shed load, reject the request, or wait? Make the caller-visible behavior match the business meaning.
Channel closure is part of the protocol
When the last sender drops, receivers eventually observe None or a closed error. When the receiver drops, senders fail. Use that shutdown signal deliberately:
while let Some(job) = rx.recv().await {
process(job).await;
}
tracing::info!("job channel closed; worker exiting");A common bug is keeping an extra tx clone alive in a struct, causing the consumer to wait forever during shutdown. Another is cloning senders into tasks without tracking who owns the canonical shutdown copy.
Field notes
- A channel capacity of 10,000 is not backpressure if the process dies at 2,000; capacity must reflect memory and latency budgets.
- Count sends, receives, drops, and queue depth. Queue depth is the metric operators actually need.
Was this lesson helpful?