Answer#
Sending an e-mail or resizing an image inside the handler makes the client wait. Put the job on a queue and let a worker do it:
use axum::{body::{to_bytes, Body}, extract::{Path, State}, http::{Request, StatusCode}, routing::post, Router};
use std::time::Duration;
use tokio::sync::mpsc;
use tower::ServiceExt;
#[derive(Clone)]
struct AppState { jobs: mpsc::Sender<String> }
async fn enqueue(State(s): State<AppState>, Path(email): Path<String>) -> StatusCode {
match s.jobs.try_send(email) {
Ok(()) => StatusCode::ACCEPTED, // 202: queued, not done yet
Err(mpsc::error::TrySendError::Full(_)) => StatusCode::SERVICE_UNAVAILABLE, // queue full: tell the client to retry later
Err(mpsc::error::TrySendError::Closed(_)) => StatusCode::INTERNAL_SERVER_ERROR,
}
}
async fn worker(mut rx: mpsc::Receiver<String>) {
while let Some(email) = rx.recv().await {
tokio::time::sleep(Duration::from_millis(10)).await; // pretend to send a message
println!("worker: sent mail to {email}");
}
println!("worker: channel closed, finished");
}
#[tokio::main]
async fn main() {
let (tx, rx) = mpsc::channel(2); // room for two waiting jobs
let app = Router::new().route("/welcome/{email}", post(enqueue)).with_state(AppState { jobs: tx });
// The worker is not running yet, so the queue fills up.
for who in ["[email protected]", "[email protected]", "[email protected]"] {
let res = app.clone().oneshot(Request::post(format!("/welcome/{who}")).body(Body::empty()).unwrap()).await.unwrap();
println!("{who} -> {}", res.status());
let _ = to_bytes(res.into_body(), usize::MAX).await;
}
let handle = tokio::spawn(worker(rx));
drop(app); // dropping the last Sender closes the channel; the worker drains what is queued, then ends
handle.await.unwrap();
}[email protected] -> 202 Accepted
[email protected] -> 202 Accepted
[email protected] -> 503 Service Unavailable
worker: sent mail to [email protected]
worker: sent mail to [email protected]
worker: channel closed, finished- The queue has room for two jobs, and the worker had not started yet, so the third request found it full and got
503 Service Unavailable. A bounded queue is how overload becomes a clear answer and not unlimited memory use. try_sendnever waits. Usesend().awaitinstead if the handler may wait for room.- When the last
Senderis dropped the channel closes, the worker finishes the jobs still queued and then leaves itswhile letloop. The output shows both queued jobs were processed beforechannel closed. 202 Acceptedsays "received, not done yet". The client cannot tell whether the job later failed; if it matters, store a job record and let the client look it up.
Common mistakes#
- An unbounded channel, which can grow without limit when work arrives faster than the worker.
- Treating the queue as durable. If the program exits, the queued jobs are gone. Work that must not be lost belongs in a database table.
- One worker for slow jobs and no limit on how long a job may take. Add a timeout inside the worker.
Related questions#
Can I run several workers?#
Share the receiver behind a lock, or give each worker its own channel. This thread ran one worker.
Sources#
- tokio,
mpsc: https://docs.rs/tokio/1.54.1/tokio/sync/mpsc/index.html (read 2026-12-05)