Sub topic 11
Bounded channels and backpressure
This chapter assumes you can spawn and join threads, use mpsc::channel with Sender and Receiver, and know that a receiving loop ends once every sender is dropped. It builds on the earlier chapters on channel closing and on handling send errors.
The problem with unbounded channels
mpsc::channel() creates an unbounded channel. send never blocks, because the channel grows its internal queue as needed. That is convenient, but it hides a failure mode. If a producer is faster than its consumer, the queue grows without limit. Memory use climbs until the process slows down or is killed. Nothing in the program tells the producer to slow down.
Backpressure is the fix. It means the slow side of a pipeline pushes back on the fast side. In Rust's standard library, the tool for this is std::sync::mpsc::sync_channel, which creates a bounded channel with a fixed capacity.
Creating a bounded channel
sync_channel(n) returns a (SyncSender<T>, Receiver<T>) pair. The receiver is the same Receiver type you already know. The sender is a different type, SyncSender, whose send blocks when the buffer holds n messages.
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::sync_channel::<u32>(2);
let producer = thread::spawn(move || {
for i in 0..5 {
tx.send(i).unwrap();
}
});
let got: Vec<u32> = rx.iter().collect();
producer.join().unwrap();
assert_eq!(got, vec![0, 1, 2, 3, 4]);
println!("{got:?}");
}The output is always [0, 1, 2, 3, 4]. Capacity changes timing, not ordering or delivery. When the producer has queued two messages that the consumer has not taken yet, the third send blocks. It resumes as soon as the consumer frees a slot.
Watching backpressure happen
A slow consumer makes the effect visible. In this program the consumer takes 100 ms per message, and the producer prints after each successful send.
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
fn main() {
let (tx, rx) = mpsc::sync_channel::<u32>(2);
let producer = thread::spawn(move || {
for i in 0..6 {
tx.send(i).unwrap();
println!("sent {i}");
}
});
for v in rx {
thread::sleep(Duration::from_millis(100));
println!("handled {v}");
}
producer.join().unwrap();
}The first few sent lines appear at once. After that, each sent line is gated by a handled line. The exact interleaving of lines can vary between runs, but the rule always holds. The number of completed sends never exceeds the number of messages received plus the capacity.
Choosing a capacity
The capacity is a design decision, not a tuning detail.
- A small capacity (1 to 10) keeps memory low and limits how far the producer runs ahead. It can cause the producer to wait often when the consumer's speed varies.
- A larger capacity absorbs bursts. It also lets more work pile up, which means more memory and more stale data if the consumer is slow.
- Capacity 0 is a special case, described next.
There is no universal number. A reasonable approach is to pick a small value, measure whether producers spend much time blocked, and raise it only if bursts justify it. Keep in mind that the capacity is counted in messages, not bytes. A bounded channel of 1000 messages that each hold a 10 MB buffer can still use 10 GB.
Capacity 0: a rendezvous channel
With sync_channel(0) there is no buffer. send blocks until a receiver is actually calling recv, and the value is handed directly over. The two threads meet at that moment, which is why this is called a rendezvous channel.
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
fn main() {
let (tx, rx) = mpsc::sync_channel::<&str>(0);
let sender = thread::spawn(move || {
tx.send("hello").unwrap();
println!("send returned");
});
thread::sleep(Duration::from_millis(100));
println!("receiving");
println!("{}", rx.recv().unwrap());
sender.join().unwrap();
}receiving always prints first, because send cannot return before the receiver arrives. The order of hello and send returned afterwards is not fixed. Use capacity 0 when you want a synchronization point, not a queue.
Sending without blocking: try_send
Blocking is not always acceptable. A thread that handles network events or a UI loop may prefer to drop or defer work than to wait. SyncSender::try_send returns immediately.
use std::sync::mpsc::{self, TrySendError};
fn main() {
let (tx, rx) = mpsc::sync_channel::<u32>(2);
for i in 0..4 {
match tx.try_send(i) {
Ok(()) => println!("queued {i}"),
Err(TrySendError::Full(v)) => println!("full, dropped {v}"),
Err(TrySendError::Disconnected(v)) => println!("receiver gone, {v}"),
}
}
println!("{:?}", rx.try_recv());
}This prints queued 0, queued 1, full, dropped 2, full, dropped 3, then Ok(0). The two error variants carry the unsent value back to you, so you can retry it, log it, or discard it deliberately. That is the same pattern as SendError, which also returns the value.
| Method | When the buffer is full | When the receiver is gone |
|---|---|---|
| `send` | Blocks until space is free | Returns `Err(SendError(value))` |
| `try_send` | Returns `Err(TrySendError::Full(value))` | Returns `Err(TrySendError::Disconnected(value))` |
The standard library has no send_timeout. If you need a bounded wait on the sending side, you must loop on try_send with a short sleep, or use a third-party channel crate such as crossbeam-channel, which offers send_timeout.
Cloning and closing
SyncSender is Clone, so many producers can share one bounded channel, exactly as with Sender. The capacity is shared across all of them, not per producer. When the buffer is full, every producer that calls send blocks, and they are released as the consumer drains the queue.
Closing works as in the unbounded case. The receiving loop ends when every SyncSender is dropped and the buffer is empty. Messages already buffered are still delivered after the last sender drops. If the Receiver is dropped first, a blocked send wakes up and returns an error, so a producer is never stuck forever on a consumer that has gone away.
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::sync_channel::<u32>(1);
let producer = thread::spawn(move || {
let mut sent = 0;
for i in 0..100 {
if tx.send(i).is_err() {
break;
}
sent += 1;
}
sent
});
println!("first = {}", rx.recv().unwrap());
drop(rx);
let sent = producer.join().unwrap();
println!("producer stopped early: {}", sent < 100);
}The producer would otherwise block on the full buffer. Dropping rx makes the next send fail, the loop breaks, and join returns. The program prints first = 0 and producer stopped early: true.
Common mistakes
- Sending and receiving on the same thread. A bounded channel with capacity
nblocks the thread that sends then + 1th message with no receiver running. With a single thread this is a permanent deadlock, and the program hangs with no error. - Holding a lock while sending. If a producer holds a
Mutexguard and blocks on a full channel, any thread that needs that lock stalls. If the consumer needs that same lock to make progress, the program deadlocks. Release locks before callingsend. - Assuming
try_sendis a general replacement forsend. If you ignore itsFullerror you silently lose messages. Decide on a policy: drop, retry, or count and report. - Expecting FIFO fairness among blocked producers. The standard library does not promise which blocked sender gets the next free slot. Per-sender ordering holds, but cross-sender order does not.
Where this leads
Bounded channels are the natural job queue for a worker pool. If the queue has a fixed capacity, a submitter that outpaces the workers blocks, instead of piling up jobs without limit. The worker pool chapter combines this with shared state.
Exercise
A program creates let (tx, rx) = mpsc::sync_channel::<u32>(3); and, on a single thread with no other threads, calls tx.send(i) in a loop for i in 0..10 before ever calling rx.recv(). What happens, and what are two ways to fix it?
Show answer
The first three sends fill the buffer and the fourth send blocks forever, because the only thread that could receive is the one that is blocked. This is a deadlock and the program hangs. One fix is to move the sending loop into a spawned thread and receive on the main thread. Another is to use try_send and handle TrySendError::Full, for example by receiving some messages before sending more. Increasing the capacity to 10 or more would also avoid the hang here, but it only hides the problem for larger inputs.
Exercise
What is the difference between sync_channel(0) and sync_channel(1) from the sender's point of view?
Show answer
With capacity 0 there is no buffer, so send blocks until a receiver is waiting in recv and takes the value directly. With capacity 1 one message can sit in the buffer, so the first send returns immediately even if no receiver is ready. The second send then blocks until the receiver takes the first message.