Go Playbook

Course › Week 4 · Concurrency and plugging into Laravel › Day 6 · lesson 27 of 42 · 1 h 5 min reading + 2–3 h practice

Build the Laravel worker

An artisan command queues a batch, the Go worker processes it concurrently and writes results in one transaction.

goroutinesdatabase/sqlProcess facade

On this page
  1. The task
  2. The design
  3. The tables, as Laravel creates them
  4. Step 1: the job, the output and the config
  5. Step 2: the database
  6. Step 3: the analysis API client
  7. Step 4: the run
  8. Step 5: main
  9. Run it: the four outcomes
  10. And when the setup is wrong
  11. The Laravel side
  12. Deploy
  13. What changed, and what did not
  14. Practice
  15. Remember

This week’s tool is Go doing one heavy job inside a Laravel system, with Laravel still in charge of the queue, the retries and the users. It joins every lesson of the week, goroutines, context, the HTTP client, Postgres and errgroup, into one binary of about 450 lines.

The Go side was built and run here for real, against Postgres 16 and the Laravel-style API on 127.0.0.1:8000. The PHP side is syntax-checked with php -l but not executed on this machine.

#dataThursday 10:15

Sara · dataThe nightly analysis job takes 3 hours now. For each evaluation it loads the answers, sends the comments to the analysis API, and saves the counts, one evaluation at a time, because each call waits about 100 ms and PHP waits with it.

Omar · backendKeep the queue, the retries and the dashboard in Laravel. Give me a binary that takes a batch of ids, does the waiting in parallel, and either saves the whole batch or nothing. And it must tell the job apart: “API down, try later” is not the same as “these 3 evaluations have no answers”.

The design

One job, start to finish:

StepWhereLesson
Pick pending evaluations, split into batches of 200, queue one job eachLaravel: artisan command
Run the binary, send {"evaluation_ids": […]} on stdinLaravel: queued job, Process
Check the config, load every answer of the batch in two queriesGoPostgres
Call the analysis API for each evaluation, 8 at a time, with retriesGocontext and HTTP, errgroup
Save every result in one transactionGoPostgres
Print the result as JSON; exit 0, 1, 2 or 3GoJSON
Retry the job, or requeue only the retryable ids, or fail itLaravel: queued job

Two queries for the whole batch, not two per evaluation: where evaluation_id = any($1) with the slice of ids bound as one Postgres array. The 3-hour job was mostly waiting; this one waits for 8 calls at a time.

worker/
worker/
├── go.mod            (module github.com/you/worker)
├── main.go           (logs, stdin → run → stdout, exit codes)
├── config.go         (DATABASE_URL, ANALYSIS_URL, WORKER_CONCURRENCY)
├── job.go            (Job in, Output out)
├── db.go             (load answers, save results in one transaction)
├── analysis.go       (the analysis API client, with retries)
├── process.go        (group, analyse concurrently, decide, save)
└── process_test.go

The tables, as Laravel creates them

database/migrations/2026_11_02_000000_create_evaluations_tables.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('evaluations', function (Blueprint $table) {
            $table->id();
            $table->string('school');
            $table->string('status', 20)->default('pending');   // pending → analysed
            $table->integer('average_tenths')->nullable();
            $table->integer('positive')->nullable();
            $table->integer('negative')->nullable();
            $table->integer('neutral')->nullable();
            $table->timestamp('analysed_at')->nullable();
            $table->timestamps();
        });

        Schema::create('answers', function (Blueprint $table) {
            $table->id();
            $table->foreignId('evaluation_id')->constrained();
            $table->string('question', 20);
            $table->smallInteger('score');
            $table->text('comment')->nullable();
        });
    }
};

The sample data: five evaluations. 1042, 1043 and 1045 have answers with comments, one of them in Arabic; 1044 has no answers; 1046 has one answer without a comment.

Step 1: the job, the output and the config

The contract with Laravel, as types. Ids are int64 because they are Postgres bigints. Each Failed entry says whether it is Retryable, so Laravel can send those evaluations again without resending the rest. v2 writes an empty Failed slice as [], never null, so the PHP side never needs ?? [].

worker/job.gonew file
package main

// Job is what Laravel sends on stdin.
type Job struct {
	EvaluationIDs []int64 `json:"evaluation_ids"`
}

