Handle backpressure in async Rust by using bounded channels to limit the number of in-flight tasks and prevent memory exhaustion. When the channel is full, the sender blocks until a receiver consumes an item, naturally throttling the producer.
use tokio::sync::mpsc;
#[tokio::main]
async fn main() {
let (tx, mut rx) = mpsc::channel::<String>(10);
// Sender blocks if channel is full (backpressure)
for i in 0..100 {
tx.send(format!("msg-{i}")).await.unwrap();
}
while let Some(msg) = rx.recv().await {
println!("Received: {msg}");
}
}