Your Tokio Broadcast Receiver Fell Behind. Where Did the Messages Go?
They were overwritten. A tokio::sync::broadcast channel is a fixed-size ring, and when it is full the next send replaces the oldest value, whether or not every receiver has read it. The slow receiver cannot get those messages back from the channel.
What it does get is an error, RecvError::Lagged(n), saying how many it missed. It is remarkably easy to write code that throws that error away.
Twenty sends into a channel of ten
Here is a receiver that does nothing until the sender has finished. I ran this, and the other behaviour described here was checked against the source and docs of Tokio 1.54.1.
use tokio::sync::broadcast::{self, error::RecvError};
#[tokio::main(flavor = "current_thread")]
async fn main() {
let (tx, mut rx) = broadcast::channel(10);
for i in 0..20 {
tx.send(i).unwrap(); // every one of these succeeds
}
println!("len before: {}", rx.len());
drop(tx);
loop {
match rx.recv().await {
Ok(v) => println!("got {v}"),
Err(RecvError::Lagged(n)) => println!("lagged {n}"),
Err(RecvError::Closed) => break,
}
}
}
The output starts like this, then carries on up to 19:
len before: 20
lagged 4
got 4
got 5
got 6
Values 0 to 3 are gone. The Lagged error moved this receiver's cursor to the oldest value still held, so the next recv returned 4. Lagging does not disconnect you; the receiver carries on working, with a hole in its history.
Why did a capacity of 10 keep 16?
Quick detour, because this one looks like a bug. Ten slots and twenty messages should lose ten, yet we lost four.
Tokio rounds the capacity up to the next power of two, so channel(10) allocates 16 slots. This is documented, and lag detection uses the rounded figure. Ask for 1025 and you get 2048, which matters if each message is large and you sized the channel to a memory budget.
Note also that rx.len() said 20. It counts everything this receiver has not yet received, including values already overwritten. A length above the rounded capacity means the next receive will report lag.
A successful send promises very little
send is not async and never waits for room. A slow consumer therefore puts no backpressure on the producer at all.
The Ok(n) it returns is the number of subscribed receivers. It is not a delivery receipt: any of them may lag or be dropped before reading the value. An Err means there were no receivers at that moment, though a later subscribe can make sends succeed again.
New subscribers also start from now. Neither tx.subscribe() nor rx.resubscribe() hands over older messages, so you cannot recover a gap by reconnecting. Calling resubscribe on a lagging receiver skips even the values it could still have read.
Three ways to lose the error
This loop looks tidy and is the one I would search a codebase for first:
while let Ok(msg) = rx.recv().await {
handle(msg);
}
Lagged is an Err, so the first lag ends the loop for good. The consumer stops as though the channel had closed. If it was a spawned task and nobody checks on it, the symptom is that updates simply cease, probably just after your busiest moment.
The select! version fails more quietly:
loop {
tokio::select! {
Ok(msg) = rx.recv() => handle(msg),
_ = shutdown.recv() => break,
}
}
When the pattern does not match, select! disables that branch for the rest of this call. The error has already been consumed, and the cursor has already moved. On a later trip round the loop, reading resumes with no trace that anything was skipped.
The third lives in tokio-stream. BroadcastStream yields a Result whose error is BroadcastStreamRecvError::Lagged(n), and a casual filter_map(Result::ok) deletes your only evidence.
The fix for all three is to match the whole result. At the very least, log n and increment a metric.
A bigger buffer only buys time
Raising the capacity is reasonable if your traffic comes in bursts and the consumer catches up between them. It does nothing if the consumer is slower than the producer on average. You will lag later, with more memory in use.
The cost is shared, too. There is one ring for all receivers, and a value can stay in it until the last of them has read it or it is overwritten. One stalled subscriber can keep the buffer full while the others are fully caught up.
Check what the consumer does between calls to recv. A database write or a network send to a sluggish client in that loop sets your maximum consumption rate.
Decide what a gap means for your data
The right response to Lagged depends on what the messages are:
- Disposable samples (live metrics, cursor positions): count the loss and carry on.
- Current state (configuration, a status flag): reload the state, or use a
watchchannel, which only keeps the latest value. - A client you can reconnect: close it and make it fetch a fresh snapshot.
- Events that must all be processed: keep them somewhere replayable, or give each consumer a bounded
mpscchannel and accept that the producer must wait or handle a full queue.
Replaying the gap from a log
For the last case, you can keep broadcast as the fast path and treat a separate log as the truth. Give every event a sequence number, and remember which one you expect next.
use std::sync::Mutex;
use tokio::sync::broadcast::{self, error::RecvError};
#[derive(Clone, Debug)]
struct Event {
seq: u64,
body: String,
}
struct Bus {
log: Mutex<Vec<Event>>,
tx: broadcast::Sender<Event>,
}
impl Bus {
fn publish(&self, body: String) {
// Held across send, so sequence order matches channel order.
let mut log = self.log.lock().unwrap();
let event = Event { seq: log.len() as u64, body };
log.push(event.clone());
// An error only means nobody is listening; the log still has it.
let _ = self.tx.send(event);
}
fn since(&self, seq: u64) -> Vec<Event> {
let log = self.log.lock().unwrap();
log.iter().skip(seq as usize).cloned().collect()
}
}
async fn consume(
bus: &Bus,
mut rx: broadcast::Receiver<Event>,
mut next: u64,
mut handle: impl FnMut(Event),
) {
loop {
let batch = match rx.recv().await {
Ok(event) => vec![event],
Err(RecvError::Lagged(n)) => {
eprintln!("lagged by {n}, replaying from {next}");
bus.since(next)
}
Err(RecvError::Closed) => break,
};
for event in batch {
// A replay overlaps what is still in the ring, so skip repeats.
if event.seq >= next {
next = event.seq + 1;
handle(event);
}
}
}
}
The overlap is easy to miss. After Lagged, the ring still holds its retained values, and your replay has just processed them. Without the sequence check you swap lost messages for duplicates.
This is deliberately small. The in-memory Vec grows without limit and vanishes on restart, so a real service needs durable storage and a retention rule. If a consumer falls behind the oldest retained entry, it needs a snapshot instead. A large replay would also be better read in pages.
Make the lag happen in a test
You do not need load or sleeps to exercise this path. Create a channel with a capacity of 4, publish ten events before the consumer runs, then check that it handles all ten in order.
I did that with the code above: it reported a lag of 6, replayed from zero and handled each event once. Note that Bus owns the sender, so the channel stays open while consume borrows it. My test stopped the waiting consumer with a short tokio::time::timeout.
The API details are in the Tokio broadcast module documentation. Then go and search for while let Ok.