notes · · 3 min

Batched receives from many async producers in Rust

How to drain an async channel in batches when many producers feed one consumer: Tokio's recv_many, a receive-then-drain pattern for any channel, and rapidfire's exclusive MPSC receiver, with the limits of each.

On this page · 5 sections
  1. With Tokio: recv_many
  2. With any async channel: receive one, then drain
  3. With rapidfire: an exclusive MPSC receiver
  4. Which one to use
  5. Limits and measurements

Many tasks often feed a single consumer: WebSocket readers feed a strategy, request handlers feed a database writer, parser threads feed a logger. One recv().await per message works, but the consumer then pays the cost of each receive (a poll, a queue check and often a wake-up) for every message, even when hundreds are already waiting. Taking everything that is ready in one call handles a burst in one pass. It also lets the consumer do its own per-batch work once per batch, such as one database insert or one flush.

One rule keeps latency bounded: wait only for the first message, then take what is already queued, and never wait to fill a batch. A message that arrives alone is handled at once, and a burst is handled together. Time-based batching (“flush every 5 ms”) is a separate timer on top, and it adds that delay to every message.

With Tokio: recv_many

Since Tokio 1.34, tokio::sync::mpsc::Receiver::recv_many does exactly this, and so does the same method on UnboundedReceiver:

use tokio::sync::mpsc;

fn handle(_value: u64) {}

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

    for producer in 0..4u64 {
        let tx = tx.clone();
        tokio::spawn(async move {
            for sequence in 0..1000 {
                tx.send(producer * 1000 + sequence).await.unwrap();
            }
        });
    }
    drop(tx); // Keep only the producers' senders alive.

    let mut batch = Vec::with_capacity(64);
    // Waits for the first message, then appends whatever else is ready, up to 64.
    // Returns 0 only after every sender is gone and the queue is empty.
    while rx.recv_many(&mut batch, 64).await > 0 {
        for value in batch.drain(..) {
            handle(value);
        }
    }
}

The return value is the number of messages appended. With a non-zero limit, it is 0 only when the channel is closed and empty. The buffer grows as needed. Reuse it, and drain or clear it after processing. The method is cancel safe: if it loses a tokio::select! race, no message was taken. If your program already runs on Tokio and has one consumer, this is the answer, and you need no extra crate.

With any async channel: receive one, then drain

A channel that offers only recv and try_recv, such as async-channel, can be batched with a small helper:

/// Waits for one message, then takes what is already queued, up to `limit`.
/// Returns `false` once the channel is closed and empty.
async fn recv_batch<T>(
    rx: &async_channel::Receiver<T>,
    batch: &mut Vec<T>,
    limit: usize,
) -> bool {
    match rx.recv().await {
        Ok(first) => batch.push(first),
        Err(_) => return false,
    }
    for _ in 1..limit {
        match rx.try_recv() {
            Ok(next) => batch.push(next),
            Err(_) => break, // Empty right now: do not wait to fill the batch.
        }
    }
    true
}

This works for MPMC channels too. With several consumers, each one takes a batch, so batches can split unevenly between them. Each try_recv is still a separate operation on the channel, so the channel cannot combine its own bookkeeping across the batch. A built-in batch receive can do that.

With rapidfire: an exclusive MPSC receiver

rapidfire 0.2.0 adds rapidfire::mpsc, a channel with cloneable senders and exactly one receiver. The receiver cannot be cloned. recv, try_recv and recv_many take &mut self, so the compiler rejects two concurrent receives on one receiver. With a single consumer, the receive path skips coordination between consumers. A batch publishes freed capacity once per chunk of a queue block, not once per message, and then wakes up to that many blocked senders. The default build depends only on std, and its futures are ordinary standard futures. This example uses plain threads and futures::executor::block_on, with no runtime:

use futures::executor::block_on;
use rapidfire::mpsc;
use std::thread;

fn handle(_value: u64) {}

fn main() {
    let (tx, mut rx) = mpsc::bounded::<u64>(4096);

    // Producers on plain threads; no async runtime is involved.
    let producers: Vec<_> = (0..4u64)
        .map(|producer| {
            let tx = tx.clone();
            thread::spawn(move || {
                block_on(async {
                    for sequence in 0..1000 {
                        tx.send(producer * 1000 + sequence).await.unwrap();
                    }
                })
            })
        })
        .collect();
    drop(tx);

    block_on(async {
        let mut batch = Vec::with_capacity(64);
        // Err(RecvError) means every sender is gone and the queue is empty.
        while rx.recv_many(&mut batch, 64).await.is_ok() {
            for value in batch.drain(..) {
                handle(value);
            }
        }
    });
    for producer in producers {
        producer.join().unwrap();
    }
}

recv_many returns Ok(count). It returns Ok(0) at once for a zero limit and Err(RecvError) once the channel is closed and drained. It never waits for a full batch, and cancelling a pending call consumes no messages. For several consumers, rapidfire::{bounded, unbounded} is the MPMC variant on the same queue. It has no recv_many; drain it with try_recv as above.

Which one to use

  • On Tokio, with one consumer: Tokio’s recv_many.
  • Several consumers, or a channel you already use: receive one, then drain.
  • No runtime dependency, or a gain you have measured on your workload: rapidfire::mpsc.

Limits and measurements

Batching is not automatically faster. The 0.2.0 fleet report measures rapidfire’s two receivers on twelve machines, with 1 KiB messages, four Tokio workers and a receive limit of 32:

  • 40 producers, bounded(4096), Ryzen 7950X: the exclusive receiver cost 57 ns per message, against 250 ns for the general one.
  • 4 producers, unbounded, Ryzen 9950X: it cost 246 ns against 47 ns, 5.25× slower.

Scheduling, queue occupancy and block recycling can outweigh the work that batching saves. A lower throughput cost does not imply a lower p99 latency. The report also compares other crates, Tokio’s mpsc among them, but those runs take one message per receive. It does not compare batched receives across crates. Measure your own workload.

rapidfire has other limits too:

  • Waiter lists and the block pool use mutexes, so not every operation is lock-free.
  • Memory stays at the channel’s high-water mark until the channel is dropped.
  • One close race is documented: a send that saw the channel open may succeed after a concurrent close has made the receiver report closed. That value is dropped with the channel.

Documentation: docs.rs/rapidfire, Tokio Receiver::recv_many.

Cite this article
Citation
Alexander Panasenko (2026-11-29). Batched receives from many async producers in Rust. https://prod.codes/blog/batched-receives-from-many-async-producers-in-rust/