Skip to content
systemcoding.dev
Concurrency

Use Tokio Channels: mpsc, oneshot, broadcast and watch

Pick the right Tokio channel: mpsc for queues, oneshot for one reply, broadcast for fan-out and watch for the latest value, each with a working example.

7 min read
Summarize in AI
Flat illustration of parallel threads meeting at a mutex, with the Rust, C and Erlang logos.

Tasks in a Tokio program rarely share memory directly. They pass messages, and the tokio::sync module offers four channel types that cover almost every pattern: mpsc for a queue of work, oneshot for a single reply, broadcast for sending each message to many receivers and watch for publishing the latest value of some state. Choosing the right one is mostly a question of how many senders and receivers you have and whether receivers need every message or only the newest. This post shows each with a complete example for Tokio 1.x on Rust 1.90, and ends with a decision table. Tokio's channels are async-aware: sending to a full channel or receiving from an empty one suspends the task rather than blocking the thread.

mpsc: many producers, one consumer

tokio::sync::mpsc is the workhorse. Create a bounded channel with mpsc::channel(capacity), clone the Sender for each producer, and have one task own the Receiver. When the buffer is full, send(..).await waits, which gives you backpressure for free.

src/main.rsrust
use tokio::sync::mpsc;

#[tokio::main]
async fn main() {
    let (tx, mut rx) = mpsc::channel::<String>(8);

    let mut producers = Vec::new();
    for id in 0..2 {
        let tx = tx.clone();
        producers.push(tokio::spawn(async move {
            for n in 0..2 {
                tx.send(format!("producer {id} item {n}")).await.unwrap();
            }
        }));
    }
    drop(tx); // the original sender; otherwise the loop below never ends

    let mut got = Vec::new();
    while let Some(msg) = rx.recv().await {
        got.push(msg);
    }
    got.sort();
    for m in got { println!("{m}"); }
    for p in producers { p.await.unwrap(); }
}
Text
producer 0 item 0
producer 0 item 1
producer 1 item 0
producer 1 item 1

recv returns None once every Sender has been dropped and the buffer is empty. That is why the original tx is dropped explicitly: a forgotten sender keeps the receiver waiting forever. Arrival order between producers varies from run to run, so the example sorts before printing to make the output stable. Messages from a single producer always arrive in the order that producer sent them.

Prefer the bounded channel. mpsc::unbounded_channel never makes senders wait, which means a fast producer and a slow consumer grow memory without limit.

oneshot: exactly one value

A oneshot channel carries a single value from one sender to one receiver. Its main use is a reply: embed the oneshot::Sender in a request message and await the Receiver for the answer.

src/main.rsrust
use tokio::sync::{mpsc, oneshot};

struct Request {
    a: u32,
    b: u32,
    reply: oneshot::Sender<u32>,
}

#[tokio::main]
async fn main() {
    let (tx, mut rx) = mpsc::channel::<Request>(4);

    tokio::spawn(async move {
        while let Some(req) = rx.recv().await {
            let _ = req.reply.send(req.a + req.b);
        }
    });

    let (reply_tx, reply_rx) = oneshot::channel();
    tx.send(Request { a: 2, b: 40, reply: reply_tx }).await.unwrap();
    println!("answer = {}", reply_rx.await.unwrap());
}
Text
answer = 42

This request and reply pattern is the basis of the actor style that later posts in this cluster build on. send on a oneshot is not async, because it never waits: it either delivers the value or returns it back inside an Err if the receiver was dropped. Awaiting the receiver gives Err(RecvError) if the sender was dropped without sending.

broadcast: every receiver gets every message

broadcast::channel(capacity) creates a multi-producer, multi-consumer channel in which each message is cloned for every receiver. Receivers are created with tx.subscribe().

src/main.rsrust
use tokio::sync::broadcast;

#[tokio::main]
async fn main() {
    let (tx, mut rx1) = broadcast::channel::<&str>(4);
    let mut rx2 = tx.subscribe();

    tx.send("start").unwrap();
    tx.send("stop").unwrap();

    println!("rx1: {} {}", rx1.recv().await.unwrap(), rx1.recv().await.unwrap());
    println!("rx2: {} {}", rx2.recv().await.unwrap(), rx2.recv().await.unwrap());
}
Text
rx1: start stop
rx2: start stop

