Concurrency and Tasks
- Introduction
- Running operations concurrently
- Time limits and pauses
- Background work
- Spawned tasks
- Blocking work
- Ticks
Introduction
Requests often need to perform several independent operations, such as counting both users and orders for a dashboard. Running those operations concurrently makes the response only as slow as the slowest query rather than the sum of all of them. Other work, such as notifying a webhook after an order ships, doesn't need to delay the HTTP response at all.
The laravel::task module provides helpers for running work concurrently and in the background. Prefer these helpers over tokio::spawn: they propagate the application's context and tracing span into the spawned work so resolve, config, the HTTP client, and logging continue working as expected.
Running operations concurrently
To run multiple operations concurrently and wait for all of them to finish, use task::try_join!. It returns each output in the order you passed the operations, or short-circuits on the first error. For example, this dashboard handler counts users and orders in parallel:
1use laravel::db;2use laravel::prelude::*;3use laravel::task;4use serde_json::json;56pub async fn show() -> laravel::Result<Json<serde_json::Value>> {7 let (users, orders) = task::try_join!(8 db::table("users").count(),9 db::table("orders").count(),10 )?;1112 Ok(Json(json!({ "users": users, "orders": orders })))13}1use laravel::db;2use laravel::prelude::*;3use laravel::task;4use serde_json::json;56pub async fn show() -> laravel::Result<Json<serde_json::Value>> {7 let (users, orders) = task::try_join!(8 db::table("users").count(),9 db::table("orders").count(),10 )?;1112 Ok(Json(json!({ "users": users, "orders": orders })))13}
Pass the futures without .await, since the macro awaits them for you. When the operations do not return a Result, use task::join! instead.
To race several operations and continue as soon as the first one finishes, use task::select!. It executes the winning branch and drops the remaining futures, cancelling them. For example, this handler queries two exchange-rate providers and returns whichever responds first:
1use laravel::http::client;2use laravel::task;34pub async fn rates() -> laravel::Result<String> {5 let response = task::select! {6 response = client::get("https://rates.example.com/latest") => response?,7 response = client::get("https://backup-rates.example.com/latest") => response?,8 };910 Ok(response.text().into_owned())11}1use laravel::http::client;2use laravel::task;34pub async fn rates() -> laravel::Result<String> {5 let response = task::select! {6 response = client::get("https://rates.example.com/latest") => response?,7 response = client::get("https://backup-rates.example.com/latest") => response?,8 };910 Ok(response.text().into_owned())11}
These are re-exports of Tokio's macros. Because they run within the current task, the operations can borrow local variables from your handler. They share one thread and interleave while waiting on I/O, which works well for database queries and HTTP requests. Code that blocks the thread stalls the other operations too, so move blocking work to spawn_blocking.
Limiting concurrency
Sometimes you have a list of items to process, such as fetching the GitHub profile of each organization on a user's account, and the upstream API limits how many requests you may send at once. Pass the collection, the maximum number of operations to run at the same time, and an async closure to task::map:
1use laravel::http::client;2use laravel::prelude::*;3use laravel::task;4use serde_json::Value;56pub async fn index() -> laravel::Result<Json<Vec<Value>>> {7 let orgs = ["laravel", "rust-lang", "tokio-rs"];89 let profiles = task::map(orgs, 5, async |org| {10 client::get("https://api.github.com/orgs/{org}")11 .url_parameters([("org", org)])12 .await?13 .json::<Value>()14 })15 .await?;1617 Ok(Json(profiles))18}1use laravel::http::client;2use laravel::prelude::*;3use laravel::task;4use serde_json::Value;56pub async fn index() -> laravel::Result<Json<Vec<Value>>> {7 let orgs = ["laravel", "rust-lang", "tokio-rs"];89 let profiles = task::map(orgs, 5, async |org| {10 client::get("https://api.github.com/orgs/{org}")11 .url_parameters([("org", org)])12 .await?13 .json::<Value>()14 })15 .await?;1617 Ok(Json(profiles))18}
task::map returns the results in the order of the input items, so profiles[0] is always the profile for laravel regardless of which request finished first. If any call returns an error, task::map stops starting remaining items, drops the other in-flight futures to cancel them, and returns that error.
Time limits and pauses
An outgoing request waits as long as the remote service takes, which can tie up your handler if an upstream service hangs. To enforce a deadline, pass a duration and a future to task::timeout. Because the operation's own Result is nested inside the timeout's Result, unwrap both with ??:
1use laravel::http::client;2use laravel::prelude::*;3use laravel::task;45pub async fn rates() -> laravel::Result<String> {6 let response = task::timeout(7 3.seconds(),8 client::get("https://rates.example.com/latest"),9 )10 .await??;1112 Ok(response.text().into_owned())13}1use laravel::http::client;2use laravel::prelude::*;3use laravel::task;45pub async fn rates() -> laravel::Result<String> {6 let response = task::timeout(7 3.seconds(),8 client::get("https://rates.example.com/latest"),9 )10 .await??;1112 Ok(response.text().into_owned())13}
If the operation does not finish in time, timeout cancels it and returns a task::TimedOut error, which Laravel renders as a 504 Gateway Timeout response. Since the outer Result only fails on timeout, you can match on it to fall back cleanly, such as returning cached rates:
1use laravel::cache;2use laravel::http::client;3use laravel::prelude::*;4use laravel::task;56pub async fn rates() -> laravel::Result<String> {7 let request = client::get("https://rates.example.com/latest");89 match task::timeout(3.seconds(), request).await {10 Ok(response) => Ok(response?.text().into_owned()),11 Err(_) => Ok(cache::get::<String>("rates").await?.unwrap_or_default()),12 }13}1use laravel::cache;2use laravel::http::client;3use laravel::prelude::*;4use laravel::task;56pub async fn rates() -> laravel::Result<String> {7 let request = client::get("https://rates.example.com/latest");89 match task::timeout(3.seconds(), request).await {10 Ok(response) => Ok(response?.text().into_owned()),11 Err(_) => Ok(cache::get::<String>("rates").await?.unwrap_or_default()),12 }13}
To pause execution without blocking the thread (for example, between rate-limited API calls), await task::sleep. Other requests continue running while the task sleeps:
1use laravel::prelude::*;2use laravel::task;34task::sleep(500.milliseconds()).await;1use laravel::prelude::*;2use laravel::task;34task::sleep(500.milliseconds()).await;
Background work
When the user does not need to wait for an operation to finish, run it with task::background. The task starts immediately while your handler returns its response. For example, this handler marks an order as shipped and notifies a webhook in the background:
1use laravel::http::client;2use laravel::prelude::*;3use laravel::task;4use serde_json::json;56pub async fn ship(Params(id): Params<u64>) -> laravel::Result<Redirect> {7 // Mark the order as shipped...89 task::background(async move {10 client::post("https://example.com/webhooks/shipped")11 .json(json!({ "order_id": id }))12 .ensure_successful()13 .await?;1415 Ok(())16 })?;1718 Ok(Redirect::back())19}1use laravel::http::client;2use laravel::prelude::*;3use laravel::task;4use serde_json::json;56pub async fn ship(Params(id): Params<u64>) -> laravel::Result<Redirect> {7 // Mark the order as shipped...89 task::background(async move {10 client::post("https://example.com/webhooks/shipped")11 .json(json!({ "order_id": id }))12 .ensure_successful()13 .await?;1415 Ok(())16 })?;1718 Ok(Redirect::back())19}
The future returns laravel::Result<()>, and Laravel reports any errors or panics as it does for handlers. Capture owned values such as IDs with async move, and avoid reading the request or session inside the task since it may outlive the HTTP response. background itself only returns an error if the application has already started shutting down, so propagate it with ?.
During graceful shutdown, the server waits for in-flight background work to complete, up to SERVER_SHUTDOWN_TIMEOUT. Console commands also wait for background work before exiting, so you may use task::background inside commands and scheduled callbacks as well.
Background work is not a replacement for a queue. Tasks are not retried on failure and any unfinished work is lost if the process exits unexpectedly. For work that must succeed reliably, such as charging a card or sending a receipt, dispatch a queued job instead.
Spawned tasks
Sometimes you want to kick off an operation, perform other work in the meantime, and collect its output later in the same handler. task::spawn starts the future as an independent task that may run on another worker thread and returns a handle you can await. Like the other helpers in laravel::task, it carries the current application context and tracing span into the new task:
1use laravel::db;2use laravel::prelude::*;3use laravel::task;4use serde_json::json;56pub async fn show() -> laravel::Result<Json<serde_json::Value>> {7 let orders = task::spawn(async { db::table("orders").count().await });89 let users = db::table("users").count().await?;10 let orders = orders.await??;1112 Ok(Json(json!({ "users": users, "orders": orders })))13}1use laravel::db;2use laravel::prelude::*;3use laravel::task;4use serde_json::json;56pub async fn show() -> laravel::Result<Json<serde_json::Value>> {7 let orders = task::spawn(async { db::table("orders").count().await });89 let users = db::table("users").count().await?;10 let orders = orders.await??;1112 Ok(Json(json!({ "users": users, "orders": orders })))13}
A spawned task must own any data it uses, so capture values with async move. Awaiting the handle fails if the task panicked; otherwise it returns the task's output. When that output is itself a Result, ?? unwraps both layers. Spawned task errors are not reported automatically, so return them from your handler or report them directly.
Dropping the handle does not cancel the task; it continues running in the background, though server shutdown will not wait for it. Use task::background for work that graceful shutdown should wait for.
Blocking work
CPU-intensive work or synchronous libraries (such as image resizing or building a large export) block their OS thread until finished, delaying other requests sharing that thread. Offload blocking code with task::spawn_blocking, which runs the closure on a dedicated blocking thread pool while preserving your application context and tracing span:
1use laravel::task;23pub async fn export() -> laravel::Result<String> {4 let csv = task::spawn_blocking(move || {5 // Build a large CSV report with a synchronous library...6 String::from("id,total\n1,100\n")7 })8 .await?;910 Ok(csv)11}1use laravel::task;23pub async fn export() -> laravel::Result<String> {4 let csv = task::spawn_blocking(move || {5 // Build a large CSV report with a synchronous library...6 String::from("id,total\n1,100\n")7 })8 .await?;910 Ok(csv)11}
Database queries and HTTP client requests are already async and do not need spawn_blocking. Once a blocking closure starts running, it cannot be cancelled mid-flight; wrapping its handle in task::timeout stops waiting for the output, but the closure itself still runs to completion.
Ticks
Sometimes each process of your application maintains in-memory state, such as buffered view counts that you flush periodically instead of writing to the database on every request. A tick runs an async callback on a repeating interval inside each server process and each queue worker. Register ticks with with_ticks in src/app.rs:
1use laravel::prelude::*;23use crate::services::ViewCounts;45async fn flush_view_counts(counts: Inject<ViewCounts>) -> laravel::Result<()> {6 counts.flush().await7}89Application::configure()10 .with_ticks(|ticks, _| {11 ticks12 .every(10.seconds(), flush_view_counts)13 .name("flush-view-counts")14 .when(|host| host.is_server())15 .run_on_shutdown();16 })1use laravel::prelude::*;23use crate::services::ViewCounts;45async fn flush_view_counts(counts: Inject<ViewCounts>) -> laravel::Result<()> {6 counts.flush().await7}89Application::configure()10 .with_ticks(|ticks, _| {11 ticks12 .every(10.seconds(), flush_view_counts)13 .name("flush-view-counts")14 .when(|host| host.is_server())15 .run_on_shutdown();16 })
A tick callback is an async function or closure returning () or laravel::Result<()>, and may inject Inject<T> services and Section<T> config sections. Each tick runs in its own application context where resolve, config, and once work like they do in a request. Laravel reports any errors or panics from a tick and continues scheduling future ticks. A service provider can register ticks via app.ticks() inside register.
Each interval starts after the previous tick finishes, so ticks never overlap. You may configure a tick with the following methods:
| Method | Effect |
|---|---|
name("flush-view-counts") |
Names the tick for log output and testing. |
immediately() |
Runs the first tick as soon as the process starts instead of waiting one interval. |
jitter(2.seconds()) |
Randomizes each wait by up to the given duration so processes started together don't tick in lockstep. |
run_on_shutdown() |
Runs the tick one final time during shutdown after in-flight requests or jobs finish, flushing any remaining buffered state. |
when(|host| host.is_server()) |
Runs the tick only in the processes the closure accepts. |
Ticks run in the HTTP server (serve) and in every queue worker (queue:work). Other console commands, the scheduler, and tests do not run them automatically.
Choosing where ticks run
Some ticks only apply to a specific type of process. For example, if only HTTP requests increment your buffered view counts, queue workers have nothing to flush. Pass a closure to when to inspect the current Host and return true when the tick should run (Laravel evaluates the closure before each tick, so you may also check configuration values):
1use laravel::foundation::Host;2use laravel::prelude::*;34Application::configure()5 .with_ticks(|ticks, _| {6 ticks7 .every(10.seconds(), flush_view_counts)8 .when(|host| host.is_server());910 ticks11 .every(10.seconds(), flush_job_metrics)12 .when(|host| host.is_worker());1314 ticks15 .every(10.seconds(), flush_priority_metrics)16 .when(|host| match host {17 Host::Worker { queues, .. } => queues.iter().any(|queue| queue == "high"),18 _ => false,19 });20 })1use laravel::foundation::Host;2use laravel::prelude::*;34Application::configure()5 .with_ticks(|ticks, _| {6 ticks7 .every(10.seconds(), flush_view_counts)8 .when(|host| host.is_server());910 ticks11 .every(10.seconds(), flush_job_metrics)12 .when(|host| host.is_worker());1314 ticks15 .every(10.seconds(), flush_priority_metrics)16 .when(|host| match host {17 Host::Worker { queues, .. } => queues.iter().any(|queue| queue == "high"),18 _ => false,19 });20 })
Host::Server represents the HTTP server, while Host::Worker represents a queue worker and carries the connection and queue names it processes. To run ticks inside your own long-running console commands, add with_ticks to #[command] (such as #[command("feeds:watch", long_running, with_ticks)]), which sets the host to Host::Command containing the command's name.
You may also inspect the current process host anywhere in your application, such as inside a job or service, by calling foundation::host(). It returns None in one-off console commands and tests:
1use laravel::foundation;23if foundation::host().is_some_and(|host| host.is_worker()) {4 // Running in a queue worker...5}1use laravel::foundation;23if foundation::host().is_some_and(|host| host.is_worker()) {4 // Running in a queue worker...5}
Every server process and queue worker runs its matching ticks independently. For work that should run once across your entire fleet or at a specific time of day, use the scheduler instead.
Testing ticks
Tests do not run ticks on a timer. To execute a named tick inside a test, call app.tick (which invokes the tick directly without evaluating its when closure) and assert on its effects:
1use laravel::testing::prelude::*;23#[laravel::test]4async fn flushing_saves_view_counts(app: Application) -> laravel::Result<()> {5 app.tick("flush-view-counts").await?;67 // Assert on what the tick saved...89 Ok(())10}1use laravel::testing::prelude::*;23#[laravel::test]4async fn flushing_saves_view_counts(app: Application) -> laravel::Result<()> {5 app.tick("flush-view-counts").await?;67 // Assert on what the tick saved...89 Ok(())10}