Async Tasks and Concurrency
Part 2 · Laravel Rust. Do several things at once in a Laravel Rust handler: task::try_join!, task::select!, spawn_blocking, background work and in-process ticks.
Picture the Rusty Bean Café on a busy morning. One barista who makes every drink from start to finish, one at a time, would leave a long line. A good barista starts the espresso shot, and while it pulls, steams the milk. Nothing is rushed. The work overlaps.
Your web handlers can do the same thing. In this lesson you will learn the helpers in laravel::task that let a handler run several jobs at once, race two of them, hand heavy work to a separate thread, and keep small chores running in the background.
Note
Laravel Rust entered beta on December 1, 2026, and its API may still change. Every snippet in this lesson is adapted from the official Concurrency and Tasks guide (opens in new tab). When in doubt, the guide wins.
Why concurrency matters
Many things a handler does are waiting: waiting for the database to answer, waiting for another website to reply. While your code waits, the computer has nothing to do for that request.
Laravel Rust is built on Tokio, the async engine you met in Async/Await and Tokio. Every handler is an async fn, and every .await is a place where your code says “I’m waiting, go serve someone else”. Laravel’s own announcement says the database, HTTP client, Redis, queues and WebSockets are all non-blocking, and that its internal benchmarks on Laravel Cloud show Laravel Rust running 18x faster than Laravel PHP. That is Laravel’s claim from its own tests, not something we measured here.
The laravel::task module gives you ready-made helpers. The guide says to prefer them over plain tokio::spawn, because they carry your application’s context (config, logging, the HTTP client) into the new work.
Running things together with task::try_join!
Imagine the café owner opens a dashboard that shows how many menu items and how many orders exist. Those two counts do not depend on each other, so there is no reason to wait for one before asking for the other.
use laravel::db;use laravel::prelude::*;use laravel::task;use serde_json::json;
pub async fn show() -> laravel::Result<Json<serde_json::Value>> { let (menu_items, orders) = task::try_join!( db::table("menu_items").count(), db::table("orders").count(), )?;
Ok(Json(json!({ "menu_items": menu_items, "orders": orders })))}Step by step:
task::try_join!takes several futures. A future is a piece of async work that has not finished yet.- Notice there is no
.awaiton the two counts. The macro awaits them for you. - It runs both at the same time and hands back a tuple, in the order you wrote them.
- The
try_part means that if either one fails, the whole thing stops early with that error, and?passes it on. - The response is only as slow as the slowest query, not the sum of both.
If your operations do not return a Result, use task::join! instead.
Tip
try_join! and select! run inside your current task, so the operations can borrow local variables from your handler. They share one thread and take turns while waiting on I/O.
Racing with task::select!
Sometimes you want the first answer, not all of them. Suppose the café asks two delivery services for a time estimate and uses whichever replies first.
use laravel::http::client;use laravel::task;
pub async fn estimate() -> laravel::Result<String> { let response = task::select! { response = client::get("https://courier-a.example.com/estimate") => response?, response = client::get("https://courier-b.example.com/estimate") => response?, };
Ok(response.text().into_owned())}The first branch to finish wins. Its code after => runs, and the other future is dropped, which cancels it. Both task::select! and task::try_join! are re-exports of Tokio’s macros, so what you learn here works in plain Tokio too.
The guide also describes task::map (run many items with a limit on how many go at once), task::timeout (give up after a deadline) and task::sleep (pause without blocking the thread). They are worth a read once these basics feel comfortable.
Heavy work: task::spawn_blocking
Here is a trap. Async code only works well if every task hands control back quickly at its .await points. If you run a long calculation with no .await, you hog the thread, and every other request sharing it has to wait. The guide’s examples are CPU-heavy work such as resizing images or building a large export.
The fix is task::spawn_blocking, which runs a normal (non-async) closure on a separate pool of threads made for exactly this:
use laravel::task;
pub async fn export() -> laravel::Result<String> { let csv = task::spawn_blocking(move || { // Build a large CSV report with a synchronous library... String::from("item,total_cents\nLatte,450\n") }) .await?;
Ok(csv)}Note the .await after spawn_blocking: the handler waits for the result, but the busy thread is not yours.
Warning
Database queries and HTTP client calls are already async. Do not wrap them in spawn_blocking. Also, once a blocking closure has started, it cannot be cancelled halfway.
Work after the response: task::background
When a customer marks an order as picked up, they should not wait while you notify an outside system. task::background starts a task right away and lets your handler return its response.
use laravel::http::client;use laravel::prelude::*;use laravel::task;use serde_json::json;
pub async fn ready(Params(id): Params<i64>) -> laravel::Result<Redirect> { // Mark the order as ready for pickup...
task::background(async move { client::post("https://example.com/webhooks/order-ready") .json(json!({ "order_id": id })) .ensure_successful() .await?;
Ok(()) })?;
Ok(Redirect::back())}Params<i64>reads the order’s ID from the URL. The Routing and Handlers lesson usedu64for plain path numbers, but Laravel’s own examples usei64for IDs that go on to models and jobs, because model IDs arei64. Either works for parsing a path.async movecopies the ownedidinto the task. The task may outlive the request, so it must not borrow from it.- The task returns
laravel::Result<()>. Laravel reports errors and panics just like it does for handlers. - During a graceful shutdown, the server waits for background tasks to finish (up to
SERVER_SHUTDOWN_TIMEOUT).
Important
Background tasks are not a queue. They are not retried, and if the process dies, unfinished work is lost. The guide’s own advice: for work that must succeed, such as charging a card or sending a receipt, dispatch a queued job. That is the topic of the next lesson.
There is also task::spawn, which gives you a handle to await later. Dropping that handle does not cancel the task, but shutdown will not wait for it either.
Ticks: small chores inside each process
Some state lives in memory inside one running program. For example, the café site might count menu page views in memory and write the total to the database every ten seconds instead of on every visit. A tick is a function Laravel calls on a repeating interval. You register ticks in src/app.rs:
use laravel::prelude::*;
use crate::services::MenuViewCounts;
async fn flush_view_counts(counts: Inject<MenuViewCounts>) -> laravel::Result<()> { counts.flush().await}
Application::configure() .with_ticks(|ticks, _| { ticks .every(10.seconds(), flush_view_counts) .name("flush-view-counts") .when(|host| host.is_server()) .run_on_shutdown(); })Reading it:
every(10.seconds(), ...)runs the function on that interval. The next wait starts after the previous tick finishes, so ticks never overlap.name(...)labels it in logs and tests.when(|host| host.is_server())limits it to the web server process, not queue workers.run_on_shutdown()runs it one last time as the app stops, so buffered counts are not lost.
MenuViewCounts is a service you would write yourself, so this snippet is illustrative. In a test, you can run a named tick directly with app.tick("flush-view-counts").await?.
Ticks run in every server process and every queue worker. For something that must happen once across your whole fleet, use the scheduler instead (see the Task Scheduling guide (opens in new tab)).
Try it yourself
- A dashboard also needs a count of
users(your customers). Add it to thetry_join!call. - Decide for each case whether to use
task::backgroundor a queued job: (a) pinging a “new order” webhook, (b) emailing the customer’s receipt.
Show solution
- Three futures, a three-item tuple, and one more key in the JSON:
let (menu_items, orders, users) = task::try_join!( db::table("menu_items").count(), db::table("orders").count(), db::table("users").count(),)?;- (a) is a good fit for
task::background: it is lightweight and nobody is hurt if one ping is lost. (b) should be a queued job, because the receipt must be retried if sending fails.
Recap
task::try_join!runs independent async operations at the same time and returns their results in order, stopping at the first error.task::select!races operations and keeps only the winner.task::spawn_blockingmoves CPU-heavy, non-async work off the async threads.task::backgroundruns lightweight work after the response, but it is not retried and can be lost.- Ticks run small repeating chores inside each server or worker process.
What’s next
When work must not be lost, you need a queue. Continue to Queued Jobs.
0 of 35 lessons complete