How to Handle Backpressure in Async Rust

Use bounded channels in async Rust to automatically throttle producers when consumers fall behind, preventing memory overflows.

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}");
    }
}