The channel keeps a ring buffer of the given capacity. A receiver that falls too far behind loses the oldest messages, and its next recv returns Err(RecvError::Lagged(n)) telling it how many were skipped. Handle that case deliberately, because it is how a slow subscriber is isolated from the fast ones. The message type must be Clone.

watch: the latest value only

watch holds one value. Receivers do not queue anything; they see the current value and can wait for it to change. It suits configuration and shutdown flags, where only the newest state matters.

src/main.rsrust
use tokio::sync::watch;

#[tokio::main]
async fn main() {
    let (tx, mut rx) = watch::channel("v1");

    let waiter = tokio::spawn(async move {
        rx.changed().await.unwrap();
        println!("saw {}", *rx.borrow_and_update());
    });

    tx.send("v2").unwrap();
    waiter.await.unwrap();
}
Text
saw v2

If the sender updates the value several times before a receiver looks, the receiver sees only the last one. That is the intended semantics, and it is the reason watch is wrong for events that must not be missed. The value is held inside the channel, and borrow gives a short-lived read guard that you must not hold across an .await.

Choosing a channel

NeedChannelCapacity behavior
Queue of work for one consumermpscbounded, sender waits when full
A single reply to a requestoneshotexactly one value
Every subscriber must see every eventbroadcastring buffer, slow receivers lag
Share current state or a configwatchlatest value only

A common mistake: a channel closing too early or never

Two bugs account for most trouble. In the first, a sender is kept alive in a long-lived struct, so the receiver never sees None and the consumer task never exits. In the second, a receiver is dropped early, so send starts returning errors that the producer ignores with unwrap and crashes on. Decide who owns the last sender, and treat a send error as the shutdown signal it usually is.

Backpressure and the try_send escape

A bounded mpsc channel makes producers wait when it is full. That is usually what you want inside a pipeline, because the slow stage slows the stages before it instead of letting memory grow. Sometimes waiting is wrong. A metrics collector or a log forwarder should not stall the request path just because the sink is slow. For those cases, Sender::try_send returns immediately with Err(TrySendError::Full(value)) when the buffer has no room, and you can drop the item and count the drop. Sender::reserve is the third option: it waits for capacity first and hands you a permit, so the later send cannot fail, which helps when you must not lose a message after doing expensive work to build it.

Decide the policy explicitly. Dropping new items, dropping old ones and blocking the producer are three different behaviors, and the channel type you choose implies one of them: a bounded mpsc blocks, a broadcast drops old items for lagging receivers, and a watch keeps only the newest.

Receivers that own state

A recurring shape is a task that owns a piece of state and exposes it only through a channel. The mpsc receiver is the task's inbox, and the state never needs a lock because only that task touches it. That is the actor pattern in miniature, and it is why oneshot replies and mpsc inboxes appear together so often. The cost is one task switch per operation, so for a hot counter an atomic is cheaper, while for state with real invariants the single owner is easier to reason about than a mutex that several tasks lock in different orders.

When you use watch to publish configuration, remember that Receiver::borrow holds a read lock while the guard is alive. Copy what you need and drop the guard before awaiting anything, or the sender's next send may wait on you.

Testing code that uses channels

Channel-based code is easy to test when the tests control time and closure. Close a channel by dropping its senders and assert that the consumer's loop ends. Use #[tokio::test] with a bounded channel of capacity one to force the producer to wait, and assert with try_send that a full channel reports Full. With tokio::time::pause() and the test-util feature, timeouts advance instantly, so a test of a reply that never comes does not need to sleep for real. Keep the message type small and plain, because a type with obvious equality is simple to assert on, and keep the channel creation in one function so tests can build the same wiring the program does.

Share

Keep reading

Flat illustration of two options weighed side by side, with the C, C++ and Rust logos.
Performance

Spinlocks vs Mutexes: When Spinning Wins

A spinlock burns a core while it waits and a mutex sleeps. Compare their costs, write a correct C11 spinlock, and see when user-space spinning beats a mutex.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.