What survives after work is spawned? In examples/src/bin/ep11.rs, tokio::spawn() schedules a preview inside the current process. main() retains its join handle and awaits completion. A persisted Laravel queue job has a different lifetime from this in-memory task.
The spawned preview is scheduled on this program’s Tokio runtime. A Laravel job stored in a persistent queue can remain available after the request ends. That behavior depends on the queue backend and configuration. Laravel’s synchronous driver executes in the current process rather than creating a durable queued handoff.
If our Rust process exits, a spawned task is not a record waiting safely in a database. We have to add persistence and recovery deliberately when the product needs those guarantees.
The source will demonstrate concurrent waiting and observed completion in one process. Predict which value owns the title after async move, then identify who waits for the task to finish.
This lesson covers running concurrent work inside one process with Tokio: an async fn, tokio::spawn, .await, why the spawned task owns its input, and the two layers of failure in task.await??. It compares that with a Laravel queued job and says where the two differ. It leaves out persistence, blocking work beyond a pointer, and multi-threaded runtimes. It assumes Tutorials 2, 5, and 7.
Take a look at Example 1.
Example 1. Complete example (examples/src/bin/ep11.rs)
use std::time::Duration;
use tokio::time::sleep;
async fn preview(title: String) -> Result<String, &'static str> {
if title.trim().is_empty() { return Err("empty title"); }
sleep(Duration::from_millis(10)).await;
Ok(format!("ready: {title}"))
}
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let title = String::from("tests");
let task = tokio::spawn(async move { preview(title).await });
let other = preview("format".into()).await?;
let first = task.await??;
assert_eq!(first, "ready: tests");
assert_eq!(other, "ready: format");
assert_eq!(preview(" ".into()).await, Err("empty title"));
println!("{first}; {other}");
Ok(())
}
It runs as its own Cargo binary and needs Tokio's macros, runtime, and time features. The companion package's Cargo.toml provides them with this dependency table, and the exact resolved versions are recorded in its Cargo.lock:
[dependencies]
tokio = { version = "1", features = ["full"] }
axum = "=0.8.9"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tower = { version = "0.5", features = ["util"] }
Expected output:
cargo run --quiet --bin ep11
ready: tests; ready: formatThe task that was not a job
The spawned task held a String, the word tests, and regarded the work as accepted. It existed in the memory of one process, and a JoinHandle bound to the name task in main was the only record of it. No row described it in any database, and no worker elsewhere knew its name. A task like that is not waiting anywhere once its process exits.
Sometimes an operation is slow and the rest of the program has other things to do while it waits. In Laravel you might dispatch a queued job. Tokio has an answer for the waiting; everything else a queue does, you add deliberately. Take another look at Example 1.
There are four pieces. preview is an async fn, so calling it creates a future. tokio::spawn schedules a future as a task on this program's Tokio runtime and returns a JoinHandle. The async move block takes ownership of title. And .await waits on a future: main awaits a second preview, for format, and then awaits task. That answers the second prediction above. main() is the one that waits for the task to finish, through the handle it kept.
What does await promise?
Inside the future, sleep(...).await can suspend the preview until the timer is ready, and the current-thread runtime can poll another ready task during the wait. The ten-millisecond timer makes that suspension visible without measuring application performance. Run the example, and don't read a speedup into ten-millisecond timers; they demonstrate suspension and benchmark nothing.
Awaiting does not make CPU-heavy work light. A long synchronous calculation inside this task can occupy the executor thread. The example uses a current-thread runtime on purpose, so concurrent waiting is possible without assuming simultaneous execution on several CPU cores.¹
Why the title moves
The async move block in main() takes ownership of title, and calling preview(title).await moves that string into the preview future. That answers the first prediction above. Tokio requires a spawned future to meet a 'static bound, among other bounds, and owning the string avoids a dependency on a borrowed local title.
The 'static bound does not keep this String alive forever. The spawned future owns its input, and that owned value can be dropped when the future finishes. What the bound rules out is borrowed data that cannot remain valid for the required task lifetime. Borrowing is excellent for scoped work; transferring owned input is often convenient when work crosses an independently scheduled boundary. Adding a lifetime annotation cannot make a short-lived stack value live longer.
The compiler helps establish memory validity. It does not know whether the title is authorized, whether the requested operation is useful, or whether a task will meet a deadline. Those remain application decisions.
Two layers of failure
Read task.await?? from left to right. Awaiting task produces a join result. The first ? propagates a join error, such as a task panic. A successful join contains the Result returned by preview(), and the second ? propagates the preview's application error or extracts its string.
Those failures belong to different layers. A user rejection like an empty title is not the same as a task panic, and in production your logs and responses should keep them apart.²
The assertions expect ready: tests from the spawned preview and ready: format from the other one. A separate call checks that blank input returns empty title. After the checks pass, the terminal prints ready: tests; ready: format.
We keep the JoinHandle and await it. Dropping a Tokio JoinHandle detaches the task; it is not a cancellation request. If completion matters, retain a way to observe it. If shutdown matters, define how tasks are notified, how long you wait, and what you do with unfinished work.
Which guarantee do you need?
A Laravel job stored in a persistent queue can remain available after the request ends, though the queue backend and its configuration decide how, and Laravel's synchronous driver, to take the nearest example, executes the job in the current process and creates no durable handoff at all, so that "I dispatched a job" is, until someone names the driver, a statement about the code and not yet about what survives.
Choosing a tool gets easier once you name the guarantee: concurrent waiting, parallel computation, persistent delivery, or recovery after a crash. These are related needs, not synonyms. If the command must run after a laptop restarts, an in-memory spawned task is insufficient; you need a persisted request, a worker that recovers pending work, idempotency or deduplication where effects demand it, and a way to report final status. If you need two pieces of information while one HTTP request is alive, scoped concurrent futures may be enough, and spawning an independent task might add lifecycle work you don't need.
You can also meet the retry case. A queue retries after a worker lost contact with storage, and the operation might already have performed its external effect. Queue retries are not a universal exactly-once guarantee, so test the real failure scenario, especially around payments, file writes, or process execution.
So the task finishes and both lines agree. Now take one job from your application. What must survive a restart? Who observes that it completed? What happens to it at shutdown, and how long does anything wait?
Testing
Pass a blank title into the spawned preview() call and handle its application error explicitly. In a separate variation, make the task panic. Before you run either one, predict which result layer each change affects.
Then compare. Blank input produces an inner preview error after a successful task join. A panic produces an outer join error. The caller should distinguish rejected input from unexpected task failure in its response and telemetry. Restore the passing example afterward, and keep and await the join handle whenever observing completion is part of the requirement.
TL;DR
tokio::spawn schedules work on the program's own runtime, and main() owns the join handle and awaits it, which gives one observation path inside one process. Calling an async fn creates a future, and .await can suspend it while the runtime polls other ready work. The spawned future owns its input to meet Tokio's 'static bound. task.await?? separates a join failure from the preview's own Result. A persisted job needs stored state, recovery, and retry behavior, and this example demonstrates none of them.
¹ When you need blocking work, investigate the runtime's blocking-work facilities and their limits. Cancelling a future does not guarantee that an already-running blocking operation stops. A process adapter also needs an explicit policy for child-process termination and output draining.
² main() uses a boxed error for this compact demonstration. A reusable library can expose structured failure categories instead.