tokio spawn - starting a background task in Axum
Learn what tokio spawn does, how it starts a background task, what the static and Send rules mean in plain words, and what happens when the handle is dropped
A handler normally does its work and then answers. Some work does not fit that shape. A report that takes ten seconds to build, a file that needs converting, a message that needs sending - the client does not need to sit and wait for any of those. tokio::spawn starts that work as a background task and returns at once, so the handler can answer while the work carries on.
Where This Fits
Earlier pages built handlers that awaited every step before answering. The handler read the body, did the work, and only then sent the response. That shape is right when the client needs the result of the work. It is the wrong shape when the client only needs to know the work has started. This page adds the other shape. It shows how to hand work to the runtime and move on.
Think of a kitchen taking a phone order. The person on the phone writes the order down, says thank you, and hangs up. The cooking starts after the call ends. The caller does not stay on the line listening to the oven. tokio::spawn is the act of handing the order to the kitchen.
The Smallest Working Version
Start with a plain program, no web server at all. It spawns one task that prints a line after a short wait, while the main flow prints its own line straight away.
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
tokio::spawn(async {
sleep(Duration::from_millis(200)).await;
println!("background task finished its work");
});
println!("main flow carries on without waiting");
sleep(Duration::from_millis(400)).await;
}
The Cargo.toml file needs Tokio with the full feature set, which turns on the runtime, the timer used by sleep, and task spawning:
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
Run it with cargo run. The terminal prints two lines, and the order matters:
main flow carries on without waiting
background task finished its work
The main flow printed first even though the spawn call came first in the file. The spawned task waited 200 milliseconds before printing, and the main flow did not wait for it. The final sleep in main exists for one reason only: it keeps the program alive long enough for the background task to finish. Without it, main would return, the runtime would shut down, and the background task would be cut off mid-work. That detail matters, and it comes back later in this page.
Working Setup:
If the output shows the main-flow line first and the background-task line second, spawning works. The order proves the two flows ran side by side instead of one after the other.
Understanding the Spawn Call Line by Line
The spawn call is short, but three pieces of it do real work. Each one deserves a plain explanation.
The function itself
tokio::spawn(async {
tokio::spawn is a function from the Tokio runtime. A runtime is the engine that runs async code: it keeps track of every task that is waiting, wakes each one up when the thing it waited for is ready, and shares the work across threads. Calling spawn hands a new piece of async work to that engine. The engine starts running it and the call returns at once. It does not wait for the work to finish, and it does not return the result of the work. It returns a handle, which is covered in detail on its own page, and for now you can ignore the return value.
The async block
async {
sleep(Duration::from_millis(200)).await;
println!("background task finished its work");
}
The argument to spawn is an async block, which is a chunk of code that can pause at .await points and resume later. Inside the block, sleep pauses the task for 200 milliseconds without blocking the thread it runs on. While this task sleeps, the runtime is free to run other tasks on the same thread. That is the whole point of async work: waiting does not waste the thread. After the pause, the println! runs.
The missing await
There is no .await after the spawn call. That absence is the feature. Writing tokio::spawn(...).await would wait for the background task to finish, which throws away the reason for spawning it. The call itself is not async in the waiting sense: it schedules the work and returns immediately.
Spawn Returns at Once:
tokio::spawn schedules the task and returns immediately. It does not run the task to completion before returning, and it does not guarantee the task starts before the next line runs. The task runs when the runtime schedules it, which is usually very soon, but the exact moment is the runtime's decision.
What a Task Is
A task is a single piece of async work that the runtime manages on its own. It has its own stack of .await points, its own lifetime, and no connection to the code that created it once it has been spawned. The runtime keeps a list of tasks, polls each one when it is ready to make progress, and drops it when it finishes.
A useful way to picture it is a to-do list on a kitchen wall. Each order on the wall is a task. The cooks pick orders off the wall, work on whichever one is ready, and cross it off when it is done. Nobody stands over one order from start to finish while the others wait. The runtime is the kitchen, and each spawned task is one order on the wall.
Tasks are cheap. Spawning one does not start a new operating system thread, and it does not copy a large block of memory. The runtime runs many tasks on a small number of worker threads, switching between them at .await points. That is why a server can have thousands of tasks alive at once without trouble.
Spawning Instead of Awaiting Inline
The difference between awaiting inline and spawning is the difference between doing a job yourself and handing it to someone else. Both get the job done. Only one lets you move on.
use std::time::Duration;
use tokio::time::sleep;
async fn slow_job() {
sleep(Duration::from_secs(2)).await;
println!("slow job finished");
}
#[tokio::main]
async fn main() {
println!("starting the slow job inline");
slow_job().await;
println!("inline version reaches this line after 2 seconds");
println!("starting the slow job as a task");
tokio::spawn(slow_job());
println!("spawned version reaches this line at once");
sleep(Duration::from_secs(3)).await;
}
Running this prints the lines in this order, with a two second pause before the third line and no pause before the fifth:
starting the slow job inline
slow job finished
inline version reaches this line after 2 seconds
starting the slow job as a task
spawned version reaches this line at once
slow job finished
The inline version waits. The spawned version does not. The spawned job still finishes, and its final line appears at the end, after the main flow has already moved on. That ordering is the behaviour a handler wants when the client should not wait: start the job, answer at once, and let the job finish in its own time.
Spawn Is Not Parallelism:
Spawning a task makes work run concurrently, which means the flows overlap in time. It does not by itself make work run on two CPU cores at the same moment. The runtime may run tasks on different threads, and often does, but the guarantee spawn gives you is overlap, not simultaneous execution on separate cores. For the slow waiting work in this chapter, overlap is exactly what matters.
The Static Rule in Plain Words
tokio::spawn has one strict rule about the data a task uses: the task must own everything it touches, or share it through a type built for sharing. In Rust terms, the future passed to spawn must be 'static, which means it cannot borrow data that lives in the function that spawned it.
The reason is simple once you see it. A spawned task can outlive the function that created it. If the task borrowed a local variable, that variable could be dropped while the task was still using it, and the task would read freed memory. Rust refuses to let that happen, so it demands ownership instead of borrowing.
This code does not compile:
// Wrong - the task borrows greeting, which may be gone before the task runs
let greeting = String::from("hello");
tokio::spawn(async {
println!("{}", greeting);
});
The compiler stops it with this error, verified against the real compiler:
error[E0373]: async block may outlive the current function, but it borrows `greeting`, which is owned by the current function
help: to force the async block to take ownership of `greeting` (and any other referenced variables), use the `move` keyword
The fix is the move keyword, which moves the values the block uses into the block instead of borrowing them:
let greeting = String::from("hello");
tokio::spawn(async move {
println!("{}", greeting);
});
With move, the String belongs to the task now. The function that spawned the task can no longer use greeting afterwards, because ownership moved. That is the trade the rule asks for: the task gets data it fully owns, so nothing it touches can vanish underneath it.
Borrowing Across Spawn Never Compiles:
Any borrow of a local variable inside a spawned task is a compile error, not a warning and not a runtime surprise. The compiler error names the borrowed value and suggests move. Add move to the async block and clone the data first if the spawning code still needs its own copy.
When the spawning code still needs the value, clone it before moving:
let name = String::from("Asha");
let name_for_task = name.clone();
tokio::spawn(async move {
println!("background work for {}", name_for_task);
});
println!("handler still has its own copy: {}", name);
Cloning a String copies its text, so the task and the spawning code each own a separate copy. For values shared between many tasks, the usual shape is an Arc, a reference-counted pointer that lets many owners share one value, combined with a Mutex when the value also needs changing. That combination appears in the richer examples below.
The Send Rule in Plain Words
The second rule is about threads. A spawned task can be moved between worker threads by the runtime, so everything the task owns must be safe to send between threads. In Rust terms, the future must be Send. Most ordinary values are Send: String, numbers, Vec, and Arc all qualify. A few values are not, and the classic example is Rc, the single-threaded reference-counted pointer.
This code does not compile:
// Wrong - Rc cannot travel between threads
use std::rc::Rc;
let value = Rc::new(5);
tokio::spawn(async move {
println!("{}", value);
});
The compiler stops it with this error, verified against the real compiler:
error: future cannot be sent between threads safely
= help: within `{async block@...}`, the trait `Send` is not implemented for `Rc<i32>`
note: captured value is not `Send`
The fix is to use Arc instead of Rc. Arc does the same job - shared ownership through reference counting - but it uses atomic operations that are safe across threads:
use std::sync::Arc;
let value = Arc::new(5);
tokio::spawn(async move {
println!("{}", value);
});
The same rule applies to RefCell and Cell, which are also single-threaded. Their thread-safe counterparts are Mutex and RwLock from Tokio or the standard library, and atomic types like AtomicBool for simple flags. When the compiler complains that a future is not Send, the value it names is the one to replace with its thread-safe counterpart.
Send Errors Name the Value:
When a spawn call fails with a Send error, read the note at the bottom of the compiler message. It names the exact captured value that is not Send. Replace that one value - usually Rc with Arc, or RefCell with a Mutex - and the rest of the code stays the same.
What Happens When the Handle Is Dropped
tokio::spawn returns a value called a JoinHandle. Dropping that handle does not stop the task. The task keeps running in the background, detached, and its return value is simply lost. This surprises almost every beginner, because dropping most things in Rust cleans them up. A JoinHandle is the exception: dropping it only throws away your way of reaching the task.
This was verified by running a real program. The handle is dropped inside a block, and the task still finishes afterwards:
use std::sync::{
atomic::{AtomicBool, Ordering},
Arc,
};
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let done = Arc::new(AtomicBool::new(false));
let flag = Arc::clone(&done);
{
let handle = tokio::spawn(async move {
sleep(Duration::from_millis(200)).await;
flag.store(true, Ordering::SeqCst);
println!("detached task finished its work");
});
drop(handle);
println!("handle dropped, main keeps going");
}
sleep(Duration::from_millis(400)).await;
println!("flag after drop: {}", done.load(Ordering::SeqCst));
}
The output proves the task survived the drop:
handle dropped, main keeps going
detached task finished its work
flag after drop: true
The flag is true at the end, which means the task ran to completion after its handle was gone. The shared flag uses an Arc so both the task and main can reach it, and an AtomicBool so the task can set it safely from another thread without a lock. The Ordering::SeqCst argument is the strictest memory ordering, and for a simple flag it is the safe default choice.
This behaviour is exactly what a fire-and-forget handler wants: spawn the work, drop the handle, answer the client. The task lives on without anyone watching it. The cost is that nobody will ever know if it fails, which is why detached tasks need their errors logged somewhere the server can see them. For now, the rule to carry forward is one sentence: dropping the handle detaches the task, it never cancels it.
Spawning From Inside a Handler
Inside an Axum handler, tokio::spawn works exactly the same way, because a handler runs on the Tokio runtime. The handler spawns the slow work, drops the handle, and returns its response at once.
use axum::{routing::post, Json, Router};
use std::time::Duration;
use tokio::time::sleep;
async fn start_export() -> Json<serde_json::Value> {
tokio::spawn(async {
sleep(Duration::from_secs(5)).await;
println!("export finished");
});
Json(serde_json::json!({ "status": "export started" }))
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/export", post(start_export));
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();
}
Send a request with curl -X POST http://127.0.0.1:3000/export and the response comes back at once with {"status":"export started"}, while export finished appears in the server terminal five seconds later. The handler returned before the work finished, and the work still ran. The handler did not need to hold the response open, and the client did not need to wait.
The serde_json::json! macro builds the JSON body, and the Json wrapper marks it as a JSON response. The route uses post because starting an export creates work on the server, which fits the meaning of POST. The bind address 127.0.0.1:3000 keeps the server reachable only from the same machine.
Spawning Several Tasks at Once
One spawn call starts one task. A loop that spawns inside it starts many, and they run side by side. Each task gets its own copy of the data it needs through move and clone.
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
for id in 1..=3 {
tokio::spawn(async move {
sleep(Duration::from_millis(100 * id)).await;
println!("task {} finished", id);
});
}
println!("all three tasks started");
sleep(Duration::from_millis(500)).await;
}
The output shows the tasks finishing in order of their sleep time, not in spawn order alone:
all three tasks started
task 1 finished
task 2 finished
task 3 finished
The loop variable id is a plain number, and numbers are Copy, so moving it into each task is free. Each task sleeps a different length of time, and the runtime interleaves them. The final sleep keeps main alive until the slowest task finishes. Without it, the program could exit while tasks were still waiting.
The Runtime Must Be Running
tokio::spawn panics when it is called outside a Tokio runtime. There is no runtime to hand the task to, so the call fails loudly instead of silently dropping the work. This was verified by running a plain fn main that calls spawn with no runtime:
thread 'main' panicked at src/bin/bad_outside.rs:2:14:
there is no reactor running, must be called from the context of a Tokio 1.x runtime
In an Axum server this never happens by accident, because #[tokio::main] starts the runtime before main runs, and every handler runs inside it. It only bites in plain programs, in tests that forget the #[tokio::test] attribute, and in code called from a non-async context. The fix is always the same: make sure a runtime is running first.
Spawn Outside a Runtime Panics:
Calling tokio::spawn from a plain fn main, from a synchronous test, or from any code that runs before the runtime starts panics at once. In an Axum app, handlers and #[tokio::main] code are always inside the runtime, so the panic only shows up in standalone programs and in tests missing the async test attribute.
How Spawning Fits Together
The flow from a request to a finished background task looks like this in plain text:
Client sends POST /export
|
v
Handler runs on a Tokio worker thread
|
v
tokio::spawn hands the slow work to the runtime
|
v
Handler returns a response at once
|
v
Client receives the response
|
v
Runtime runs the spawned task when it is ready
|
v
Task finishes on its own, after the response is gone
The response and the work are on separate timelines after the spawn call. Nothing joins them back together unless the handler chooses to await the handle.
Testing That a Spawned Task Runs
A test can prove a spawned task ran by sharing a flag between the task and the test, then waiting long enough for the task to set it. The test itself needs the #[tokio::test] attribute so a runtime exists.
use std::sync::{
atomic::{AtomicBool, Ordering},
Arc,
};
use std::time::Duration;
use tokio::time::sleep;
#[tokio::test]
async fn spawned_task_runs_after_spawn_returns() {
let done = Arc::new(AtomicBool::new(false));
let flag = Arc::clone(&done);
tokio::spawn(async move {
sleep(Duration::from_millis(50)).await;
flag.store(true, Ordering::SeqCst);
});
assert!(!done.load(Ordering::SeqCst));
sleep(Duration::from_millis(200)).await;
assert!(done.load(Ordering::SeqCst));
}
The first assertion checks the flag is still false right after spawning, which proves the task had not finished yet. The test then waits 200 milliseconds and asserts the flag is true, which proves the task ran. The test needs tokio with the full feature and macros turned on for the #[tokio::test] attribute, which the full feature set already includes.
[dev-dependencies]
tokio = { version = "1", features = ["full"] }
Run it with cargo test. The output ends with test result: ok, and the two assertions together prove both halves of the behaviour: spawn returns at once, and the task still runs.
Common Beginner Mistakes
Forgetting move and borrowing a local
// Wrong - borrows name, which may be gone before the task runs
let name = String::from("Asha");
tokio::spawn(async {
println!("{}", name);
});
The compiler rejects this with error E0373. Add move to the async block so the task owns the value. Clone first if the spawning code still needs its own copy.
Using Rc or RefCell inside a task
// Wrong - Rc is not Send, so the task cannot move between threads
use std::rc::Rc;
let value = Rc::new(5);
tokio::spawn(async move {
println!("{}", value);
});
The compiler rejects this because the future is not Send. Replace Rc with Arc, and RefCell with a Mutex, and the same code compiles.
Awaiting the spawn call
// Wrong - awaiting the handle waits for the whole task, which defeats spawning
let result = tokio::spawn(slow_job()).await;
Awaiting the handle turns the background task back into inline work. The handler waits for the slow job before answering, which is exactly what spawning was meant to avoid. Drop the handle instead, and let the task run detached. Awaiting the handle is a real pattern, but it belongs where the result is actually needed.
Assuming the task finished because spawn returned
// Wrong - spawn returning says nothing about the work being done
tokio::spawn(slow_job());
println!("job done"); // this line is a lie, the job has only just started
spawn returning means the work was accepted, not completed. Any code that needs the result must await the handle, and any code that needs to know the work finished must share a flag or a channel with the task. The response a handler sends after spawning should say the work started, never that it finished.
Letting main return before the task finishes
// Wrong - the program can exit while the task is still waiting
#[tokio::main]
async fn main() {
tokio::spawn(slow_job());
}
When main returns, the runtime shuts down and drops every task that is still running. In a server this never happens, because axum::serve runs forever. In a plain program, keep main alive with a sleep, a wait on a signal, or an await on the handle, until the work you care about is done.
Final Complete Example
This example pulls the whole page together: an Axum server with an export route that spawns slow work, a status route that shares a flag with the task so the client can check on it, and a counter that shows how many exports have finished.
use axum::{
extract::State,
routing::{get, post},
Json, Router,
};
use std::sync::{
atomic::{AtomicUsize, Ordering},
Arc,
};
use std::time::Duration;
use tokio::time::sleep;
#[derive(Clone)]
struct AppState {
finished_exports: Arc<AtomicUsize>,
}
async fn start_export(State(state): State<AppState>) -> Json<serde_json::Value> {
let finished = Arc::clone(&state.finished_exports);
tokio::spawn(async move {
sleep(Duration::from_secs(2)).await;
finished.fetch_add(1, Ordering::SeqCst);
println!("export finished");
});
Json(serde_json::json!({ "status": "export started" }))
}
async fn export_count(State(state): State<AppState>) -> Json<serde_json::Value> {
Json(serde_json::json!({ "finished_exports": state.finished_exports.load(Ordering::SeqCst) }))
}
#[tokio::main]
async fn main() {
let state = AppState { finished_exports: Arc::new(AtomicUsize::new(0)) };
let app = Router::new()
.route("/export", post(start_export))
.route("/exports/finished", get(export_count))
.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 state holds an AtomicUsize, a counter that can be changed safely from any thread without a lock. fetch_add adds one to it, and load reads it. The handler clones the Arc into the task, so the task and the state share the same counter. The counter starts at zero, and each finished export adds one.
Run the server, then try it from a second terminal:
curl -X POST http://127.0.0.1:3000/export
curl http://127.0.0.1:3000/exports/finished
The first call answers at once with {"status":"export started"}. The second call answers {"finished_exports":0} if the two seconds have not passed yet, and {"finished_exports":1} after they have. The count changing between calls is the proof that the background task ran after the response was already sent.
Summary
The decision that matters is not how to spell tokio::spawn, it is when the client should stop waiting. If the client needs the result, await the work inline and answer with it. If the client only needs to know the work started, spawn it and answer at once. Everything else on this page follows from that choice: the task must own its data because it can outlive its creator, it must be Send because the runtime can move it between threads, and dropping its handle detaches it rather than stopping it, so a spawned task is a commitment the server keeps after the response is gone. That commitment is what makes the next pages necessary. Once work runs on its own timeline, you need a way to get its result back, a way to answer honestly while it runs, and a way to find out when it fails.