// Output is what Laravel reads from stdout: one JSON document.
type Output struct {
	Analysed []Analysed `json:"analysed"`
	Failed   []Failed   `json:"failed"`
}

// Analysed is one evaluation's result, as saved.
type Analysed struct {
	ID            int64 `json:"id"`
	AverageTenths int   `json:"average_tenths"`
	Positive      int   `json:"positive"`
	Negative      int   `json:"negative"`
	Neutral       int   `json:"neutral"`
}

// Failed is an evaluation that was not analysed, and why.
type Failed struct {
	ID     int64  `json:"id"`
	Reason string `json:"reason"`
	// Retryable is true when sending this evaluation again later may work (the analysis API was down).
	Retryable bool `json:"retryable"`
}

Config from the environment, checked once before any work. os.LookupEnv tells “not set” (use the default) from “set to something” (validate it). ANALYSIS_URL is required: there is no sensible default for a production API. if c.DatabaseURL, err = required(…); err != nil assigns two existing variables in the if’s short statement.

worker/config.gonew file
package main

import (
	"fmt"
	"os"
	"strconv"
	"strings"
)

// Config is everything the worker needs from its environment, checked once at startup. Laravel
// passes its own environment to the process, so these can live in Laravel's .env.
type Config struct {
	DatabaseURL string
	AnalysisURL string
	Concurrency int
}

func configFromEnv() (Config, error) {
	var c Config
	var err error
	if c.DatabaseURL, err = required("DATABASE_URL"); err != nil {
		return Config{}, err
	}
	if c.AnalysisURL, err = required("ANALYSIS_URL"); err != nil {
		return Config{}, err
	}
	c.Concurrency = 8
	if value, ok := os.LookupEnv("WORKER_CONCURRENCY"); ok {
		n, err := strconv.Atoi(strings.TrimSpace(value))
		if err != nil || n < 1 || n > 64 {
			return Config{}, fmt.Errorf("WORKER_CONCURRENCY must be a whole number from 1 to 64, got %q", value)
		}
		c.Concurrency = n
	}
	return c, nil
}

func required(name string) (string, error) {
	value := strings.TrimSpace(os.Getenv(name))
	if value == "" {
		return "", fmt.Errorf("%s is not set", name)
	}
	return value, nil
}

Step 2: the database

load runs two queries for the whole batch. = any($1) with a []int64 argument is how Postgres takes a list: pgx sends the slice as one array parameter, so 200 ids are still one query and still safe from injection.

save is the transaction from the Postgres lesson: one update per result, Commit at the end. If any update fails, the function returns before the commit, and the deferred Rollback undoes every earlier update in the batch.

worker/db.gonew file
package main

import (
	"context"
	"database/sql"
	"fmt"
)

// Answer is one answer, as Laravel stored it.
type Answer struct {
	EvaluationID int64
	Score        int
	Comment      *string
}

// load returns the ids among ids that exist, and all their answers, in two queries.
func load(ctx context.Context, db *sql.DB, ids []int64) (map[int64]bool, []Answer, error) {
	rows, err := db.QueryContext(ctx, "select id from evaluations where id = any($1)", ids)
	if err != nil {
		return nil, nil, fmt.Errorf("loading evaluations: %w", err)
	}
	defer rows.Close()
	known := map[int64]bool{}
	for rows.Next() {
		var id int64
		if err := rows.Scan(&id); err != nil {
			return nil, nil, fmt.Errorf("loading evaluations: %w", err)
		}
		known[id] = true
	}
	if err := rows.Err(); err != nil {
		return nil, nil, fmt.Errorf("loading evaluations: %w", err)
	}

	answerRows, err := db.QueryContext(ctx,
		"select evaluation_id, score, comment from answers where evaluation_id = any($1) order by evaluation_id, id", ids)
	if err != nil {
		return nil, nil, fmt.Errorf("loading answers: %w", err)
	}
	defer answerRows.Close()
	var answers []Answer
	for answerRows.Next() {
		var a Answer
		if err := answerRows.Scan(&a.EvaluationID, &a.Score, &a.Comment); err != nil {
			return nil, nil, fmt.Errorf("loading answers: %w", err)
		}
		answers = append(answers, a)
	}
	if err := answerRows.Err(); err != nil {
		return nil, nil, fmt.Errorf("loading answers: %w", err)
	}
	return known, answers, nil
}

// save writes every result in one transaction: all of them, or none.
func save(ctx context.Context, db *sql.DB, results []Analysed) error {
	tx, err := db.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	defer tx.Rollback()

	for _, r := range results {
		_, err := tx.ExecContext(ctx,
			"update evaluations set status = 'analysed', average_tenths = $2, positive = $3, negative = $4, neutral = $5, analysed_at = now(), updated_at = now() where id = $1",
			r.ID, r.AverageTenths, r.Positive, r.Negative, r.Neutral)
		if err != nil {
			return fmt.Errorf("saving evaluation %d: %w", r.ID, err)
		}
	}
	return tx.Commit()
}

Comment is a *string because the column is nullable. updated_at is set by hand, because Eloquent is not here to do it.

Step 3: the analysis API client

The retry loop from the context lesson, split in two: try makes one call and says whether its failure is worth retrying; Analyse decides how many times. A failure is a *Failure (a reason and a Retryable flag) instead of an error, because it is a result to report, not a reason to stop the batch.

Retryable means “the API was unreachable or overloaded after three attempts”. net.Error is the interface behind timeouts and refused connections, found with errors.As. A 404 or a body that does not decode will not get better by asking again.

worker/analysis.gonew file
package main

import (
	"bytes"
	"context"
	"encoding/json/v2"
	"errors"
	"fmt"
	"log/slog"
	"net"
	"net/http"
	"time"
)

// Sentiment is what the analysis API returns for one evaluation's comments.
type Sentiment struct {
	Positive int `json:"positive"`
	Negative int `json:"negative"`
	Neutral  int `json:"neutral"`
}

// Failure is why one evaluation could not be analysed, and whether asking again later may work.
type Failure struct {
	Reason    string
	Retryable bool
}

// Analyser calls the analysis API. One Analyser is shared by every goroutine.
type Analyser struct {
	client *http.Client
	url    string
	logger *slog.Logger
}

func newAnalyser(url string, logger *slog.Logger) *Analyser {
	return &Analyser{client: &http.Client{Timeout: 10 * time.Second}, url: url, logger: logger}
}

// Analyse makes up to three attempts. Only timeouts, connection failures, 429 and 5xx are retried.
func (a *Analyser) Analyse(ctx context.Context, evaluationID int64, comments []string) (Sentiment, *Failure) {
	payload, err := json.Marshal(map[string]any{"evaluation_id": evaluationID, "comments": comments})
	if err != nil {
		return Sentiment{}, &Failure{Reason: fmt.Sprintf("encoding the request: %v", err)}
	}

	wait := 200 * time.Millisecond
	for attempt := 1; ; attempt++ {
		sentiment, reason, retry := a.try(ctx, payload)
		if reason == "" {
			return sentiment, nil
		}
		if !retry {
			return Sentiment{}, &Failure{Reason: reason}
		}
		if attempt == 3 {
			return Sentiment{}, &Failure{Reason: reason, Retryable: true}
		}
		a.logger.Warn("retrying", "evaluation_id", evaluationID, "attempt", attempt, "reason", reason)
		select {
		case <-time.After(wait):
			wait *= 2
		case <-ctx.Done():
			return Sentiment{}, &Failure{Reason: reason, Retryable: true}
		}
	}
}

// try makes one call. It returns the sentiment, or a reason and whether the reason is worth a retry.
func (a *Analyser) try(ctx context.Context, payload []byte) (Sentiment, string, bool) {
	req, err := http.NewRequestWithContext(ctx, http.MethodPost, a.url, bytes.NewReader(payload))
	if err != nil {
		return Sentiment{}, fmt.Sprintf("building the request: %v", err), false
	}
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("User-Agent", "evaluation-worker/0.1")

	resp, err := a.client.Do(req)
	var netErr net.Error
	switch {
	case errors.As(err, &netErr):
		return Sentiment{}, fmt.Sprintf("analysis API unreachable: %v", err), true
	case err != nil:
		return Sentiment{}, fmt.Sprintf("analysis request failed: %v", err), false
	}
	defer resp.Body.Close()

	if resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= 500 {
		return Sentiment{}, fmt.Sprintf("analysis API answered %s", resp.Status), true
	}
	if resp.StatusCode != http.StatusOK {
		return Sentiment{}, fmt.Sprintf("analysis API answered %s", resp.Status), false
	}
	var s Sentiment
	if err := json.UnmarshalRead(resp.Body, &s); err != nil {
		return Sentiment{}, fmt.Sprintf("analysis API sent an unexpected body: %v", err), false
	}
	return s, "", false
}

One *Analyser with one *http.Client is shared by every goroutine; the client keeps a pool of connections to the API. The warning carries the evaluation id and the attempt, so the Laravel log shows which evaluation the API struggled with.

Step 4: the run

group is plain code, tested without a database: it puts each answer under its evaluation and moves the ids that cannot be analysed (“no such evaluation”, “no answers”) into the failed list. slices.Compact removes repeated neighbours, so after Sort the ids are unique.

The concurrent part is the errgroup lesson: SetLimit(concurrency) keeps 8 calls in flight, and each goroutine writes its own slot of results or failures. No task returns an error, because one evaluation’s failure must not stop the others.

worker/process.gonew file
package main

import (
	"cmp"
	"context"
	"database/sql"
	"errors"
	"fmt"
	"log/slog"
	"slices"

	"golang.org/x/sync/errgroup"
)

// errBadJob marks a job Laravel should never retry: exit code 2.
var errBadJob = errors.New("the job is not valid")

// errAnalysisUnavailable means nothing could be analysed because the API was down: retry later.
var errAnalysisUnavailable = errors.New("the analysis API is unavailable, nothing was written")

// evaluation is one evaluation to analyse, with its answers.
type evaluation struct {
	id      int64
	answers []Answer
}

// process runs one job: load, analyse concurrently, save everything in one transaction.
func process(ctx context.Context, db *sql.DB, analyser *Analyser, concurrency int, job Job, logger *slog.Logger) (Output, error) {
	ids := slices.Clone(job.EvaluationIDs)
	slices.Sort(ids)
	ids = slices.Compact(ids)

	known, answers, err := load(ctx, db, ids)
	if err != nil {
		return Output{}, err
	}
	todo, failed := group(ids, known, answers)
	logger.Info("loaded", "evaluations", len(todo), "skipped", len(failed))

	// One slot per evaluation: each goroutine writes only its own.
	results := make([]Analysed, len(todo))
	failures := make([]*Failure, len(todo))
	g, gctx := errgroup.WithContext(ctx)
	g.SetLimit(concurrency)
	for i, e := range todo {
		g.Go(func() error {
			var comments []string
			for _, a := range e.answers {
				if a.Comment != nil {
					comments = append(comments, *a.Comment)
				}
			}
			s, failure := analyser.Analyse(gctx, e.id, comments)
			if failure != nil {
				failures[i] = failure
				return nil
			}
			results[i] = Analysed{ID: e.id, AverageTenths: averageTenths(e.answers), Positive: s.Positive, Negative: s.Negative, Neutral: s.Neutral}
			return nil
		})
	}
	if err := g.Wait(); err != nil {
		return Output{}, err
	}

	var analysed []Analysed
	for i, e := range todo {
		if failures[i] != nil {
			failed = append(failed, Failed{ID: e.id, Reason: failures[i].Reason, Retryable: failures[i].Retryable})
			continue
		}
		analysed = append(analysed, results[i])
	}
	slices.SortFunc(failed, func(a, b Failed) int { return cmp.Compare(a.ID, b.ID) })

	// Nothing analysed and every failure temporary: the API is down. That is not "partly done", it
	// is a failed run that Laravel should retry as a whole, later.
	if len(analysed) == 0 && len(failed) > 0 && !slices.ContainsFunc(failed, func(f Failed) bool { return !f.Retryable }) {
		return Output{}, fmt.Errorf("%w: %s", errAnalysisUnavailable, failed[0].Reason)
	}

	if err := save(ctx, db, analysed); err != nil {
		return Output{}, fmt.Errorf("saving, nothing was written: %w", err)
	}
	logger.Info("done", "saved", len(analysed), "failed", len(failed))
	return Output{Analysed: analysed, Failed: failed}, nil
}

// group splits the sorted ids into evaluations to analyse, with their answers, and ones that cannot be.
func group(ids []int64, known map[int64]bool, answers []Answer) ([]evaluation, []Failed) {
	byID := map[int64][]Answer{}
	for _, a := range answers {
		byID[a.EvaluationID] = append(byID[a.EvaluationID], a)
	}

	var todo []evaluation
	var failed []Failed
	for _, id := range ids {
		switch {
		case !known[id]:
			failed = append(failed, Failed{ID: id, Reason: "no such evaluation"})
		case len(byID[id]) == 0:
			failed = append(failed, Failed{ID: id, Reason: "no answers"})
		default:
			todo = append(todo, evaluation{id: id, answers: byID[id]})
		}
	}
	return todo, failed
}

// averageTenths is the average score × 10, in whole numbers: [5, 4, 4] is 43. answers is never empty.
func averageTenths(answers []Answer) int {
	sum := 0
	for _, a := range answers {
		sum += a.Score
	}
	return sum * 10 / max(len(answers), 1)
}

Then the decision Omar asked for, just before saving: nothing analysed and every failure retryable means the API is down, so the run fails as a whole and saves nothing. Anything else is saved, and the failures are listed.

max(len(answers), 1) uses the built-in max, which takes any number of ordered values.

The tests cover the logic that needs no network or database. The runs below cover the rest, against the real ones.

worker/process_test.gonew file
package main

import (
	"slices"
	"testing"
)

func TestAverageTenths(t *testing.T) {
	answers := []Answer{{Score: 5}, {Score: 4}, {Score: 4}}
	if got := averageTenths(answers); got != 43 {
		t.Errorf("averageTenths = %d, want 43", got)
	}
}

func TestGroup(t *testing.T) {
	comment := "Clear"
	ids := []int64{1042, 1043, 1044, 9999}
	known := map[int64]bool{1042: true, 1043: true, 1044: true}
	answers := []Answer{
		{EvaluationID: 1042, Score: 5, Comment: &comment},
		{EvaluationID: 1042, Score: 4},
		{EvaluationID: 1043, Score: 3},
	}

	todo, failed := group(ids, known, answers)

	var got []int64
	for _, e := range todo {
		got = append(got, e.id)
	}
	if !slices.Equal(got, []int64{1042, 1043}) || len(todo[0].answers) != 2 {
		t.Errorf("todo = %v, want 1042 with 2 answers and 1043", got)
	}
	want := []Failed{{ID: 1044, Reason: "no answers"}, {ID: 9999, Reason: "no such evaluation"}}
	if !slices.Equal(failed, want) {
		t.Errorf("failed = %+v, want %+v", failed, want)
	}
}
$ go test -v
=== RUN   TestAverageTenths
--- PASS: TestAverageTenths (0.00s)
=== RUN   TestGroup
--- PASS: TestGroup (0.00s)
PASS
ok  	github.com/you/worker	0.003s

Step 5: main

Logs go to stderr without the time: Laravel captures stderr and writes it to its own log, which adds the timestamp. ReplaceAttr is a function the handler calls for every field, and returning an empty slog.Attr drops it.

The errors become exit codes in one place. errBadJob is a sentinel (the error-wrapping lesson) wrapped around the reason, so errors.Is picks out the jobs Laravel must not retry. The run has one 9-minute budget, under Laravel’s 10-minute process timeout, so Go always stops first and says why.

worker/main.gonew file
package main

import (
	"context"
	"database/sql"
	"encoding/json/v2"
	"errors"
	"fmt"
	"log/slog"
	"os"
	"time"

	_ "github.com/jackc/pgx/v5/stdlib"
)

// main reads a job on stdin, writes the result on stdout and logs on stderr. Exit codes:
// 0 done, 3 partly done (the result lists what failed), 2 a job that must not be retried,
// 1 a failure that may work later; nothing is written to the database for 1 and 2.
func main() {
	// No timestamps: Laravel adds its own when it logs these lines.
	logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
		ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
			if a.Key == slog.TimeKey && len(groups) == 0 {
				return slog.Attr{}
			}
			return a
		},
	}))

	output, err := run(logger)
	switch {
	case errors.Is(err, errBadJob):
		logger.Error("job rejected", "err", err)
		os.Exit(2)
	case err != nil:
		logger.Error("run failed", "err", err)
		os.Exit(1)
	}
	if len(output.Failed) > 0 {
		os.Exit(3)
	}
}

func run(logger *slog.Logger) (Output, error) {
	// The job is read before the config is checked: a malformed job is exit 2 even on a machine
	// whose config is also wrong, so Laravel never retries a job that can never succeed.
	var job Job
	if err := json.UnmarshalRead(os.Stdin, &job); err != nil {
		return Output{}, fmt.Errorf("%w: %v", errBadJob, err)
	}
	if len(job.EvaluationIDs) == 0 || len(job.EvaluationIDs) > 1000 {
		return Output{}, fmt.Errorf("%w: evaluation_ids must have 1 to 1000 ids, got %d", errBadJob, len(job.EvaluationIDs))
	}
	config, err := configFromEnv()
	if err != nil {
		return Output{}, err
	}

	// The whole run must end before Laravel's process timeout of 10 minutes.
	ctx, cancel := context.WithTimeout(context.Background(), 9*time.Minute)
	defer cancel()

	db, err := sql.Open("pgx", config.DatabaseURL)
	if err != nil {
		return Output{}, err
	}
	defer db.Close()
	db.SetMaxOpenConns(5)
	pingCtx, cancelPing := context.WithTimeout(ctx, 5*time.Second)
	defer cancelPing()
	if err := db.PingContext(pingCtx); err != nil {
		return Output{}, fmt.Errorf("connecting to the database: %w", err)
	}

	output, err := process(ctx, db, newAnalyser(config.AnalysisURL, logger), config.Concurrency, job, logger)
	if err != nil {
		return Output{}, err
	}
	if err := json.MarshalWrite(os.Stdout, output); err != nil {
		return Output{}, fmt.Errorf("writing the result: %w", err)
	}
	fmt.Println()
	return output, nil
}

Run it: the four outcomes

Each run starts from the same five pending evaluations. DATABASE_URL and ANALYSIS_URL come from the environment, as Laravel passes them. The binary was built with go build.

job.json
{"evaluation_ids": [1042, 1043]}
$ ./worker < job.json
level=INFO msg=loaded evaluations=2 skipped=0
level=INFO msg=done saved=2 failed=0
{"analysed":[{"id":1042,"average_tenths":43,"positive":1,"negative":1,"neutral":0},{"id":1043,"average_tenths":30,"positive":0,"negative":2,"neutral":0}],"failed":[]}

Exit 0: both analysed and saved. The JSON is the only thing on stdout; the two log lines are on stderr.

job.json
{"evaluation_ids": [1042, 1043, 1044, 1045, 9999]}
$ ./worker < job.json
level=INFO msg=loaded evaluations=3 skipped=2
level=INFO msg=done saved=3 failed=2
{"analysed":[{"id":1042,"average_tenths":43,"positive":1,"negative":1,"neutral":0},{"id":1043,"average_tenths":30,"positive":0,"negative":2,"neutral":0},{"id":1045,"average_tenths":50,"positive":2,"negative":0,"neutral":0}],"failed":[{"id":1044,"reason":"no answers","retryable":false},{"id":9999,"reason":"no such evaluation","retryable":false}]}
exit code 3

Exit 3, partly done. Three evaluations were analysed and saved in one transaction. 1044 has no answers and 9999 does not exist, both retryable: false: sending them again would not help, so the PHP side reports them instead of retrying.

job.json
{"evaluation_ids": [1042, 1046]}
$ ./worker < job.json
level=INFO msg=loaded evaluations=2 skipped=0
level=WARN msg=retrying evaluation_id=1042 attempt=1 reason="analysis API unreachable: Post \"http://127.0.0.1:8999/api/analyse\": dial tcp 127.0.0.1:8999: connect: connection refused"
level=WARN msg=retrying evaluation_id=1046 attempt=1 reason="analysis API unreachable: Post \"http://127.0.0.1:8999/api/analyse\": dial tcp 127.0.0.1:8999: connect: connection refused"
level=WARN msg=retrying evaluation_id=1042 attempt=2 reason="analysis API unreachable: Post \"http://127.0.0.1:8999/api/analyse\": dial tcp 127.0.0.1:8999: connect: connection refused"
level=WARN msg=retrying evaluation_id=1046 attempt=2 reason="analysis API unreachable: Post \"http://127.0.0.1:8999/api/analyse\": dial tcp 127.0.0.1:8999: connect: connection refused"
level=ERROR msg="run failed" err="the analysis API is unavailable, nothing was written: analysis API unreachable: Post \"http://127.0.0.1:8999/api/analyse\": dial tcp 127.0.0.1:8999: connect: connection refused"
exit code 1

Exit 1, with the analysis API unreachable (a wrong port). Each evaluation was tried three times, with 200 and 400 ms between attempts, then the run failed without saving anything. That is the “try later” Omar asked for: Laravel retries the whole job after its backoff.

job.json
{"evaluation_ids": "1042,1043"}
$ ./worker < job.json
level=ERROR msg="job rejected" err="the job is not valid: json: cannot unmarshal JSON string into Go []int64 within \"/evaluation_ids\""
exit code 2

Exit 2: the ids were sent as one string, the kind of bug a missing array_map('intval', …) causes. The JSON error names the member, /evaluation_ids. Nothing was touched, and Laravel will not retry it.

And when the setup is wrong

job.json
{"evaluation_ids": [1042]}
$ ./worker < job.json
level=ERROR msg="run failed" err="ANALYSIS_URL is not set"
exit code 1

A missing setting: one sentence, before anything is read or written.

job.json
{"evaluation_ids": [1042]}
$ ./worker < job.json
level=ERROR msg="run failed" err="connecting to the database: failed to connect to `user=postgres database=nordic`:\n\t127.0.0.1:5999 (127.0.0.1): dial error: dial tcp 127.0.0.1:5999: connect: connection refused\n\t127.0.0.1:5999 (127.0.0.1): dial error: dial tcp 127.0.0.1:5999: connect: connection refused"
exit code 1

The database is down (a wrong port): exit 1 at once, with the reason. Laravel retries later.

The Laravel side

The runner

Laravel’s Process facade starts the binary, gives it the job on stdin, and waits. The runner turns each exit code into exactly one decision, and returns a typed result:

app/Services/Worker/WorkerRunner.php
<?php

namespace App\Services\Worker;

use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Process;
use InvalidArgumentException;
use JsonException;

final class WorkerRunner
{
    public function __construct(private readonly string $binary, private readonly int $timeout = 600)
    {
    }

    /**
     * @param  list<int>  $evaluationIds
     *
     * @throws WorkerFailed  nothing was saved; retry the whole batch later
     * @throws InvalidArgumentException  the worker rejected the job; a bug on this side
     */
    public function analyse(array $evaluationIds): WorkerResult
    {
        $job = json_encode(['evaluation_ids' => array_map('intval', $evaluationIds)], JSON_THROW_ON_ERROR);

        $result = Process::input($job)->timeout($this->timeout)->run([$this->binary]);

        foreach (preg_split('/\R/', trim($result->errorOutput())) ?: [] as $line) {
            if ($line !== '') {
                Log::info('worker: ' . $line);
            }
        }

        return match ($result->exitCode()) {
            0, 3 => $this->parse($result->output()),
            2 => throw new InvalidArgumentException('the worker rejected the job; see the log'),
            default => throw new WorkerFailed('the worker exited with ' . $result->exitCode() . '; see the log'),
        };
    }

    /** @throws WorkerFailed */
    private function parse(string $stdout): WorkerResult
    {
        try {
            $data = json_decode($stdout, true, flags: JSON_THROW_ON_ERROR);
        } catch (JsonException $e) {
            throw new WorkerFailed('the worker wrote something that is not JSON', previous: $e);
        }

        $retry = [];
        $failed = [];
        foreach ($data['failed'] as $row) {
            if ($row['retryable']) {
                $retry[] = (int) $row['id'];
            } else {
                $failed[(int) $row['id']] = (string) $row['reason'];
            }
        }

        return new WorkerResult(count($data['analysed']), $retry, $failed);
    }
}

Each line of stderr becomes one Laravel log line, which gives the Go logs Laravel’s timestamps and channels. The exit code is read first and the JSON only for 0 and 3, the only codes that come with a result.

app/Services/Worker/WorkerResult.php
<?php

namespace App\Services\Worker;

final readonly class WorkerResult
{
    /**
     * @param  list<int>  $retry  evaluations to send again later
     * @param  array<int, string>  $failed  evaluation id => why it can never be analysed
     */
    public function __construct(public int $analysed, public array $retry, public array $failed)
    {
    }
}
app/Services/Worker/WorkerFailed.php
<?php

namespace App\Services\Worker;

use RuntimeException;

/** The worker did not finish, and saved nothing. Retrying later may succeed. */
final class WorkerFailed extends RuntimeException
{
}

The queued job

WorkerFailed is thrown on to the queue, which retries with backoff. A rejected job fails at once. Retryable ids from a partial run go into a new, delayed job, so the analysed ones are never sent twice:

app/Jobs/AnalyseEvaluations.php
<?php

namespace App\Jobs;

use App\Services\Worker\WorkerRunner;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Log;
use InvalidArgumentException;

final class AnalyseEvaluations implements ShouldQueue
{
    use Queueable;

    public int $tries = 5;

    /** @var list<int> */
    public array $backoff = [60, 300, 900, 1800];

    public int $timeout = 660;   // longer than the runner's own process timeout

    /** @param  list<int>  $evaluationIds */
    public function __construct(public readonly array $evaluationIds)
    {
    }

    public function handle(WorkerRunner $worker): void
    {
        try {
            $result = $worker->analyse($this->evaluationIds);
        } catch (InvalidArgumentException $e) {
            $this->fail($e);

            return;
        }

        foreach ($result->failed as $id => $reason) {
            Log::warning('evaluation cannot be analysed', ['evaluation_id' => $id, 'reason' => $reason]);
        }
        if ($result->retry !== []) {
            self::dispatch($result->retry)->delay(now()->addMinutes(5));
        }
    }
}

Three timeouts, nested: Go stops its own work at 9 minutes, Process kills the binary at 10, and the queue kills the PHP worker at 11. Each layer gets the chance to fail cleanly before the one around it steps in.

The artisan command

app/Console/Commands/AnalyseEvaluationsCommand.php
<?php

namespace App\Console\Commands;

use App\Jobs\AnalyseEvaluations;
use App\Models\Evaluation;
use Illuminate\Console\Command;

final class AnalyseEvaluationsCommand extends Command
{
    protected $signature = 'evaluations:analyse {--batch=200 : evaluations per worker run}';

    protected $description = 'Queue every pending evaluation for analysis by the Go worker';

    public function handle(): int
    {
        $batch = (int) $this->option('batch');
        if ($batch < 1 || $batch > 1000) {
            $this->error('--batch must be from 1 to 1000');

            return self::INVALID;
        }

        $jobs = 0;
        Evaluation::query()
            ->where('status', 'pending')
            ->select('id')
            ->chunkById($batch, function ($evaluations) use (&$jobs) {
                AnalyseEvaluations::dispatch($evaluations->pluck('id')->all());
                $jobs++;
            });

        $this->info("Queued {$jobs} batches of up to {$batch} evaluations.");

        return self::SUCCESS;
    }
}

self::INVALID is Artisan’s exit code 2, the same meaning as the worker’s. The command only queues; the work happens on the queue workers, where retries and timeouts are managed.

Deploy

terminal (in the deploy script)
(cd worker && GOOS=linux GOARCH=amd64 go build -o ../bin/worker .)

# a smoke test: an empty job must be rejected with exit 2, proving the binary starts
echo '{}' | bin/worker; test $? -eq 2

The build can run on any machine, including a Mac, and produces the Linux binary for the server. In Laravel’s .env: WORKER_BINARY, ANALYSIS_URL and DATABASE_URL next to the database settings it already has.

What changed, and what did not

BeforeAfter
Analysis callsOne at a time, in PHP8 at a time, in Go
Queries per batch of 200400 (answers + save, per evaluation)2 to load, 1 transaction to save
When the API is downEach evaluation fails on its own, some savedNothing saved, the whole job retried later
Queue, retries, scheduling, dashboardLaravelLaravel

The time the job takes is mostly the analysis API’s: 1,000 evaluations at 100 ms each are 100 seconds one at a time and about 13 seconds 8 at a time. Raise WORKER_CONCURRENCY only as far as the API’s owner agrees to.

PracticeTwo extensions

Extension 1: skip what is already analysed

Two overlapping jobs can send the same evaluation twice. Make load return only evaluations whose status is still pending, and report the others as failed with "already analysed", not retryable. Add a case to TestGroup with an id that is known but not pending.

Extension 2: lock while analysing

Better than skipping: claim the batch at the start, in its own short transaction, with update evaluations set status = 'analysing' where id = any($1) and status = 'pending' returning id. Only the returned ids are processed. Then decide what must happen to the analysing status when the run fails, so a crashed run does not leave evaluations stuck forever. (Hint: Laravel’s scheduler can reset rows that have been analysing for more than an hour.)

Remember

  • A worker’s contract is its exit codes: 0 done, 3 partly done, 2 do not retry, 1 retry later.
  • Results on stdout, logs on stderr, and nothing saved unless the whole batch can be.

Tomorrow is the Week 4 checkpoint: break the database in the middle of a save, and prove that nothing was half-written.