Non-blocking response with spawn - answering fast while work continues

Learn how a handler answers with 202 Accepted at once while a spawned task keeps working after the response is sent, and how to prove the work finished later

A handler that awaits slow work before answering keeps the client waiting for the whole job. A handler that spawns the work and answers at once frees the client after a millisecond, and the work still gets done. The response and the work run on separate timelines, and the client never has to sit through the slow part.

Where This Fits

The previous pages showed the two pieces this page joins together: tokio::spawn starts work in the background, and a JoinHandle is the receipt for that work. This page is the pattern those pieces exist for. A request comes in, the handler starts the work, the handler answers immediately, and the work finishes later, after the client has already gone.

Think of dropping a parcel at a post office counter. The clerk takes the parcel, hands you a receipt, and you leave. The parcel travels on its own after you have gone. You do not stand at the counter until the parcel arrives. The handler is the clerk, the receipt is the response, and the parcel is the spawned task.

The Smallest Working Version

A report endpoint that takes two seconds to build, and a status endpoint that shows whether it finished:

src/main.rs
use axum::{
    extract::State,
    http::StatusCode,
    routing::{get, post},
    Json, Router,
};
use serde::Serialize;
use std::sync::{
    atomic::{AtomicBool, Ordering},
    Arc,
};
use std::time::Duration;
use tokio::time::sleep;

#[derive(Clone)]
struct AppState {
    report_done: Arc<AtomicBool>,
}

#[derive(Serialize)]
struct Status {
    report_done: bool,
}

async fn start_report(State(state): State<AppState>) -> (StatusCode, Json<serde_json::Value>) {
    let flag = Arc::clone(&state.report_done);
    tokio::spawn(async move {
        sleep(Duration::from_secs(2)).await;
        flag.store(true, Ordering::SeqCst);
        println!("background report finished");
    });
    (StatusCode::ACCEPTED, Json(serde_json::json!({ "status": "accepted" })))
}

async fn status(State(state): State<AppState>) -> Json<Status> {
    Json(Status { report_done: state.report_done.load(Ordering::SeqCst) })
}

