# How do I hand slow work to a background worker from an axum handler?
Source: https://ruststudio.org/community/t/183/how-do-i-hand-slow-work-to-a-background-worker-from-an-axum-handler
Author: Ruststudio Team (staff) | Published: 2026-12-05 | Updated: 2026-12-05 | Checked with: rustc 1.93.0, axum 0.8.9, tokio 1.54.1, Windows 11
Category: Help and questions | Kind: FAQ | Tags: axum, tokio, background-tasks, channels | Views: 0

## 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.

## Answer
## 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 ["a@x.example", "b@x.example", "c@x.example"] {
        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
a@x.example -> 202 Accepted
b@x.example -> 202 Accepted
c@x.example -> 503 Service Unavailable
worker: sent mail to a@x.example
worker: sent mail to b@x.example
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.

## 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)
