expression

Axum: timeout does not roll back side effects

A timeout can drop an unfinished future without undoing effects that occurred before the await. In this example a synthetic counter changes before a delayed response. Real mutations need explicit transactional and idempotency design. In-memory standalone Cargo example. Expected stdout (not executed): 503 1 Common mistake: Blindly retrying a timed-out mutation because its response failed to arrive.

Formal Syntax & Structure

rust syntaxrust
timeout(deadline, operation).await

Working Example

Example Snippetrust
use axum::{Router, body::{Body, to_bytes}, http::{Request, StatusCode}};use tower::ServiceExt;
#[tokio::main(flavor = "current_thread", start_paused = true)]async fn main() {    use axum::{routing::post, extract::State};    use std::{sync::{Arc, atomic::{AtomicUsize, Ordering}}, time::Duration};    use tower_http::timeout::TimeoutLayer;    async fn change(State(count): State<Arc<AtomicUsize>>) -> &'static str {        count.fetch_add(1, Ordering::SeqCst);        tokio::time::sleep(Duration::from_secs(10)).await;        "done"    }    let count = Arc::new(AtomicUsize::new(0));    let app = Router::new().route("/", post(change)).with_state(count.clone()).layer(TimeoutLayer::with_status_code(StatusCode::SERVICE_UNAVAILABLE, Duration::from_secs(1)));    let r = app.oneshot(Request::builder().method("POST").body(Body::empty()).unwrap()).await.unwrap();    println!("{}", r.status().as_u16());    println!("{}", count.load(Ordering::SeqCst));}
Rust Reference