expression

gRPC: forward only the remaining time budget

Use one monotonic deadline for the work initiated by a call. Compute the remaining time before each downstream request; reject work if the budget is exhausted. This synthetic example uses Tokio paused time and explicitly forwards the remaining duration. Automatic propagation is not assumed. Run in the accompanying Cargo project. Expected stdout (not executed): remaining: 60 ms Common mistake: Resetting the full 100 ms budget on every downstream call.

Formal Syntax & Structure

rust syntaxrust
deadline.saturating_duration_since(Instant::now())

Working Example

Example Snippetrust
#[tokio::main(flavor = "current_thread", start_paused = true)]async fn main() {    use tokio::time::{self, Duration, Instant};    let deadline = Instant::now() + Duration::from_millis(100);    time::advance(Duration::from_millis(40)).await;    let left = deadline.saturating_duration_since(Instant::now());    assert!(!left.is_zero());    let mut downstream = tonic::Request::new(());    downstream.set_timeout(left);    println!("remaining: {} ms", left.as_millis());}
Rust Reference