How do I apply backpressure from the client side (or connection strength) in tonic to avoid consuming the stream too fast?

I have a server-side streaming RPC server and the stream returned by the function is meant to “drop” intermediate updates (in the sense of not returning the from .next()) based on how fast .next() is called, but it seems like the server is calling .next() in a tight loop regardless of how fast or slow the client is able to consume from it. How can I apply backpressure from the client-side so that .next() calls are limited by the rate at which the client can consume?

I tried setting the buffer size on the client side, but that doesn’t do anything (I can’t find anywhere to set it on the server side).

Sorry for the large MWE. tonic code isn’t particularly concise.


Here’s an example server and client where the server increments a counter and attempts to publish its value to any subscribers once-per-second, but the client only consumes messages once every two seconds. When I run this, the client seems to fall indefinitely behind. In other words, the queue seems completely unbounded.

I see this same behavior when the client is fast to consume but I use toxiproxy to throttle the connection, so this isn’t being caused by an unbounded client-side cache.

// streaming.proto

syntax = "proto3";

package streaming;

service Counter {
  rpc StreamCounter(Empty) returns (stream CounterResponse);
}

message Empty {}

message CounterResponse {
  int32 value = 1;
}
// server.rs

use futures_util::stream;
use std::pin::Pin;
use std::sync::Arc;
use tokio::sync::{watch, Mutex};
use tokio::time::{sleep, Duration};
use tokio_stream::{Stream, StreamExt};
use tonic::async_trait;
use tonic::{transport::Server, Request, Response, Status};

pub mod streaming {
    tonic::include_proto!("streaming");
}

use streaming::counter_server::{Counter, CounterServer};
use streaming::{CounterResponse, Empty};

pub struct MyCounter {
    tx: Arc<watch::Sender<i32>>,
}

#[async_trait]
impl Counter for MyCounter {
    type StreamCounterStream = Pin<Box<dyn Stream<Item = Result<CounterResponse, Status>> + Send>>;

    async fn stream_counter(
        &self,
        _request: Request<Empty>,
    ) -> Result<Response<Self::StreamCounterStream>, Status> {
        let rx = Arc::new(Mutex::new(self.tx.subscribe()));

        let output = stream::repeat(())
            .then(move |()| {
                let rx = rx.clone();
                async move {
                    let mut rx = rx.lock().await;
                    let result = rx.changed().await;
                    match result {
                        Ok(()) => {
                            let value = *rx.borrow();
                            drop(rx);
                            println!("Sending: {}", value);
                            Some(Ok(CounterResponse { value }))
                        }
                        Err(_) => None,
                    }
                }
            })
            .map_while(|x| x);

        Ok(Response::new(Box::pin(output)))
    }
}

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let (tx, _rx) = watch::channel(0);
    let tx = Arc::new(tx);
    let my_counter = MyCounter { tx: tx.clone() };

    tokio::spawn(async move {
        let mut counter = 0;
        loop {
            sleep(Duration::from_secs(1)).await;
            counter += 1;
            tx.send(counter).unwrap();
        }
    });

    let addr = "[::1]:50051".parse()?;
    Server::builder()
        .add_service(CounterServer::new(my_counter))
        .serve(addr)
        .await?;

    Ok(())
}
// client.rs

use streaming::counter_client::CounterClient;
use streaming::Empty;
use tokio_stream::StreamExt;
use tonic::transport::Endpoint;
use tonic::Request;

pub mod streaming {
    tonic::include_proto!("streaming");
}

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut client =
        CounterClient::connect(Endpoint::from_static("http://[::1]:50051").buffer_size(Some(2)))
            .await?;
    let request = Request::new(Empty {});

    let mut stream = client.stream_counter(request).await?.into_inner();

    while let Some(response) = stream.next().await {
        match response {
            Ok(counter_response) => {
                println!("Received: {}", counter_response.value);
                tokio::time::sleep(tokio::time::Duration::from_secs(2)).await; // Simulate slow processing
            }
            Err(e) => {
                eprintln!("Error: {}", e);
                break;
            }
        }
    }

    Ok(())
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật