Skip to content

Concurrency and Tasks

Digging Deeper

Concurrency and Tasks

Introduction

Requests often need several independent pieces of data, such as the number of users and the number of orders for a dashboard. If you load them concurrently, the response is only as slow as the slowest query, rather than the sum of them all. Other work, such as telling a webhook that an order shipped, doesn't need to hold up the response at all.

The task package runs work concurrently, gives work a time limit, and starts work in a goroutine whose result you collect later. Prefer it to a bare go statement. Each function you pass receives a context that carries the caller's application, logged-in user, and trace, so queries, the cache, the HTTP client, and logging work in it as they do in your handler. A panic in the function comes back to you as an error that responds with a 500, where a panic in a goroutine of your own ends the whole process.

Running work concurrently

To run several functions at once and wait for all of them, pass them to task.Run. Each function writes its own result, and Run returns once every function has returned, so the handler may read the results after it. For example, this dashboard handler counts users and orders concurrently:

1package dashboard
2 
3import (
4 "context"
5 
6 "go.laravel.com/db"
7 "go.laravel.com/task"
8 "go.laravel.com/web"
9)
10 
11func Show(r *web.Request) *web.Response {
12 var users, orders int
13 
14 err := task.Run(r,
15 func(ctx context.Context) (err error) {
16 users, err = db.Table("users").Count(ctx)
17 return err
18 },
19 func(ctx context.Context) (err error) {
20 orders, err = db.Table("orders").Count(ctx)
21 return err
22 },
23 )
24 if err != nil {
25 return web.Fail(err)
26 }
27 
28 return web.JSON(map[string]int{"users": users, "orders": orders})
29}
1package dashboard
2 
3import (
4 "context"
5 
6 "go.laravel.com/db"
7 "go.laravel.com/task"
8 "go.laravel.com/web"
9)
10 
11func Show(r *web.Request) *web.Response {
12 var users, orders int
13 
14 err := task.Run(r,
15 func(ctx context.Context) (err error) {
16 users, err = db.Table("users").Count(ctx)
17 return err
18 },
19 func(ctx context.Context) (err error) {
20 orders, err = db.Table("orders").Count(ctx)
21 return err
22 },
23 )
24 if err != nil {
25 return web.Fail(err)
26 }
27 
28 return web.JSON(map[string]int{"users": users, "orders": orders})
29}

Pass each function's ctx to its work, not r. When one function fails, Run returns that function's error, and the other functions' contexts end with it as the cause, so a query or HTTP request still in flight stops early rather than doing work nobody will read.

When you have two functions that each return a value, task.Both runs them concurrently and returns both values without declaring outer variables:

1users, orders, err := task.Both(r,
2 func(ctx context.Context) (int, error) { return db.Table("users").Count(ctx) },
3 func(ctx context.Context) (int, error) { return db.Table("orders").Count(ctx) },
4)
1users, orders, err := task.Both(r,
2 func(ctx context.Context) (int, error) { return db.Table("users").Count(ctx) },
3 func(ctx context.Context) (int, error) { return db.Table("orders").Count(ctx) },
4)

When the set of tasks is decided dynamically, such as in a loop or behind conditionals, create a group with task.NewGroup, start each function with g.Go, and wait for all of them with g.Wait:

1g := task.NewGroup(r)
2g.Go(func(ctx context.Context) error { return syncContacts(ctx) })
3if includeBilling {
4 g.Go(func(ctx context.Context) error { return syncInvoices(ctx) })
5}
6if err := g.Wait(); err != nil {
7 return web.Fail(err)
8}
1g := task.NewGroup(r)
2g.Go(func(ctx context.Context) error { return syncContacts(ctx) })
3if includeBilling {
4 g.Go(func(ctx context.Context) error { return syncInvoices(ctx) })
5}
6if err := g.Wait(); err != nil {
7 return web.Fail(err)
8}

Taking the first result

Sometimes two services can answer the same question, and you only need whichever answers first. To race several functions and continue as soon as one finishes, pass them to task.First, which returns the result of the first function to return. For example, this handler queries two exchange-rate providers and responds with whichever answers first:

1package rates
2 
3import (
4 "context"
5 
6 "go.laravel.com/httpclient"
7 "go.laravel.com/task"
8 "go.laravel.com/web"
9)
10 
11func Latest(r *web.Request) *web.Response {
12 res, err := task.First(r,
13 func(ctx context.Context) (*httpclient.Response, error) {
14 return httpclient.Get(ctx, "https://rates.example.com/latest")
15 },
16 func(ctx context.Context) (*httpclient.Response, error) {
17 return httpclient.Get(ctx, "https://backup-rates.example.com/latest")
18 },
19 )
20 if err != nil {
21 return web.Fail(err)
22 }
23 
24 return web.Text(res.Text())
25}
1package rates
2 
3import (
4 "context"
5 
6 "go.laravel.com/httpclient"
7 "go.laravel.com/task"
8 "go.laravel.com/web"
9)
10 
11func Latest(r *web.Request) *web.Response {
12 res, err := task.First(r,
13 func(ctx context.Context) (*httpclient.Response, error) {
14 return httpclient.Get(ctx, "https://rates.example.com/latest")
15 },
16 func(ctx context.Context) (*httpclient.Response, error) {
17 return httpclient.Get(ctx, "https://backup-rates.example.com/latest")
18 },
19 )
20 if err != nil {
21 return web.Fail(err)
22 }
23 
24 return web.Text(res.Text())
25}

The first function to return wins, even when it returns an error. Once one function wins, First ends the other functions' contexts and returns without waiting for them, so their requests are canceled and their results are dropped. Queries and HTTP requests stop when their context ends, but a function of your own should check its ctx too, so it doesn't keep running after it has lost.

Limiting how many run at once

Sometimes you have a list of things to fetch, such as the profile of each organization a user belongs to, and the API you call limits how many requests you may send at once. task.Map calls a function for each item, with at most the number of calls you give it running at the same time, and returns the results in the order of the items. For example, this handler fetches each organization's profile, five at a time:

1package organizations
2 
3import (
4 "context"
5 
6 "go.laravel.com/httpclient"
7 "go.laravel.com/task"
8 "go.laravel.com/web"
9)
10 
11func Index(r *web.Request) *web.Response {
12 orgs := []string{"laravel", "golang", "kubernetes"}
13 
14 responses, err := task.Map(
15 r,
16 orgs,
17 5,
18 func(ctx context.Context, org string) (*httpclient.Response, error) {
19 return httpclient.URLParameters("org", org).Get(ctx, "https://api.github.com/orgs/{org}")
20 },
21 )
22 if err != nil {
23 return web.Fail(err)
24 }
25 
26 profiles := make([]map[string]any, len(responses))
27 for i, res := range responses {
28 profile, err := res.JSON[map[string]any]()
29 if err != nil {
30 return web.Fail(err)
31 }
32 profiles[i] = profile
33 }
34 
35 return web.JSON(profiles)
36}
1package organizations
2 
3import (
4 "context"
5 
6 "go.laravel.com/httpclient"
7 "go.laravel.com/task"
8 "go.laravel.com/web"
9)
10 
11func Index(r *web.Request) *web.Response {
12 orgs := []string{"laravel", "golang", "kubernetes"}
13 
14 responses, err := task.Map(
15 r,
16 orgs,
17 5,
18 func(ctx context.Context, org string) (*httpclient.Response, error) {
19 return httpclient.URLParameters("org", org).Get(ctx, "https://api.github.com/orgs/{org}")
20 },
21 )
22 if err != nil {
23 return web.Fail(err)
24 }
25 
26 profiles := make([]map[string]any, len(responses))
27 for i, res := range responses {
28 profile, err := res.JSON[map[string]any]()
29 if err != nil {
30 return web.Fail(err)
31 }
32 profiles[i] = profile
33 }
34 
35 return web.JSON(profiles)
36}

responses[0] is the response for laravel, whichever request finished first. When one call fails, Map returns that call's error, starts no more calls, and ends the context of the calls still running, as task.Run does.

When the work produces no result slice, such as sending notifications to a list of recipients, use task.Each instead:

1err := task.Each(r, emails, 5, func(ctx context.Context, email string) error {
2 return mail.Send(ctx, email, welcome)
3})
1err := task.Each(r, emails, 5, func(ctx context.Context, email string) error {
2 return mail.Send(ctx, email, welcome)
3})

Time limits and pauses

An outgoing request waits as long as the remote service takes, which can tie up your handler if the service hangs. To enforce a deadline, pass a limit and a function to task.Timeout. The function's context ends at the limit, and Timeout returns the function's result, or a *task.TimeoutError when the limit passes first:

1package rates
2 
3import (
4 "context"
5 "time"
6 
7 "go.laravel.com/httpclient"
8 "go.laravel.com/task"
9 "go.laravel.com/web"
10)
11 
12func Latest(r *web.Request) *web.Response {
13 res, err := task.Timeout(r, 3*time.Second, func(ctx context.Context) (*httpclient.Response, error) {
14 return httpclient.Get(ctx, "https://rates.example.com/latest")
15 })
16 if err != nil {
17 return web.Fail(err)
18 }
19 
20 return web.Text(res.Text())
21}
1package rates
2 
3import (
4 "context"
5 "time"
6 
7 "go.laravel.com/httpclient"
8 "go.laravel.com/task"
9 "go.laravel.com/web"
10)
11 
12func Latest(r *web.Request) *web.Response {
13 res, err := task.Timeout(r, 3*time.Second, func(ctx context.Context) (*httpclient.Response, error) {
14 return httpclient.Get(ctx, "https://rates.example.com/latest")
15 })
16 if err != nil {
17 return web.Fail(err)
18 }
19 
20 return web.Text(res.Text())
21}

Timeout returns as soon as the limit passes, even if the function ignores its context, and a handler that fails with a *task.TimeoutError responds with a 504 Gateway Timeout. When the work has a fallback, check for the error with errors.AsType and use the fallback instead, such as the rates you last stored in the cache:

1func Latest(r *web.Request) *web.Response {
2 res, err := task.Timeout(r, 3*time.Second, func(ctx context.Context) (*httpclient.Response, error) {
3 return httpclient.Get(ctx, "https://rates.example.com/latest")
4 })
5 if _, ok := errors.AsType[*task.TimeoutError](err); ok {
6 rates, _, err := cache.Get[string](r, "rates")
7 if err != nil {
8 return web.Fail(err)
9 }
10 
11 return web.Text(rates)
12 }
13 if err != nil {
14 return web.Fail(err)
15 }
16 
17 return web.Text(res.Text())
18}
1func Latest(r *web.Request) *web.Response {
2 res, err := task.Timeout(r, 3*time.Second, func(ctx context.Context) (*httpclient.Response, error) {
3 return httpclient.Get(ctx, "https://rates.example.com/latest")
4 })
5 if _, ok := errors.AsType[*task.TimeoutError](err); ok {
6 rates, _, err := cache.Get[string](r, "rates")
7 if err != nil {
8 return web.Fail(err)
9 }
10 
11 return web.Text(rates)
12 }
13 if err != nil {
14 return web.Fail(err)
15 }
16 
17 return web.Text(res.Text())
18}

To pause, such as between calls to an API that limits how often you may call it, use task.Sleep. Unlike time.Sleep, it returns early with an error when its context ends, such as when the visitor leaves or the server shuts down, so a long pause doesn't keep work running that nobody needs:

1if err := task.Sleep(ctx, 500*time.Millisecond); err != nil {
2 return err
3}
1if err := task.Sleep(ctx, 500*time.Millisecond); err != nil {
2 return err
3}

Background work

When the user doesn't need to wait for some work to finish, start it with r.Background. The work starts right away in a goroutine of its own while your handler returns its response. For example, this handler marks an order as shipped and tells a webhook in the background:

1package orders
2 
3import (
4 "context"
5 
6 "go.laravel.com/httpclient"
7 "go.laravel.com/web"
8)
9 
10func Ship(r *web.Request) *web.Response {
11 id, err := r.PathInt("order")
12 if err != nil {
13 return web.Fail(err)
14 }
15 
16 // Mark the order as shipped...
17 
18 r.Background(func(ctx context.Context) error {
19 _, err := httpclient.JSON(map[string]int64{"order_id": id}).
20 EnsureSuccessful().
21 Post(ctx, "https://example.com/webhooks/shipped")
22 
23 return err
24 })
25 
26 return web.Back()
27}
1package orders
2 
3import (
4 "context"
5 
6 "go.laravel.com/httpclient"
7 "go.laravel.com/web"
8)
9 
10func Ship(r *web.Request) *web.Response {
11 id, err := r.PathInt("order")
12 if err != nil {
13 return web.Fail(err)
14 }
15 
16 // Mark the order as shipped...
17 
18 r.Background(func(ctx context.Context) error {
19 _, err := httpclient.JSON(map[string]int64{"order_id": id}).
20 EnsureSuccessful().
21 Post(ctx, "https://example.com/webhooks/shipped")
22 
23 return err
24 })
25 
26 return web.Back()
27}

The work's context carries the application, but not the request's cancellation or transaction, so the work carries on once the response has been sent. Read what the work needs from the request before you start it, such as the order's ID above, since the request's body and uploads are gone once the handler returns. Laravel reports the work's error or panic as it reports a handler's. Inside a transaction, the work starts once the transaction commits, so a webhook never hears about an order that was rolled back.

During a graceful shutdown, the server waits for background work in progress, up to SERVER_SHUTDOWN_TIMEOUT. Commands and jobs start background work by passing their ctx to laravel.Background, and a command waits for its background work before the process exits. To learn more, check out the console guide's section on background work.

Background work isn't a replacement for a queue. Nothing retries it when it fails, and a crash loses the work that hasn't finished. For work that must succeed, such as charging a card or sending a receipt, dispatch a queued job instead.

Starting a task

Sometimes you want to start some work, do something else in the meantime, and collect the work's result later in the same handler. task.Go starts a function in a goroutine of its own and returns a *task.Task at once, and the task's Wait method waits for the function and returns its result. A method value such as db.Table("orders").Count is already a function of a context, so you may pass it directly:

1package dashboard
2 
3import (
4 "go.laravel.com/db"
5 "go.laravel.com/task"
6 "go.laravel.com/web"
7)
8 
9func Show(r *web.Request) *web.Response {
10 orders := task.Go(r, db.Table("orders").Count)
11 
12 users, err := db.Table("users").Count(r)
13 if err != nil {
14 return web.Fail(err)
15 }
16 
17 orderCount, err := orders.Wait()
18 if err != nil {
19 return web.Fail(err)
20 }
21 
22 return web.JSON(map[string]int{"users": users, "orders": orderCount})
23}
1package dashboard
2 
3import (
4 "go.laravel.com/db"
5 "go.laravel.com/task"
6 "go.laravel.com/web"
7)
8 
9func Show(r *web.Request) *web.Response {
10 orders := task.Go(r, db.Table("orders").Count)
11 
12 users, err := db.Table("users").Count(r)
13 if err != nil {
14 return web.Fail(err)
15 }
16 
17 orderCount, err := orders.Wait()
18 if err != nil {
19 return web.Fail(err)
20 }
21 
22 return web.JSON(map[string]int{"users": users, "orders": orderCount})
23}

Wait returns the function's error, or a panic in it as an error. Laravel doesn't report a task's error on its own, so return it from your handler or report it yourself.

The function's context ends when the request does. If you never call Wait, the function still runs, but the server doesn't wait for it when it shuts down. For work that a graceful shutdown should wait for, use background work.

Tasks in a transaction

Inside a transaction, such as inside db.Transaction or in a test that uses RefreshDatabase, the functions you pass to the task package still run at the same time, and their queries run in the transaction. A transaction runs one query at a time, so the functions' queries take turns on its connection, while their other work, such as HTTP requests, runs at once. This means a handler that loads its data with task.Run works the same in your tests as it does in production. To run goroutines of your own inside a transaction, check out the database guide's section on concurrent work in a transaction.

Ticks

Sometimes each process of your application keeps state in memory, such as view counts that you buffer and flush every few seconds, rather than writing to the database on every request. A tick runs a function at an interval inside each running server process and each queue worker. List your ticks in Options.Ticks in bootstrap/app.go:

1func Options() laravel.Options {
2 return laravel.Options{
3 // ...
4 Ticks: []laravel.Tick{
5 {
6 Name: "flush-view-counts",
7 Every: 10 * time.Second,
8 When: func(host laravel.Host) bool { return host.IsServer() },
9 Run: flushViewCounts,
10 RunOnShutdown: true,
11 },
12 },
13 }
14}
15 
16func flushViewCounts(ctx context.Context) error {
17 return services.From(ctx).ViewCounts.Flush(ctx)
18}
1func Options() laravel.Options {
2 return laravel.Options{
3 // ...
4 Ticks: []laravel.Tick{
5 {
6 Name: "flush-view-counts",
7 Every: 10 * time.Second,
8 When: func(host laravel.Host) bool { return host.IsServer() },
9 Run: flushViewCounts,
10 RunOnShutdown: true,
11 },
12 },
13 }
14}
15 
16func flushViewCounts(ctx context.Context) error {
17 return services.From(ctx).ViewCounts.Flush(ctx)
18}

