Course › Week 6 · Laravel Go › Day 4 · lesson 39 of 42 · 25 min reading + 60 min practice
Queues and tasks
Jobs as structs with a Handle method, retries, and several queries at once with the task package.
Week 4 built a Go worker that a Laravel queue fed (the worker lesson), and Week 5 ran work in the background of a service and had to make it survive a restart (the service lesson). Laravel Go has a queue of its own, with the same shape as Laravel’s: jobs stored in the jobs table, a worker command, retries, and failed jobs.
Today a job that asks the PHP Laravel app to send a guest a reminder, the ways it can fail, and the task package for work that must finish inside the request.
A queued job
1. A job is a struct with Handle
A job is a struct with a Handle(ctx) error method. Its exported fields are stored as JSON in the jobs table until a worker runs it, so a job carries data, never a connection or a client:
package jobs
import (
"context"
"fmt"
"go.laravel.com/httpclient"
"app/models"
"app/services"
)
// SendReminder asks the Laravel app to remind a guest of their booking.
type SendReminder struct {
Booking models.Booking `queue:"model"`
Channel string
}
func (j SendReminder) Handle(ctx context.Context) error {
url := fmt.Sprintf("%s/api/bookings/%d/reminders", services.From(ctx).LaravelURL, j.Booking.ID)
res, err := httpclient.JSON(map[string]string{"channel": j.Channel}).Post(ctx, url)
if err != nil {
return err
}
if res.Failed() {
return fmt.Errorf("reminder for booking %d: Laravel answered %d: %s", j.Booking.ID, res.Status, res.Text())
}
return nil
}
queue:"model" stores only the booking’s ID; before Handle runs, the worker loads the row again, so the job works with fresh data, like Laravel’s SerializesModels. If the row is gone by then, the worker deletes the job without running it.
httpclient is Laravel’s Http facade: JSON(body).Post(ctx, url) sends the request and reads the whole response. As with net/http (the HTTP client lesson), a 4xx or 5xx is a response, not an error, so res.Failed() is checked by hand. Returning an error fails the attempt.
laravel make:job SendReminder writes the file and adds SendReminder{} to jobs.All in jobs/jobs.go; a job missing from that list cannot be dispatched.
2. Where the job finds the Laravel app
The job reaches the URL through the services, from its ctx, the same way a handler does:
package services
import (
"context"
laravel "go.laravel.com"
"go.laravel.com/config"
)
type Services struct {
// LaravelURL is the base URL of the PHP Laravel app that sends guests their reminders.
LaravelURL string
}
func New(env *config.Env, app *laravel.App) Services {
return Services{
LaravelURL: env.String("LARAVEL_URL", "http://127.0.0.1:8000"),
}
}
func From(ctx context.Context) *Services {
return laravel.ServicesOf[*Services](ctx)
}
A job’s fields hold data; what lives as long as the app (a URL, a client, a key) comes from services.From(ctx). The fallback is the stand-in PHP API on port 8000.
3. Dispatching, and the worker
A handler validates, dispatches, and answers 202 with the job’s ID. A worker in another process runs the job, here ./app queue:work next to the server:
package reminders
import (
"net/http"
"go.laravel.com/model"
"go.laravel.com/queue"
"go.laravel.com/validation"
"go.laravel.com/validation/rule"
"go.laravel.com/web"
"app/jobs"
"app/models"
)
type StoreReminder struct {
Channel string `json:"channel"`
}
func (f *StoreReminder) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.Channel, rule.Required, rule.Max(20)),
)
}
func Store(r *web.Request) *web.Response {
booking, err := model.FromRoute[models.Booking](r, "booking")
if err != nil {
return web.Fail(err)
}
form, err := r.Validate[StoreReminder]()
if err != nil {
return web.Fail(err)
}
id, err := queue.Dispatch(r, jobs.SendReminder{Booking: booking, Channel: form.Channel})
if err != nil {
return web.Fail(err)
}
return web.JSON(map[string]queue.JobID{"job": id}).WithStatus(http.StatusAccepted)
}
HTTP/1.1 202 Accepted
Content-Length: 46
Content-Type: application/json
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: 8bc297d44e0dd87694cfe360009235a0
{"job":"01a23d63-177a-7c5c-b803-5e9c79dcb6a4"}4 s later:
Server running at `http://127.0.0.1:8080`. Press Ctrl+C to stop.
POST 202 /api/bookings/2/reminders 10.0ms
Stopping. Waiting up to 20s for the work in progress.Processing jobs from `database:default`. Press Ctrl+C to stop.
jobs.SendReminder 9.9msqueue.Dispatch(r, job) inserts the job into the jobs table (QUEUE_CONNECTION=database in .env) and returns its ID, a UUID. The request is done in milliseconds; the call to Laravel happens in the worker, which logged the job’s name and how long it took.
laravel dev starts the server, a worker and Vite together. In production the worker is its own process, kept running by your process manager, as php artisan queue:work is.
When a job fails
4. Retries with backoff
By default a job that returns an error is tried once. A JobOptions method changes that, like a PHP job’s $tries, $backoff and $timeout:
package jobs
import (
"context"
"fmt"
"time"
"go.laravel.com/httpclient"
"go.laravel.com/queue"
"app/models"
"app/services"
)
// SendReminder asks the Laravel app to remind a guest of their booking.
type SendReminder struct {
Booking models.Booking `queue:"model"`
Channel string
}
func (SendReminder) JobOptions() queue.Options {
return queue.Options{
Tries: 3,
Backoff: []time.Duration{time.Second, 2 * time.Second},
Timeout: 30 * time.Second,
}
}
func (j SendReminder) Handle(ctx context.Context) error {
url := fmt.Sprintf("%s/api/bookings/%d/reminders", services.From(ctx).LaravelURL, j.Booking.ID)
res, err := httpclient.JSON(map[string]string{"channel": j.Channel}).Post(ctx, url)
if err != nil {
return err
}
if res.Failed() {
return fmt.Errorf("reminder for booking %d: Laravel answered %d: %s", j.Booking.ID, res.Status, res.Text())
}
return nil
}
HTTP/1.1 202 Accepted
Content-Length: 46
Content-Type: application/json
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: 47df93e85ad2abe320b78b493583f174
{"job":"01a23d63-54dc-72c4-babd-029d234fd73e"}10 s later:
Server running at `http://127.0.0.1:8080`. Press Ctrl+C to stop.
POST 202 /api/bookings/2/reminders 10.2ms
Stopping. Waiting up to 20s for the work in progress.Processing jobs from `database:default`. Press Ctrl+C to stop.
time=2026-12-03T21:30:51.699+02:00 level=WARN msg="the job failed and will be retried: httpclient: the request to http://127.0.0.1:8001/api/bookings/2/reminders failed: dial tcp 127.0.0.1:8001: connect: connection refused" attempt=1 retry_in=1s job=app/jobs.SendReminder job_id=01a23d63-54dc-72c4-babd-029d234fd73e
jobs.SendReminder retrying 2.4ms
httpclient: the request to http://127.0.0.1:8001/api/bookings/2/reminders failed: dial tcp 127.0.0.1:8001: connect: connection refused
time=2026-12-03T21:30:54.724+02:00 level=WARN msg="the job failed and will be retried: httpclient: the request to http://127.0.0.1:8001/api/bookings/2/reminders failed: dial tcp 127.0.0.1:8001: connect: connection refused" attempt=2 retry_in=2s job=app/jobs.SendReminder job_id=01a23d63-54dc-72c4-babd-029d234fd73e
jobs.SendReminder retrying 1.6ms
httpclient: the request to http://127.0.0.1:8001/api/bookings/2/reminders failed: dial tcp 127.0.0.1:8001: connect: connection refused
time=2026-12-03T21:30:57.750+02:00 level=ERROR msg="httpclient: the request to http://127.0.0.1:8001/api/bookings/2/reminders failed: dial tcp 127.0.0.1:8001: connect: connection refused" attempt=3 location=/tmp/go-playbook/app/jobs/send_reminder.go:29 type=*httpclient.ConnectionError job=app/jobs.SendReminder job_id=01a23d63-54dc-72c4-babd-029d234fd73e
jobs.SendReminder failed 3.6ms
httpclient: the request to http://127.0.0.1:8001/api/bookings/2/reminders failed: dial tcp 127.0.0.1:8001: connect: connection refusedID Queue Job Failed at
01a23d63-54dc-72c4-babd-029d234fd73e database:default jobs.SendReminder 2026-12-03 21:30:57Here LARAVEL_URL points at a port where nothing listens, so every attempt is a connection error. The worker logs each failed attempt as a warning with retry_in: 1 s after the first, 2 s after the second. After the third it is a failed job, and queue:failed lists it.
Timeout ends the attempt’s ctx after 30 s. Go cannot stop a goroutine from outside, so the timeout works only because the HTTP call takes ctx: pass it to everything the job waits on.
5. A failure that retrying cannot fix
The PHP app answers 422 for a channel it does not know. Sending the same request again gets the same 422, so retrying only delays the failure. queue.Fail(err) fails the job permanently, at once:
package jobs
import (
"context"
"fmt"
"time"
"go.laravel.com/httpclient"
"go.laravel.com/queue"
"app/models"
"app/services"
)
// SendReminder asks the Laravel app to remind a guest of their booking.
type SendReminder struct {
Booking models.Booking `queue:"model"`
Channel string
}
func (SendReminder) JobOptions() queue.Options {
return queue.Options{
Tries: 3,
Backoff: []time.Duration{time.Second, 2 * time.Second},
Timeout: 30 * time.Second,
}
}
func (j SendReminder) Handle(ctx context.Context) error {
url := fmt.Sprintf("%s/api/bookings/%d/reminders", services.From(ctx).LaravelURL, j.Booking.ID)
res, err := httpclient.JSON(map[string]string{"channel": j.Channel}).Post(ctx, url)
if err != nil {
return err
}
switch {
case res.ClientError():
// The same request will be refused again: retrying cannot help.
return queue.Fail(fmt.Errorf("reminder for booking %d refused with %d: %s", j.Booking.ID, res.Status, res.Text()))
case res.Failed():
return fmt.Errorf("reminder for booking %d: Laravel answered %d", j.Booking.ID, res.Status)
}
return nil
}
HTTP/1.1 202 Accepted
Content-Length: 46
Content-Type: application/json
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: c342e7c06044a3f9fd282f1ce65af63b
{"job":"01a23d63-9955-7701-a5b4-ff84b3870a04"}4 s later:
Server running at `http://127.0.0.1:8080`. Press Ctrl+C to stop.
POST 202 /api/bookings/3/reminders 9.2ms
Stopping. Waiting up to 20s for the work in progress.Processing jobs from `database:default`. Press Ctrl+C to stop.
time=2026-12-03T21:31:09.240+02:00 level=ERROR msg="reminder for booking 3 refused with 422: {\"message\":\"The selected channel is invalid.\",\"errors\":{\"channel\":[\"The selected channel is invalid.\"]}}" attempt=1 location=/tmp/go-playbook/app/jobs/send_reminder.go:29 type=*errors.errorString job=app/jobs.SendReminder job_id=01a23d63-9955-7701-a5b4-ff84b3870a04
jobs.SendReminder failed 8.4ms
reminder for booking 3 refused with 422: {"message":"The selected channel is invalid.","errors":{"channel":["The selected channel is invalid."]}}ID Queue Job Failed at
01a23d63-9955-7701-a5b4-ff84b3870a04 database:default jobs.SendReminder 2026-12-03 21:31:09One attempt, logged as an error with the body Laravel sent, then the failed-jobs table. The split is the rule of the HTTP client lesson: retry what can succeed later (no connection, 5xx, 429), fail at once what cannot (the other 4xx).
queue:retry <id> puts a failed job back on the queue once the cause is fixed, queue:forget <id> deletes it, and queue:flush deletes them all: the same commands as artisan.
Tasks
6. Several queries at once: task.Run
Not all work belongs on a queue. A response that needs three counts can run them at the same time. task.Run runs its functions concurrently and returns when all have, like errgroup (the errgroup lesson):
package stats
import (
"context"
"go.laravel.com/model"
"go.laravel.com/task"
"go.laravel.com/web"
"app/models"
)
type Stats struct {
Pending int `json:"pending"`
Confirmed int `json:"confirmed"`
Properties int `json:"properties"`
}
func Show(r *web.Request) *web.Response {
var stats Stats
err := task.Run(r,
func(ctx context.Context) (err error) {
stats.Pending, err = model.Query[models.Booking]().WhereEq("status", models.Pending).Count(ctx)
return err
},
func(ctx context.Context) (err error) {
stats.Confirmed, err = model.Query[models.Booking]().WhereEq("status", models.Confirmed).Count(ctx)
return err
},
func(ctx context.Context) (err error) {
stats.Properties, err = model.Query[models.Property]().Count(ctx)
return err
},
)
if err != nil {
return web.Fail(err)
}
return web.JSON(stats)
}
HTTP/1.1 200 OK
Content-Length: 42
Content-Type: application/json
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: 81d41dc3fd047064efb499f10bfcfce5
{"pending":2,"confirmed":1,"properties":2}Server running at `http://127.0.0.1:8080`. Press Ctrl+C to stop.
time=2026-12-03T21:31:22.760+02:00 level=DEBUG msg=query sql="select count(*) from \"properties\"" duration_ms=12.851 dialect=postgres request_id=81d41dc3fd047064efb499f10bfcfce5
time=2026-12-03T21:31:22.760+02:00 level=DEBUG msg=query sql="select count(*) from \"bookings\" where \"bookings\".\"status\" = $1" duration_ms=13.183 dialect=postgres request_id=81d41dc3fd047064efb499f10bfcfce5
time=2026-12-03T21:31:22.760+02:00 level=DEBUG msg=query sql="select count(*) from \"bookings\" where \"bookings\".\"status\" = $1" duration_ms=13.297 dialect=postgres request_id=81d41dc3fd047064efb499f10bfcfce5
GET 200 /api/stats 13.8ms
Stopping. Waiting up to 20s for the work in progress.
time=2026-12-03T21:31:22.763+02:00 level=DEBUG msg="command finished" exit_code=0 duration_ms=215.591Each function writes only its own field, so they never touch the same variable. The log shows the three queries and their times, and the request’s total, which is close to the slowest query, not to the sum of the three.
Pass each function’s ctx, not r: when one fails, Run returns its error and ends the others’ contexts, so their queries stop. A panic in a function comes back as an error, a 500, where a panic in a bare go goroutine ends the whole server.
7. Which one to use
| Work | Use | Survives a crash or deploy? |
|---|---|---|
| Part of this response, several at once | task.Run, task.Both, task.Map | no need: the response waits for it |
| After the response, nice to have (a cleanup, a ping) | r.Background(func(ctx) error) | no: nothing retries it |
| Must happen (a reminder, a charge, an email) | queue.Dispatch | yes: it is a row in jobs |
| A long process with waits and steps | a workflow (the workflows lesson) | yes: each step is stored |
A bare go statement is on none of these lines. Its goroutine gets no application in its context unless you pass one, its panic kills the process, and the server’s shutdown does not wait for it: the problems the service lesson solved by hand.
Coming from PHP
<?php
namespace App\Jobs;
use App\Models\Booking;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Http;
class SendReminder implements ShouldQueue
{
use Queueable;
public int $tries = 3;
public array $backoff = [1, 2];
public function __construct(public Booking $booking, public string $channel) {}
public function handle(): void
{
$response = Http::post(config('services.laravel.url')."/api/bookings/{$this->booking->id}/reminders", [
'channel' => $this->channel,
]);
if ($response->clientError()) {
$this->fail("Reminder refused with {$response->status()}");
return;
}
$response->throw();
}
}
Almost line for line. The differences: PHP serializes the job with serialize(), Go stores its exported fields as JSON, and finds the job’s type by its name, app/jobs.SendReminder: rename or move the type and the jobs already in the table have nothing to run them, unless a JobName() method keeps the name stable. And there is no container: handle() in PHP can ask for services by type-hinting them, the Go job reads them from ctx.
The worker is different underneath. php artisan queue:work runs one job at a time per process; a Go worker is one process that can run many jobs at once, each on its own goroutine, with queue:work --concurrency=8.
PracticeThe queues and tasks guides; a reminder the next day
Read “Creating jobs”, “Dispatching jobs”, “Retries and timeouts” and “Running the worker” in queues.md, and tasks.md, in the app’s bundled docs.
Exercise: remind the day before
Change reminders.Store so the job runs at 18:00 UTC on the day before the check-in: find queue.DelayUntil in the docs. A check-in that is already past is a 422. Start a worker, dispatch for a booking with a check-in tomorrow, and read the available_at column of the job’s row in jobs with psql to see when it will run.
Remember
- A job carries data; services come from
services.From(ctx), models throughqueue:"model". - A job runs once unless
JobOptionssaysTries; fail at once withqueue.Failwhat a retry cannot fix. - Inside a response use
task.Run; for work that must happen, a queued job, never a barego.
Tomorrow: workflows, a long process written as one function that survives restarts.