#[tokio::main]
async fn main() {
    let state = AppState { report_done: Arc::new(AtomicBool::new(false)) };
    let app = Router::new()
        .route("/report", post(start_report))
        .route("/status", get(status))
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

The Cargo.toml file needs Axum, Tokio with the full feature set, and serde for the JSON status body:

Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"

Run the server, then try it from a second terminal:

curl -X POST http://127.0.0.1:3000/report
curl http://127.0.0.1:3000/status

The first call answers at once. The second call answers {"report_done":false} if the two seconds have not passed yet, and {"report_done":true} after they have. The flag changing between calls is the proof that the work finished after the response was already sent.

Working Setup:

If the report call answers at once, the status call first says false and later says true, and background report finished appears in the server terminal, the pattern works. The response went out early and the work still completed.

Proving It With Timings

The claim of this page is a timing claim: the response arrives before the work finishes. Timings are easy to assert and easy to fake, so here is the proof, measured on a real run of this exact code with a two second job. The response took 0.0014 seconds:

http=202 time=0.001411s
{"status":"accepted"}

The status check straight after the response said the work was not done:

{"report_done":false}

Three seconds later, the same check said it was done, and the server terminal showed the log line:

{"report_done":true}
background report finished

Read the three facts together. The response arrived in about a millisecond while the job needed two seconds, so the response cannot have waited for the job. The flag was false right after the response, so the job was still running when the client already had its answer. The flag turned true later, so the job finished on its own after the client had gone. That sequence is the whole pattern, measured rather than assumed.

Understanding the Handler Line by Line

The handler is short, and the two lines that matter are the spawn call and the return. The rest is wiring that the reader has already met.

Cloning the flag into the task

let flag = Arc::clone(&state.report_done);

The flag is shared between the handler and the task through an Arc, a reference-counted pointer that lets many owners share one value. Cloning an Arc does not copy the flag itself, it only adds one more owner pointing at the same flag. The task gets its own handle to the same AtomicBool, so setting the flag inside the task is visible to the status route. Without the clone, the task would try to borrow the state's flag, and the borrow would fail to compile, because a spawned task must own what it uses.

The spawned work

tokio::spawn(async move {
    sleep(Duration::from_secs(2)).await;
    flag.store(true, Ordering::SeqCst);
    println!("background report finished");
});

The sleep stands in for the real slow work: building the report, converting a file, calling another service. It pauses the task for two seconds without blocking the thread, so the runtime can run other tasks meanwhile. flag.store(true, Ordering::SeqCst) sets the shared flag, and the println! leaves a line in the server log so a human watching the terminal can see the moment the work finished. The handle returned by spawn is dropped here on purpose: nobody needs the result, and the task is meant to run detached.

The response

(StatusCode::ACCEPTED, Json(serde_json::json!({ "status": "accepted" })))

The handler returns a tuple of a status code and a JSON body. Axum turns the tuple into a finished response. The status is 202 Accepted, and the body says the work was accepted. Neither the status nor the body claims the work is done. That honesty is the point of the next section.

202 Accepted Is the Honest Status

Status codes are promises. 200 OK promises the request succeeded and the work is done. 201 Created promises a new resource exists now. 202 Accepted promises something narrower: the request was accepted, the work has started, and the result is not ready yet. When a handler spawns work and answers at once, 202 is the only status that describes what actually happened.

Returning 200 for work that has only just started misleads the client. A client that reads 200 assumes the report exists and tries to fetch it, then fails because the report is still being built. A client that reads 202 knows to wait, or to check the status endpoint, or to come back later. The number in the status line is a contract, and 202 keeps that contract honest.

The status code 202 comes from the HTTP standard, and Axum exposes it as StatusCode::ACCEPTED in the http crate. The body alongside it should say what was accepted and, when there is one, how the client can check on it. A bare 202 with an empty body leaves the client guessing. A body like {"status":"accepted"} at least names the situation, and a body that also carries a job id or a status URL gives the client somewhere to go next.

202 Means Accepted, Not Done:

A 202 response is a receipt, not a result. The client must treat it as "your request is in the queue" and never as "your work is finished". Any client code that reads 202 and then immediately uses the result of the work has misunderstood the status.

The Response and the Work Are on Separate Timelines

Once the handler returns, the response is gone. The spawned task keeps running on its own timeline, and nothing connects the two again unless the code builds a connection: a shared flag, a database row, a channel, a status endpoint. The handler cannot change the response after returning it, and the task cannot send anything to the client that already received its answer.

That separation has a consequence beginners often miss. The task outlives the handler that created it. The handler function returns, its local variables are dropped, and the request is finished, while the task carries on with the data it owns. The task is not tied to the request in any way after the spawn call. If the server restarts, the task dies with it, because tasks live only in memory. If the client disconnects, the task keeps running, because it never knew about the client in the first place.

The flow looks like this in plain text:

Client sends POST /report
        |
        v
Handler clones the shared flag
        |
        v
Handler spawns the report task
        |
        v
Handler returns 202 Accepted at once
        |
        v
Client receives the response and moves on
        |
        |     (meanwhile, on a separate timeline)
        v
Task sleeps, works, sets the flag
        |
        v
Task finishes, response already long gone

Two timelines, one spawn call between them. Everything after the spawn call happens without the client.

The Blocking Version for Comparison

The same endpoint written without spawning shows what this page is saving the client from. The handler awaits the slow work before answering:

// Slow version - the client waits the full two seconds
async fn start_report_slow() -> (StatusCode, Json<serde_json::Value>) {
    sleep(Duration::from_secs(2)).await;
    (StatusCode::OK, Json(serde_json::json!({ "status": "done" })))
}

A request to this version takes two seconds to answer, and the response honestly says done, because the work really is done when the response goes out. The blocking version is simpler, and it is the right choice when the client needs the result. The spawned version is the right choice when the client only needs to know the work started. The two versions differ by one line - the spawn call - and by everything about what the client experiences.

There is a second cost to the blocking version that matters under load. While one request waits two seconds inside its handler, that handler is not doing other work, and if enough requests pile up, new requests queue behind them. The spawned version frees the handler in a millisecond, so the server can take the next request at once. The slow work still consumes resources, but it does so in the background, where it no longer holds a client connection open.

Sharing Progress With a Status Endpoint

A 202 without any way to check progress leaves the client blind. The smallest honest addition is a status endpoint backed by shared state, exactly like the one in the smallest example. The handler and the task share a flag, and the status route reads it.

A flag only says done or not done. Real jobs have more states: waiting, running, done, failed. A shared string or a small enum in a Mutex carries those states. The shape is the same, only the value is richer:

src/main.rs
use axum::{
    extract::State,
    routing::get,
    Json, Router,
};
use std::sync::{Arc, Mutex};

#[derive(Clone)]
struct AppState {
    job_state: Arc<Mutex<String>>,
}

async fn job_status(State(state): State<AppState>) -> Json<serde_json::Value> {
    let current = state.job_state.lock().unwrap().clone();
    Json(serde_json::json!({ "state": current }))
}

#[tokio::main]
async fn main() {
    let state = AppState { job_state: Arc::new(Mutex::new("waiting".to_string())) };
    let app = Router::new()
        .route("/job/status", get(job_status))
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

The task sets the string to "running" when it starts and "done" when it finishes, and the status route reads whatever value is there now. The Mutex is a lock that lets only one piece of code touch the string at once, which keeps the read and the write from colliding. The .clone() inside the handler copies the string out of the lock so the lock can be released before the response is built. Holding a standard library lock across an await is a mistake this page avoids by cloning the value out first, and a later section shows the same rule in a fuller example.

Clone Values Out of a Lock Before Awaiting:

Read the shared value, clone it, drop the lock, and only then await or build the response. Holding a standard library MutexGuard across an .await makes the handler future unable to move between threads, and Axum requires handler futures to be Send, so the code fails to compile.

What the Task Cannot Do After the Response

Three limits follow from the response already being gone. First, the task cannot change the response. A task that discovers an error cannot turn the 202 into a 500, because the 202 was already sent. Second, the task cannot send its result to the client. There is no open channel back to that request. Third, the task cannot ask the client anything. No follow-up question, no confirmation, no retry prompt.

Those limits decide what belongs in a spawned task. Work that needs a reply from the client does not belong there. Work whose failure the client must know about immediately does not belong there either. Work that belongs there is work the client can afford to hear about later, or never: a report that lands in storage, a file that gets converted for later download, a log entry that gets written, a message that gets sent. When the work fails, the server must find out some other way, and a later page in this cluster covers logging those failures.

Testing the Non-Blocking Behaviour

A test can prove the response arrives before the work finishes by sending a request through the router and checking two things: the status is 202, and the work flag is still false right after the response comes back.

tests/nonblocking_test.rs
use axum::{
    body::Body,
    extract::State,
    http::{Request, StatusCode},
    routing::{get, post},
    Json, Router,
};
use serde::Serialize;
use std::sync::{
    atomic::{AtomicBool, Ordering},
    Arc,
};
use std::time::Duration;
use tokio::time::sleep;
use tower::ServiceExt;

#[derive(Clone)]
struct AppState {
    report_done: Arc<AtomicBool>,
}

#[derive(Serialize)]
struct Status {
    report_done: bool,
}

async fn start_report(State(state): State<AppState>) -> (StatusCode, Json<serde_json::Value>) {
    let flag = Arc::clone(&state.report_done);
    tokio::spawn(async move {
        sleep(Duration::from_millis(200)).await;
        flag.store(true, Ordering::SeqCst);
    });
    (StatusCode::ACCEPTED, Json(serde_json::json!({ "status": "accepted" })))
}

async fn status(State(state): State<AppState>) -> Json<Status> {
    Json(Status { report_done: state.report_done.load(Ordering::SeqCst) })
}

fn app(state: AppState) -> Router {
    Router::new()
        .route("/report", post(start_report))
        .route("/status", get(status))
        .with_state(state)
}

#[tokio::test]
async fn response_arrives_before_work_finishes() {
    let state = AppState { report_done: Arc::new(AtomicBool::new(false)) };
    let flag = Arc::clone(&state.report_done);
    let app = app(state);

    let response = app
        .oneshot(Request::builder().uri("/report").method("POST").body(Body::empty()).unwrap())
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::ACCEPTED);
    assert!(!flag.load(Ordering::SeqCst));

    sleep(Duration::from_millis(400)).await;
    assert!(flag.load(Ordering::SeqCst));
}

The test builds the router in memory and sends a request through it with oneshot, which runs the request without any network connection. The first assertion checks the status is 202. The second checks the flag is still false immediately after the response, which proves the response did not wait for the work. The test then waits 400 milliseconds, longer than the 200 millisecond job, and asserts the flag is true, which proves the work still finished.

The test needs tower with the util feature as a dev dependency, which provides the oneshot method:

Cargo.toml
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }

Run it with cargo test. The output ends with test result: ok, and the two assertions together prove both halves of the behaviour: the answer came first, and the work still got done.

Common Beginner Mistakes

Returning 200 for work that only started

// Wrong - 200 promises the work is done, and it is not
(StatusCode::OK, Json(serde_json::json!({ "status": "accepted" })))

The body says accepted and the status says done, and the client believes the status. Use 202 Accepted whenever the response goes out before the work finishes.

Awaiting the spawned work before answering

// Wrong - awaiting the handle waits for the whole job
let handle = tokio::spawn(build_report());
let _ = handle.await;
(StatusCode::ACCEPTED, Json(serde_json::json!({ "status": "accepted" })))

Awaiting the handle turns the background task back into inline work. The response waits two seconds, and the 202 becomes a lie in the other direction: the work is done, but the status claims it is only accepted. Either await the work and answer 200 with the result, or spawn it, drop the handle, and answer 202 at once.

Checking progress with a borrowed flag

// Wrong - the task cannot borrow the flag, it must own a clone
tokio::spawn(async {
    flag.store(true, Ordering::SeqCst);
});

A spawned task must own everything it uses, so borrowing the flag fails to compile with error E0373. Clone the Arc before the spawn call and move the clone into the task.

Assuming the client will wait for the result

// Wrong - there is no way back to the client after the response
tokio::spawn(async move {
    let result = build_report().await;
    // nothing here can reach the client that already got its 202
});

Once the handler returns, the request is over. The task can store the result somewhere the client can fetch later, or log it, but it cannot send it to the client. Design the status endpoint or the storage step before spawning, not after.

Spawning work the client must hear about

// Wrong - a payment failure inside this task is invisible to the client
tokio::spawn(async move {
    charge_card().await;
});

Work whose failure changes what the client should do next must not be detached. Charge the card inside the handler, await the result, and answer with success or failure. Spawn only the work the client can afford to hear about later or never.

Never Detach Work the Client Must Hear About:

Spawning a payment charge, a password change, or any action whose failure must change the answer is a real bug, not a style choice. The client receives a success response while the work fails silently in the background, and there is no way to take the response back. Keep such work inside the handler, await it, and answer with the real result.

Final Complete Example

This example pulls the page together: an export endpoint that spawns the work and answers 202, a status endpoint that reports the job state from shared state, and a result endpoint that serves the finished export once it exists.

src/main.rs
use axum::{
    extract::State,
    http::StatusCode,
    routing::{get, post},
    Json, Router,
};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::time::sleep;

#[derive(Clone)]
struct AppState {
    job_state: Arc<Mutex<String>>,
    finished: Arc<Mutex<Option<String>>>,
}

async fn start_export(State(state): State<AppState>) -> (StatusCode, Json<serde_json::Value>) {
    let job_state = Arc::clone(&state.job_state);
    let finished = Arc::clone(&state.finished);
    {
        let mut current = job_state.lock().unwrap();
        *current = "running".to_string();
    }
    tokio::spawn(async move {
        sleep(Duration::from_secs(2)).await;
        {
            let mut slot = finished.lock().unwrap();
            *slot = Some("export-2026-11-14.csv".to_string());
        }
        let mut current = job_state.lock().unwrap();
        *current = "done".to_string();
        println!("background export finished");
    });
    (StatusCode::ACCEPTED, Json(serde_json::json!({ "status": "accepted" })))
}

async fn export_status(State(state): State<AppState>) -> Json<serde_json::Value> {
    let current = state.job_state.lock().unwrap().clone();
    Json(serde_json::json!({ "state": current }))
}

async fn export_result(State(state): State<AppState>) -> (StatusCode, Json<serde_json::Value>) {
    let slot = state.finished.lock().unwrap().clone();
    match slot {
        Some(name) => (StatusCode::OK, Json(serde_json::json!({ "file": name }))),
        None => (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!({ "error": "export not ready yet" })),
        ),
    }
}

#[tokio::main]
async fn main() {
    let state = AppState {
        job_state: Arc::new(Mutex::new("waiting".to_string())),
        finished: Arc::new(Mutex::new(None)),
    };
    let app = Router::new()
        .route("/export", post(start_export))
        .route("/export/status", get(export_status))
        .route("/export/result", get(export_result))
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

Two pieces of shared state carry the job. job_state is a string that moves from "waiting" to "running" to "done", and finished holds the name of the finished file once it exists. The handler sets the state to "running" before spawning, inside a block that drops the lock guard before the spawn call. The task sleeps for two seconds, stores the file name, sets the state to "done", and logs a line. Each lock is held only for the few lines that read or write the value, and every clone happens before any await.

Try it from a second terminal:

curl -X POST http://127.0.0.1:3000/export
curl http://127.0.0.1:3000/export/status
curl http://127.0.0.1:3000/export/result

The first call answers at once with {"status":"accepted"} and a 202 status. The status call answers {"state":"running"} before two seconds pass and {"state":"done"} after. The result call answers {"error":"export not ready yet"} with a 404 while the job runs, and {"file":"export-2026-11-14.csv"} with a 200 once it finishes. The 404 before the file exists is honest in the same way the 202 was: it says the result is not ready yet, instead of pretending otherwise.

Summary

The pattern on this page is a trade, and the trade is the thing to remember. The client gives up knowing the result right away, and in return it gets its answer back in a millisecond. The server gives up the ability to report failure through the response, and in return it stops holding connections open for slow work. The status code is what keeps the trade honest: 202 says accepted, the status endpoint says where the work stands, and the result endpoint says when it is ready. Use the pattern when the client can afford to wait for the result and the work can afford to fail quietly in the background with its failure recorded elsewhere. Do not use it when the client needs the result now, or when a failure must change the answer. That line - whether the client needs the result in this response or can fetch it later - is the decision this page exists to teach.