Here ViewCounts stands for a service of your own that buffers the counts in memory. A tick's Run function receives a context that carries the application, so your services, configuration, queries, and logging work in it as they do in a handler. Laravel reports a tick's error or panic, as it reports a handler's, and the next tick runs as usual. A package adds ticks with app.Ticks in its Register method.

The interval counts from when the previous tick finishes, so ticks never overlap. You may configure a tick with these fields:

Field Effect
Name Names the tick in its log lines and in tests. Every tick needs a name of its own.
Immediately Runs the first tick as soon as the process starts, rather than one interval later.
Jitter Waits up to this much longer or shorter than the interval, at random, so processes started together don't tick in lockstep. It must be shorter than Every.
RunOnShutdown Runs the tick one final time when the process stops, after the requests, jobs, and background work in progress finish, so what they buffered isn't lost.
When Runs the tick only in the hosts for which the function returns true.

Ticks run in serve, in every queue worker (queue:work), and in long-running console commands that implement WithTicks() bool. Other commands, the scheduler, and tests don't run them on their own.

Every matching process runs every tick independently. For work that should run once across all your servers, or at a time of day, use the scheduler instead.

Choosing where ticks run

Some ticks only apply to one kind of process. For example, if only HTTP requests increment your buffered view counts, queue workers have nothing to flush. Set When on a tick to inspect the current laravel.Host and return true when the tick should run (Laravel calls When before each tick, so you may also check configuration values):

1Ticks: []laravel.Tick{
2 {
3 Name: "flush-view-counts",
4 Every: 10 * time.Second,
5 When: func(host laravel.Host) bool { return host.IsServer() },
6 Run: flushViewCounts,
7 },
8 {
9 Name: "flush-job-metrics",
10 Every: 10 * time.Second,
11 When: func(host laravel.Host) bool { return host.IsWorker() },
12 Run: flushJobMetrics,
13 },
14 {
15 Name: "flush-priority-metrics",
16 Every: 10 * time.Second,
17 When: func(host laravel.Host) bool {
18 return host.IsWorker() && slices.Contains(host.Queues, "high")
19 },
20 Run: flushPriorityMetrics,
21 },
22}
1Ticks: []laravel.Tick{
2 {
3 Name: "flush-view-counts",
4 Every: 10 * time.Second,
5 When: func(host laravel.Host) bool { return host.IsServer() },
6 Run: flushViewCounts,
7 },
8 {
9 Name: "flush-job-metrics",
10 Every: 10 * time.Second,
11 When: func(host laravel.Host) bool { return host.IsWorker() },
12 Run: flushJobMetrics,
13 },
14 {
15 Name: "flush-priority-metrics",
16 Every: 10 * time.Second,
17 When: func(host laravel.Host) bool {
18 return host.IsWorker() && slices.Contains(host.Queues, "high")
19 },
20 Run: flushPriorityMetrics,
21 },
22}

host.IsServer() matches the HTTP server, host.IsWorker() matches queue:work (with host.Connection and host.Queues), and host.IsCommand() matches a long-running command that enables ticks (with host.Command).

You may also inspect the current host anywhere in your application, such as inside a job or service, by calling laravel.CurrentHost(ctx). It returns false in one-off console commands and tests:

1if host, ok := laravel.CurrentHost(ctx); ok && host.IsWorker() {
2 // Running in a queue worker...
3}
1if host, ok := laravel.CurrentHost(ctx); ok && host.IsWorker() {
2 // Running in a queue worker...
3}

Testing ticks

Tests don't run ticks on a timer. To run a tick in a test, call the client's Tick method with the tick's name, then assert on what the tick did. With RefreshDatabase, the tick's queries run in the client's transaction:

1func TestFlushingSavesViewCounts(t *testing.T) {
2 client := tests.New(t)
3 
4 if err := client.Tick("flush-view-counts"); err != nil {
5 t.Fatal(err)
6 }
7 
8 // Assert on what the tick saved...
9}
1func TestFlushingSavesViewCounts(t *testing.T) {
2 client := tests.New(t)
3 
4 if err := client.Tick("flush-view-counts"); err != nil {
5 t.Fatal(err)
6 }
7 
8 // Assert on what the tick saved...
9}