FAQ - Help and questions

How do I hand slow work to a background worker from an axum handler?

#axum#tokio#background-tasks#channelspublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Create a bounded tokio mpsc channel, keep the Sender in the application state and run one worker task that reads the Receiver. The handler calls try_send and answers 202 Accepted at once, or 503 when the queue is full. Jobs held in memory are lost if the program stops.

Checked with rustc 1.93.0, axum 0.8.9, tokio 1.54.1, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

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:

rust
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();
}
text
[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_send never waits. Use send().await instead if the handler may wait for room.
  • When the last Sender is dropped the channel closes, the worker finishes the jobs still queued and then leaves its while let loop. The output shows both queued jobs were processed before channel closed.
  • 202 Accepted says "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.

Can I run several workers?#

Share the receiver behind a lock, or give each worker its own channel. This thread ran one worker.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet