Go Playbook

Course › Week 5 · HTTP services with net/http › Day 6 · lesson 34 of 42 · 1 h 35 min reading + 3 h practice

Build the service

POST a batch, poll its status, and Laravel calls it with Http.

net/httpgoroutinesHttp facade

On this page
  1. The task
  2. The design
  3. The tables
  4. Step 1: config, and the HTTP pieces
  5. Step 2: the database
  6. Step 3: the background runner
  7. Step 4: the handlers
  8. Step 5: main
  9. Run it: one click
  10. When things go wrong
  11. The Laravel side
  12. The worker or the service?
  13. Practice
  14. Remember

The worker of the Week 4 build day answers when the batch is done, which is right for a nightly job and wrong for a button in the dashboard. Today the same analysis becomes a small HTTP service: it answers at once with a batch id, does the work in the background, and is asked for the status later.

It uses every lesson of this week, and the analysis code of Week 4. As before, the Go side was built and run here for real, against Postgres and the Laravel-style analysis API; the PHP side is syntax-checked but not executed.

#productMonday 14:30

Sara · productSchools keep asking for an Analyse now button. Right now they wait for the nightly run at 02:00 to see the results of an evaluation they closed in the morning.

Omar · backendI can’t start the worker from a web request: a big batch takes minutes and the request dies at 30 seconds. I need a small HTTP service. I post the ids, get a batch id back at once, and a queued job polls until it’s done.

Omar · backendTwo things I care about. Our Http client retries on timeouts, so a retried POST must not start a second batch. And a deploy must not lose a batch that was half-way through.

The design

RequestAnswerWhy
POST /api/batches with a new reference202 Accepted, the batch, a Location headerThe work starts in the background
the same reference and the same ids again200 OK, the same batchA retry of the same click: nothing new starts
the same reference with other ids409 ConflictA bug in the caller, never silently merged
GET /api/batches/{id}the batch: queued, running, done or failed, with its failuresWhat the queued job polls

The batch lives in Postgres, not in memory. A deploy stops the process; at its next start the service resumes every batch that is still queued or running. And because a batch is saved in one transaction at the end, a batch that was cut off left nothing half-written to redo.

analysis-service/
analysis-service/
├── go.mod            (module github.com/you/analysis-service)
├── main.go           (config, pool, resume, server, graceful shutdown)
├── config.go         (DATABASE_URL, ANALYSIS_URL, SERVICE_API_KEY, WORKER_CONCURRENCY)
├── http.go           (errors to responses, JSON, the API key, request logs)
├── batches.go        (the routes and the two handlers)
├── process.go        (the background runner: analyse, decide, save)
├── analysis.go       (the analysis API client, from Week 4)
├── db.go             (batches, answers, the final transaction)
└── batches_test.go

The tables

database/migrations/2026_12_02_000000_create_analysis_batches_tables.php
<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('analysis_batches', function (Blueprint $table) {
            $table->id();
            $table->string('reference', 100)->unique();
            $table->string('status', 20)->default('queued');
            $table->integer('total');
            $table->integer('analysed')->default(0);
            $table->integer('failed')->default(0);
            $table->string('error')->nullable();
            $table->timestamps();
        });
        // A Postgres array of ids: Laravel's schema builder has no column type for it.
        DB::statement('alter table analysis_batches add column evaluation_ids bigint[] not null');

        Schema::create('analysis_batch_failures', function (Blueprint $table) {
            $table->id();
            $table->foreignId('batch_id')->constrained('analysis_batches');
            $table->bigInteger('evaluation_id');
            $table->string('reason');
            $table->boolean('retryable');
        });
    }
};

The evaluations and answers tables are Week 4’s. The unique index on reference is what makes a retried POST safe even when two copies arrive at the same moment: only one insert can win.

Step 1: config, and the HTTP pieces

The worker’s config, with the service’s own settings: the listen address and the API key, which must be long enough to mean something.

analysis-service/config.gonew file
package main

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

// Config is everything the service needs from its environment, checked once at startup.
type Config struct {
	Addr        string
	DatabaseURL string
	AnalysisURL string
	APIKey      string
	Concurrency int
}

func configFromEnv() (Config, error) {
	c := Config{Addr: ":8080", Concurrency: 8}
	if addr := os.Getenv("SERVICE_ADDR"); addr != "" {
		c.Addr = addr
	}
	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
	}
	if c.APIKey, err = required("SERVICE_API_KEY"); err != nil {
		return Config{}, err
	}
	if len(c.APIKey) < 20 {
		return Config{}, fmt.Errorf("SERVICE_API_KEY must be at least 20 characters")
	}
	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
}

Everything from the dependencies lesson and the middleware lesson in one file: handle maps errors to statuses, now with a *conflictError for 409 and errStopping for a 503 with Retry-After while the service shuts down; writeJSON; the API key; the request log.

A method on one line, func (e *validationError) Error() string { return e.Message }, is how gofmt keeps a one-statement method that was written on one line.

analysis-service/http.gonew file
package main

import (
	"crypto/subtle"
	"encoding/json/v2"
	"errors"
	"log/slog"
	"net/http"
	"strings"
	"time"
)

// validationError is a request with wrong values: 422, with Laravel's shape.
type validationError struct {
	Message string              `json:"message"`
	Errors  map[string][]string `json:"errors"`
}

func (e *validationError) Error() string { return e.Message }

// conflictError is a request that contradicts what is stored: 409.
type conflictError struct{ message string }

func (e *conflictError) Error() string { return e.message }

type apiFunc func(w http.ResponseWriter, r *http.Request) error

// handle maps every error a handler returns to its response, in one place.
func (s *server) handle(fn apiFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		err := fn(w, r)
		if err == nil {
			return
		}
		var invalid *validationError
		var conflict *conflictError
		switch {
		case errors.As(err, &invalid):
			writeJSON(w, http.StatusUnprocessableEntity, invalid)
		case errors.As(err, &conflict):
			writeJSON(w, http.StatusConflict, map[string]string{"message": conflict.message})
		case errors.Is(err, errNotFound):
			writeJSON(w, http.StatusNotFound, map[string]string{"message": "Not Found"})
		case errors.Is(err, errStopping):
			w.Header().Set("Retry-After", "5")
			writeJSON(w, http.StatusServiceUnavailable, map[string]string{"message": "Service Unavailable"})
		default:
			s.logger.Error("request failed", "method", r.Method, "path", r.URL.Path, "err", err)
			writeJSON(w, http.StatusInternalServerError, map[string]string{"message": "Server Error"})
		}
	}
}

func writeJSON(w http.ResponseWriter, status int, v any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	if err := json.MarshalWrite(w, v, json.Deterministic(true)); err != nil {
		slog.Error("writing the response", "err", err)
	}
}

// requireAPIKey answers 401 unless the request carries "Authorization: Bearer <key>".
func requireAPIKey(key string, next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		given, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
		if !ok || subtle.ConstantTimeCompare([]byte(given), []byte(key)) != 1 {
			writeJSON(w, http.StatusUnauthorized, map[string]string{"message": "Unauthenticated."})
			return
		}
		next.ServeHTTP(w, r)
	})
}

type statusRecorder struct {
	http.ResponseWriter
	status int
}

func (r *statusRecorder) WriteHeader(status int) {
	r.status = status
	r.ResponseWriter.WriteHeader(status)
}

func logRequests(logger *slog.Logger, next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()
		rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
		next.ServeHTTP(rec, r)
		logger.Info("request", "method", r.Method, "path", r.URL.Path, "status", rec.status, "ms", time.Since(start).Milliseconds())
	})
}

Step 2: the database

createBatch is the heart of the retry safety: insert … on conflict (reference) do nothing returning id inserts a new batch, or does nothing and returns no row when the reference exists. sql.ErrNoRows therefore means “this is a retry, or a bug”, and the handler decides which by comparing the ids.

EvaluationIDs scans straight from the bigint[] column into a []int64; pgx converts the Postgres array. Its tag json:"-" keeps it out of the API’s answers, which show counts and failures, not the ids sent.

finishBatch writes every result, every failure and the batch’s new status in one transaction: a batch is either done with everything saved, or not done at all.

analysis-service/db.gonew file
package main

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

// Batch is one analysis batch, as the API shows it.
type Batch struct {
	ID            int64    `json:"id"`
	Reference     string   `json:"reference"`
	Status        string   `json:"status"` // queued, running, done or failed
	Total         int      `json:"total"`
	Analysed      int      `json:"analysed"`
	Failed        int      `json:"failed"`
	Error         *string  `json:"error"`
	Failures      []Failed `json:"failures"`
	EvaluationIDs []int64  `json:"-"`
}

// Analysed is one evaluation's result. Failed is an evaluation that was not analysed, and why.
type Analysed struct {
	ID            int64
	AverageTenths int
	Positive      int
	Negative      int
	Neutral       int
}

type Failed struct {
	EvaluationID int64  `json:"evaluation_id"`
	Reason       string `json:"reason"`
	Retryable    bool   `json:"retryable"`
}

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

var errNotFound = errors.New("not found")

// createBatch stores a new batch, or finds the one that already has this reference. created is
// true only for a new batch. The unique index on reference makes this safe when two requests with
// the same reference arrive at the same moment.
func createBatch(ctx context.Context, db *sql.DB, reference string, ids []int64) (Batch, bool, error) {
	var id int64
	err := db.QueryRowContext(ctx,
		"insert into analysis_batches (reference, evaluation_ids, total, created_at, updated_at) values ($1, $2, $3, now(), now()) on conflict (reference) do nothing returning id",
		reference, ids, len(ids)).Scan(&id)
	created := true
	if errors.Is(err, sql.ErrNoRows) {
		created = false // the reference exists: this request is a retry, or a bug
	} else if err != nil {
		return Batch{}, false, fmt.Errorf("storing the batch: %w", err)
	}

	var b Batch
	err = db.QueryRowContext(ctx, "select id from analysis_batches where reference = $1", reference).Scan(&b.ID)
	if err != nil {
		return Batch{}, false, fmt.Errorf("reading the batch: %w", err)
	}
	b, err = findBatch(ctx, db, b.ID)
	return b, created, err
}

// findBatch reads a batch and its failures.
func findBatch(ctx context.Context, db *sql.DB, id int64) (Batch, error) {
	b := Batch{Failures: []Failed{}}
	err := db.QueryRowContext(ctx,
		"select id, reference, status, total, analysed, failed, error, evaluation_ids from analysis_batches where id = $1", id).
		Scan(&b.ID, &b.Reference, &b.Status, &b.Total, &b.Analysed, &b.Failed, &b.Error, &b.EvaluationIDs)
	if errors.Is(err, sql.ErrNoRows) {
		return Batch{}, errNotFound
	}
	if err != nil {
		return Batch{}, fmt.Errorf("reading batch %d: %w", id, err)
	}

	rows, err := db.QueryContext(ctx, "select evaluation_id, reason, retryable from analysis_batch_failures where batch_id = $1 order by evaluation_id", id)
	if err != nil {
		return Batch{}, fmt.Errorf("reading the failures of batch %d: %w", id, err)
	}
	defer rows.Close()
	for rows.Next() {
		var f Failed
		if err := rows.Scan(&f.EvaluationID, &f.Reason, &f.Retryable); err != nil {
			return Batch{}, fmt.Errorf("reading the failures of batch %d: %w", id, err)
		}
		b.Failures = append(b.Failures, f)
	}
	return b, rows.Err()
}

// unfinishedBatches are the batches a stopped service left queued or running.
func unfinishedBatches(ctx context.Context, db *sql.DB) ([]int64, error) {
	rows, err := db.QueryContext(ctx, "select id from analysis_batches where status in ('queued', 'running') order by id")
	if err != nil {
		return nil, fmt.Errorf("listing unfinished batches: %w", err)
	}
	defer rows.Close()
	var ids []int64
	for rows.Next() {
		var id int64
		if err := rows.Scan(&id); err != nil {
			return nil, fmt.Errorf("listing unfinished batches: %w", err)
		}
		ids = append(ids, id)
	}
	return ids, rows.Err()
}

func setStatus(ctx context.Context, db *sql.DB, id int64, status string, reason *string) error {
	_, err := db.ExecContext(ctx, "update analysis_batches set status = $2, error = $3, updated_at = now() where id = $1", id, status, reason)
	if err != nil {
		return fmt.Errorf("setting batch %d to %s: %w", id, status, err)
	}
	return nil
}

// loadAnswers returns the ids among ids that exist, and all their answers.
func loadAnswers(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)
	}
	return known, answers, answerRows.Err()
}

// finishBatch saves every result, every failure and the batch's status in one transaction.
func finishBatch(ctx context.Context, db *sql.DB, batchID int64, analysed []Analysed, failed []Failed) error {
	tx, err := db.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	defer tx.Rollback()

	for _, r := range analysed {
		_, 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)
		}
	}
	for _, f := range failed {
		_, err := tx.ExecContext(ctx, "insert into analysis_batch_failures (batch_id, evaluation_id, reason, retryable) values ($1, $2, $3, $4)",
			batchID, f.EvaluationID, f.Reason, f.Retryable)
		if err != nil {
			return fmt.Errorf("saving the failure of evaluation %d: %w", f.EvaluationID, err)
		}
	}
	_, err = tx.ExecContext(ctx, "update analysis_batches set status = 'done', analysed = $2, failed = $3, error = null, updated_at = now() where id = $1",
		batchID, len(analysed), len(failed))
	if err != nil {
		return fmt.Errorf("finishing batch %d: %w", batchID, err)
	}
	return tx.Commit()
}

Step 3: the background runner

runner.start runs a batch in a goroutine registered in a WaitGroup (the goroutines lesson), so main can wait for running batches at shutdown. The goroutine uses the runner’s own context, not the request’s: the request ends with the 202 long before the batch does, and its context with it.

run is the worker’s logic: group, analyse with errgroup and a limit, decide, save. Two new checks: a batch already done or failed is skipped, so resuming twice is harmless; and if the context ended during the analysis (a deploy), it saves nothing and returns, leaving the batch running for the next start.

analysis-service/process.gonew file
package main

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

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

// runner runs batches in the background, after their request has been answered.
type runner struct {
	db          *sql.DB
	analyser    *Analyser
	logger      *slog.Logger
	concurrency int
	ctx         context.Context // ends when the service must stop working
	running     sync.WaitGroup
}

// start runs one batch in its own goroutine.
func (r *runner) start(batchID int64) {
	r.running.Go(func() {
		if err := r.run(r.ctx, batchID); err != nil {
			r.logger.Error("batch not finished", "batch", batchID, "err", err)
		}
	})
}

// run analyses one batch and saves its result. A batch it could not finish stays queued or running
// in the database, and the next start of the service picks it up again.
func (r *runner) run(ctx context.Context, batchID int64) error {
	b, err := findBatch(ctx, r.db, batchID)
	if err != nil {
		return err
	}
	if b.Status == "done" || b.Status == "failed" {
		return nil
	}
	if err := setStatus(ctx, r.db, batchID, "running", nil); err != nil {
		return err
	}

	known, answers, err := loadAnswers(ctx, r.db, b.EvaluationIDs)
	if err != nil {
		return err
	}
	todo, failed := group(b.EvaluationIDs, known, answers)

	results := make([]Analysed, len(todo))
	failures := make([]*Failure, len(todo))
	g, gctx := errgroup.WithContext(ctx)
	g.SetLimit(r.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 := r.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 err
	}
	// Stopped in the middle (a deploy): save nothing, the batch is resumed at the next start.
	if err := ctx.Err(); err != nil {
		return fmt.Errorf("stopped while analysing: %w", err)
	}

	var analysed []Analysed
	for i, e := range todo {
		if failures[i] != nil {
			failed = append(failed, Failed{EvaluationID: 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.EvaluationID, b.EvaluationID) })

	// Nothing analysed and every failure temporary: the API is down. The batch fails as a whole, so the
	// client can send it again later; nothing is half-saved.
	if len(analysed) == 0 && len(failed) > 0 && !slices.ContainsFunc(failed, func(f Failed) bool { return !f.Retryable }) {
		reason := "the analysis API is unavailable: " + failed[0].Reason
		r.logger.Warn("batch failed", "batch", batchID, "reason", reason)
		return setStatus(ctx, r.db, batchID, "failed", &reason)
	}
	if err := finishBatch(ctx, r.db, batchID, analysed, failed); err != nil {
		return err
	}
	r.logger.Info("batch done", "batch", batchID, "analysed", len(analysed), "failed", len(failed))
	return nil
}

// resume starts every batch a previous run of the service left unfinished.
func (r *runner) resume(ctx context.Context) error {
	ids, err := unfinishedBatches(ctx, r.db)
	if err != nil {
		return err
	}
	for _, id := range ids {
		r.logger.Info("resuming batch", "batch", id)
		r.start(id)
	}
	return nil
}

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

// group splits the sorted ids into evaluations to analyse 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{EvaluationID: id, Reason: "no such evaluation"})
		case len(byID[id]) == 0:
			failed = append(failed, Failed{EvaluationID: 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.
func averageTenths(answers []Answer) int {
	sum := 0
	for _, a := range answers {
		sum += a.Score
	}
	return sum * 10 / max(len(answers), 1)
}

// errStopping is returned by handlers that would start work while the service shuts down.
var errStopping = errors.New("the service is shutting down")

analysis.go is Week 4’s client, unchanged except that the request no longer sends a User-Agent:

analysis-service/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")

	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
}

Step 4: the handlers

validate is a method on the request type with a value receiver, and returns the ids sorted and without duplicates, so [1043, 1042] and [1042, 1043, 1042] are the same batch. storeBatch does Omar’s three cases in order: create, or find; a match is a retry and gets 200; the same reference with other ids gets 409; only a new batch starts and gets 202.

While the service shuts down, storeBatch refuses new work with a 503 and Retry-After, which Laravel’s client retries; showBatch keeps answering until the server closes.

analysis-service/batches.gonew file
package main

import (
	"encoding/json/v2"
	"fmt"
	"log/slog"
	"net/http"
	"slices"
	"strconv"
	"strings"
)

// server is the HTTP side: the routes, and the runner they hand work to.
type server struct {
	runner *runner
	logger *slog.Logger
	apiKey string
}

func (s *server) routes() http.Handler {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /api/health", func(w http.ResponseWriter, r *http.Request) {
		writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
	})
	mux.Handle("POST /api/batches", requireAPIKey(s.apiKey, s.handle(s.storeBatch)))
	mux.Handle("GET /api/batches/{id}", requireAPIKey(s.apiKey, s.handle(s.showBatch)))
	return logRequests(s.logger, mux)
}

type storeRequest struct {
	Reference     string  `json:"reference"`
	EvaluationIDs []int64 `json:"evaluation_ids"`
}

// validate checks the request and returns its ids sorted and without duplicates.
func (req storeRequest) validate() ([]int64, error) {
	errs := map[string][]string{}
	if strings.TrimSpace(req.Reference) == "" {
		errs["reference"] = []string{"The reference field is required."}
	} else if len(req.Reference) > 100 {
		errs["reference"] = []string{"The reference field must not be greater than 100 characters."}
	}
	switch {
	case len(req.EvaluationIDs) == 0:
		errs["evaluation_ids"] = []string{"The evaluation ids field is required."}
	case len(req.EvaluationIDs) > 1000:
		errs["evaluation_ids"] = []string{"The evaluation ids field must not have more than 1000 items."}
	case slices.ContainsFunc(req.EvaluationIDs, func(id int64) bool { return id < 1 }):
		errs["evaluation_ids"] = []string{"Every evaluation id must be at least 1."}
	}
	if len(errs) > 0 {
		first := "The given data was invalid."
		for _, field := range []string{"reference", "evaluation_ids"} {
			if messages, ok := errs[field]; ok {
				first = messages[0]
				break
			}
		}
		return nil, &validationError{Message: first, Errors: errs}
	}
	ids := slices.Clone(req.EvaluationIDs)
	slices.Sort(ids)
	return slices.Compact(ids), nil
}

// storeBatch answers 202 for a new batch, 200 for a retry of the same one, 409 for a reference
// that was used for other evaluations.
func (s *server) storeBatch(w http.ResponseWriter, r *http.Request) error {
	if s.runner.ctx.Err() != nil {
		return errStopping
	}
	var req storeRequest
	if err := json.UnmarshalRead(http.MaxBytesReader(w, r.Body, 64*1024), &req); err != nil {
		return &validationError{Message: "The request body is not valid JSON.", Errors: map[string][]string{}}
	}
	ids, err := req.validate()
	if err != nil {
		return err
	}

	b, created, err := createBatch(r.Context(), s.runner.db, req.Reference, ids)
	if err != nil {
		return err
	}
	if !created {
		if !slices.Equal(b.EvaluationIDs, ids) {
			return &conflictError{message: "The reference was already used for other evaluations."}
		}
		writeJSON(w, http.StatusOK, b)
		return nil
	}
	s.runner.start(b.ID)
	w.Header().Set("Location", fmt.Sprintf("/api/batches/%d", b.ID))
	writeJSON(w, http.StatusAccepted, b)
	return nil
}

func (s *server) showBatch(w http.ResponseWriter, r *http.Request) error {
	id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
	if err != nil {
		return errNotFound
	}
	b, err := findBatch(r.Context(), s.runner.db, id)
	if err != nil {
		return err
	}
	writeJSON(w, http.StatusOK, b)
	return nil
}
analysis-service/batches_test.gonew file
package main

import (
	"errors"
	"slices"
	"strings"
	"testing"
)

func TestValidate(t *testing.T) {
	ids, err := storeRequest{Reference: "close-77", EvaluationIDs: []int64{1043, 1042, 1043}}.validate()
	if err != nil {
		t.Fatalf("validate returned an error: %v", err)
	}
	if !slices.Equal(ids, []int64{1042, 1043}) {
		t.Errorf("ids = %v, want [1042 1043]: sorted, without duplicates", ids)
	}

	tests := []struct {
		name  string
		req   storeRequest
		field string
	}{
		{name: "no reference", req: storeRequest{EvaluationIDs: []int64{1}}, field: "reference"},
		{name: "a long reference", req: storeRequest{Reference: strings.Repeat("x", 101), EvaluationIDs: []int64{1}}, field: "reference"},
		{name: "no ids", req: storeRequest{Reference: "r"}, field: "evaluation_ids"},
		{name: "a zero id", req: storeRequest{Reference: "r", EvaluationIDs: []int64{1, 0}}, field: "evaluation_ids"},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			_, err := tt.req.validate()
			var invalid *validationError
			if !errors.As(err, &invalid) {
				t.Fatalf("validate error = %v, want a validationError", err)
			}
			if _, ok := invalid.Errors[tt.field]; !ok {
				t.Errorf("errors = %v, want one for %q", invalid.Errors, tt.field)
			}
		})
	}
}

func TestAverageTenths(t *testing.T) {
	if got := averageTenths([]Answer{{Score: 5}, {Score: 4}, {Score: 4}}); got != 43 {
		t.Errorf("averageTenths = %d, want 43", got)
	}
}
$ go test -v
=== RUN   TestValidate
=== RUN   TestValidate/no_reference
=== RUN   TestValidate/a_long_reference
=== RUN   TestValidate/no_ids
=== RUN   TestValidate/a_zero_id
--- PASS: TestValidate (0.00s)
    --- PASS: TestValidate/no_reference (0.00s)
    --- PASS: TestValidate/a_long_reference (0.00s)
    --- PASS: TestValidate/no_ids (0.00s)
    --- PASS: TestValidate/a_zero_id (0.00s)
=== RUN   TestAverageTenths
--- PASS: TestAverageTenths (0.00s)
PASS
ok  	github.com/you/analysis-service	0.004s

The handlers that need a database are tested end to end in the checkpoint, against a fresh database per test.

Step 5: main

The shutdown of the tests lesson, with one more stage. Two contexts: stopCtx ends on the signal and stops the HTTP server; workCtx ends only if the running batches have not finished 15 seconds later. Batches get the chance to finish; what cannot finish in time saves nothing and resumes on the next start.

make(chan struct{}) is a channel that carries no values, only the moment it is closed: the usual way to say “done”. The 10 + 15 seconds must fit inside what the platform waits before it kills the process: set Docker’s stop_grace_period or systemd’s TimeoutStopSec to 30 seconds.

analysis-service/main.gonew file
package main

import (
	"context"
	"database/sql"
	"errors"
	"log/slog"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

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

func main() {
	logger := slog.New(slog.NewTextHandler(os.Stderr, nil))
	if err := serve(logger); err != nil {
		logger.Error("service stopped", "err", err)
		os.Exit(1)
	}
}

func serve(logger *slog.Logger) error {
	config, err := configFromEnv()
	if err != nil {
		return err
	}
	db, err := sql.Open("pgx", config.DatabaseURL)
	if err != nil {
		return err
	}
	defer db.Close()
	db.SetMaxOpenConns(10)
	pingCtx, cancelPing := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancelPing()
	if err := db.PingContext(pingCtx); err != nil {
		return err
	}

	// stopCtx ends on SIGINT or SIGTERM; workCtx ends a little later, to let batches finish.
	stopCtx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()
	workCtx, stopWork := context.WithCancel(context.Background())
	defer stopWork()

	run := &runner{db: db, analyser: newAnalyser(config.AnalysisURL, logger), logger: logger, concurrency: config.Concurrency, ctx: workCtx}
	if err := run.resume(pingCtx); err != nil {
		return err
	}
	s := &server{runner: run, logger: logger, apiKey: config.APIKey}
	srv := &http.Server{Addr: config.Addr, Handler: s.routes(), ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 30 * time.Second, WriteTimeout: 30 * time.Second, IdleTimeout: 120 * time.Second}

	serveErr := make(chan error, 1)
	go func() {
		logger.Info("listening", "addr", config.Addr)
		serveErr <- srv.ListenAndServe()
	}()
	select {
	case err := <-serveErr:
		return err
	case <-stopCtx.Done():
	}

	logger.Info("shutting down")
	shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	if err := srv.Shutdown(shutdownCtx); err != nil {
		return err
	}
	if err := <-serveErr; !errors.Is(err, http.ErrServerClosed) {
		return err
	}

	// Give running batches up to 15 seconds; what is still running then is stopped, saves nothing,
	// and is resumed by the next start.
	finished := make(chan struct{})
	go func() {
		run.running.Wait()
		close(finished)
	}()
	select {
	case <-finished:
	case <-time.After(15 * time.Second):
		logger.Warn("stopping unfinished batches; they resume at the next start")
		stopWork()
		<-finished
	}
	logger.Info("stopped cleanly")
	return nil
}

Run it: one click

$ curl -s -i -X POST -H 'Authorization: Bearer 9f2c4e1ab7d05e38a1c6' -H 'Content-Type: application/json' -d '{"reference": "dashboard-7f3a", "evaluation_ids": [1043, 1042, 1042, 1044, 9999]}' http://127.0.0.1:8080/api/batches
HTTP/1.1 202 Accepted
Content-Type: application/json
Location: /api/batches/1
Content-Length: 116

{"id":1,"reference":"dashboard-7f3a","status":"queued","total":4,"analysed":0,"failed":0,"error":null,"failures":[]}

0.6 s later:

$ curl -s -H 'Authorization: Bearer 9f2c4e1ab7d05e38a1c6' http://127.0.0.1:8080/api/batches/1
{"id":1,"reference":"dashboard-7f3a","status":"done","total":4,"analysed":2,"failed":2,"error":null,"failures":[{"evaluation_id":1044,"reason":"no answers","retryable":false},{"evaluation_id":9999,"reason":"no such evaluation","retryable":false}]}
$ curl -s -i -X POST -H 'Authorization: Bearer 9f2c4e1ab7d05e38a1c6' -H 'Content-Type: application/json' -d '{"reference": "dashboard-7f3a", "evaluation_ids": [1042, 1043, 1044, 9999]}' http://127.0.0.1:8080/api/batches
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 247

{"id":1,"reference":"dashboard-7f3a","status":"done","total":4,"analysed":2,"failed":2,"error":null,"failures":[{"evaluation_id":1044,"reason":"no answers","retryable":false},{"evaluation_id":9999,"reason":"no such evaluation","retryable":false}]}
$ curl -s -i -X POST -H 'Authorization: Bearer 9f2c4e1ab7d05e38a1c6' -H 'Content-Type: application/json' -d '{"reference": "dashboard-7f3a", "evaluation_ids": [1045]}' http://127.0.0.1:8080/api/batches
HTTP/1.1 409 Conflict
Content-Type: application/json
Content-Length: 67

{"message":"The reference was already used for other evaluations."}
the server’s log (stderr), after Ctrl-C
time=2026-12-03T19:11:11.758+02:00 level=INFO msg=listening addr=:8080
time=2026-12-03T19:11:11.960+02:00 level=INFO msg=request method=POST path=/api/batches status=202 ms=3
time=2026-12-03T19:11:12.079+02:00 level=INFO msg="batch done" batch=1 analysed=2 failed=2
time=2026-12-03T19:11:12.572+02:00 level=INFO msg=request method=GET path=/api/batches/1 status=200 ms=1
time=2026-12-03T19:11:12.583+02:00 level=INFO msg=request method=POST path=/api/batches status=200 ms=1
time=2026-12-03T19:11:12.593+02:00 level=INFO msg=request method=POST path=/api/batches status=409 ms=1
time=2026-12-03T19:11:12.595+02:00 level=INFO msg="shutting down"
time=2026-12-03T19:11:12.595+02:00 level=INFO msg="stopped cleanly"

The POST answered 202 at once with the batch queued; 0.6 seconds later the batch is done: two evaluations analysed, and two failures, neither retryable. The same click retried, with the ids in another order and without the duplicate, got 200 and the same batch, and nothing new started. The same reference with other ids got 409.

The log shows each request, the batch finishing between them, and the graceful stop at the end with nothing left running.

$ curl -s -i -X POST -H 'Content-Type: application/json' -d '{"reference": "dashboard-8c01", "evaluation_ids": [1042]}' http://127.0.0.1:8080/api/batches
HTTP/1.1 401 Unauthorized
Content-Type: application/json
Content-Length: 30

{"message":"Unauthenticated."}
$ curl -s -i -X POST -H 'Authorization: Bearer 9f2c4e1ab7d05e38a1c6' -H 'Content-Type: application/json' -d '{"reference": "", "evaluation_ids": [1042, 0]}' http://127.0.0.1:8080/api/batches
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json
Content-Length: 167

{"message":"The reference field is required.","errors":{"evaluation_ids":["Every evaluation id must be at least 1."],"reference":["The reference field is required."]}}
$ curl -s http://127.0.0.1:8080/api/health
{"status":"ok"}
the server’s log (stderr), after Ctrl-C
time=2026-12-03T19:11:14.274+02:00 level=INFO msg=listening addr=:8080
time=2026-12-03T19:11:14.475+02:00 level=INFO msg=request method=POST path=/api/batches status=401 ms=0
time=2026-12-03T19:11:14.485+02:00 level=INFO msg=request method=POST path=/api/batches status=422 ms=0
time=2026-12-03T19:11:14.494+02:00 level=INFO msg=request method=GET path=/api/health status=200 ms=0
time=2026-12-03T19:11:14.495+02:00 level=INFO msg="shutting down"
time=2026-12-03T19:11:14.495+02:00 level=INFO msg="stopped cleanly"

No key: 401. A bad body: 422 with every field’s message. The health check needs no key.

When things go wrong

The analysis API is down

$ curl -s -i -X POST -H 'Authorization: Bearer 9f2c4e1ab7d05e38a1c6' -H 'Content-Type: application/json' -d '{"reference": "dashboard-9d22", "evaluation_ids": [1042, 1045]}' http://127.0.0.1:8080/api/batches
HTTP/1.1 202 Accepted
Content-Type: application/json
Location: /api/batches/1
Content-Length: 116

{"id":1,"reference":"dashboard-9d22","status":"queued","total":2,"analysed":0,"failed":0,"error":null,"failures":[]}

1.5 s later:

$ curl -s -H 'Authorization: Bearer 9f2c4e1ab7d05e38a1c6' http://127.0.0.1:8080/api/batches/1
{"id":1,"reference":"dashboard-9d22","status":"failed","total":2,"analysed":0,"failed":0,"error":"the analysis API is unavailable: analysis API unreachable: Post \"http://127.0.0.1:8999/api/analyse\": dial tcp 127.0.0.1:8999: connect: connection refused","failures":[]}
the server’s log (stderr), after Ctrl-C
time=2026-12-03T19:11:16.474+02:00 level=INFO msg=listening addr=:8080
time=2026-12-03T19:11:16.675+02:00 level=INFO msg=request method=POST path=/api/batches status=202 ms=4
time=2026-12-03T19:11:16.679+02:00 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"
time=2026-12-03T19:11:16.679+02:00 level=WARN msg=retrying evaluation_id=1045 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"
time=2026-12-03T19:11:16.880+02:00 level=WARN msg=retrying evaluation_id=1045 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"
time=2026-12-03T19:11:16.880+02:00 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"
time=2026-12-03T19:11:17.281+02:00 level=WARN msg="batch failed" batch=1 reason="the analysis API is unavailable: analysis API unreachable: Post \"http://127.0.0.1:8999/api/analyse\": dial tcp 127.0.0.1:8999: connect: connection refused"
time=2026-12-03T19:11:18.187+02:00 level=INFO msg=request method=GET path=/api/batches/1 status=200 ms=1
time=2026-12-03T19:11:18.188+02:00 level=INFO msg="shutting down"
time=2026-12-03T19:11:18.188+02:00 level=INFO msg="stopped cleanly"

Every call was tried three times, then the batch failed as a whole with the reason, and no evaluation was touched. The Laravel side fails the poll and the user can press the button again later, with a new reference.

A deploy cut a batch off

Here the database starts with batch 7 left running by a process that was stopped in the middle of it. The new process resumes it at once:

0.6 s later:

$ curl -s -H 'Authorization: Bearer 9f2c4e1ab7d05e38a1c6' http://127.0.0.1:8080/api/batches/7
{"id":7,"reference":"nightly-2026-12-02","status":"done","total":3,"analysed":3,"failed":0,"error":null,"failures":[]}
the server’s log (stderr), after Ctrl-C
time=2026-12-03T19:11:19.782+02:00 level=INFO msg="resuming batch" batch=7
time=2026-12-03T19:11:19.782+02:00 level=INFO msg=listening addr=:8080
time=2026-12-03T19:11:19.891+02:00 level=INFO msg="batch done" batch=7 analysed=3 failed=0
time=2026-12-03T19:11:20.586+02:00 level=INFO msg=request method=GET path=/api/batches/7 status=200 ms=1
time=2026-12-03T19:11:20.587+02:00 level=INFO msg="shutting down"
time=2026-12-03T19:11:20.587+02:00 level=INFO msg="stopped cleanly"

resuming batch is the first thing in the log, before the server listens. Nothing had been saved for batch 7, because nothing is saved before the final transaction, so analysing it again from the start is correct.

The setup is wrong

$ ./analysis-service
time=2026-12-03T19:11:22.113+02:00 level=ERROR msg="service stopped" err="SERVICE_API_KEY must be at least 20 characters"
exit code 1

It refuses to start, with the reason, before it opens a port. A service that starts with a guessable key is worse than one that does not start.

The Laravel side

The settings

config/services.php (part)
    'analysis' => [
        'url' => env('ANALYSIS_SERVICE_URL', 'http://127.0.0.1:8080/api'),
        'key' => env('ANALYSIS_SERVICE_KEY'),   // the service's SERVICE_API_KEY
    ],

The client

One class talks to the service. retry repeats a request only when repeating can help (no connection, 429, 503), and repeating a POST is safe here because of the reference. throw() turns every other error status into a RequestException:

app/Services/Analysis/AnalysisService.php
<?php

namespace App\Services\Analysis;

use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
use Throwable;

final class AnalysisService
{
    public function __construct(private readonly string $url, private readonly string $key)
    {
    }

    /**
     * @param  list<int>  $evaluationIds
     *
     * @throws ConnectionException  the service could not be reached, even after the retries
     * @throws RequestException  the service refused the batch (401, 409, 422) or kept failing
     */
    public function submit(string $reference, array $evaluationIds): AnalysisBatch
    {
        $response = $this->client()->post('/batches', [
            'reference' => $reference,
            'evaluation_ids' => array_values(array_map('intval', $evaluationIds)),
        ]);

        return AnalysisBatch::fromArray($response->json());
    }

    /** @throws ConnectionException|RequestException */
    public function status(int $batchId): AnalysisBatch
    {
        return AnalysisBatch::fromArray($this->client()->get("/batches/{$batchId}")->json());
    }

    private function client(): PendingRequest
    {
        return Http::baseUrl($this->url)
            ->withToken($this->key)
            ->acceptJson()
            ->timeout(10)
            ->retry(3, 500, fn (Throwable $e): bool => $e instanceof ConnectionException
                || ($e instanceof RequestException && in_array($e->response->status(), [429, 503], true)))
            ->throw();
    }
}

Bind it once in AppServiceProvider::register(): $this->app->singleton(AnalysisService::class, fn () => new AnalysisService(config('services.analysis.url'), config('services.analysis.key')));.

app/Services/Analysis/AnalysisBatch.php
<?php

namespace App\Services\Analysis;

final readonly class AnalysisBatch
{
    /**
     * @param  list<array{evaluation_id: int, reason: string, retryable: bool}>  $failures
     */
    public function __construct(
        public int $id,
        public string $reference,
        public string $status,
        public int $analysed,
        public ?string $error,
        public array $failures,
    ) {
    }

    /** @param  array<string, mixed>  $data */
    public static function fromArray(array $data): self
    {
        return new self(
            (int) $data['id'],
            (string) $data['reference'],
            (string) $data['status'],
            (int) $data['analysed'],
            isset($data['error']) ? (string) $data['error'] : null,
            $data['failures'],
        );
    }

    public function finished(): bool
    {
        return in_array($this->status, ['done', 'failed'], true);
    }

    /** @return list<int> */
    public function retryableIds(): array
    {
        $retryable = array_filter($this->failures, fn (array $f): bool => $f['retryable']);

        return array_values(array_map(fn (array $f): int => (int) $f['evaluation_id'], $retryable));
    }
}

The button

The controller sends the batch and answers the browser at once. A fresh reference per click, made before the request, is what makes retry safe: every retry of this click carries the same one.

app/Http/Controllers/AnalyseNowController.php
<?php

namespace App\Http\Controllers;

use App\Jobs\WatchAnalysisBatch;
use App\Services\Analysis\AnalysisService;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\RequestException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

final class AnalyseNowController
{
    public function __invoke(Request $request, AnalysisService $analysis): JsonResponse
    {
        $validated = $request->validate([
            'evaluation_ids' => ['required', 'array', 'min:1', 'max:500'],
            'evaluation_ids.*' => ['integer'],
        ]);

        try {
            $batch = $analysis->submit('dashboard-' . Str::uuid(), $validated['evaluation_ids']);
        } catch (ConnectionException|RequestException $e) {
            Log::error('analysis service refused or unreachable', ['error' => $e->getMessage()]);

            return response()->json(['message' => 'Analysis is not available right now. Try again in a few minutes.'], 503);
        }

        WatchAnalysisBatch::dispatch($batch->id)->delay(now()->addSeconds(2));

        return response()->json(['batch' => $batch->id, 'status' => $batch->status], 202);
    }
}

The poll

A queued job asks for the status, and puts itself back on the queue for 5 seconds while the batch is not finished. retryUntil gives up after 30 minutes, however many polls that took. Retryable failures go into one new batch; its reference ends in -retry, so they are retried once and not forever:

app/Jobs/WatchAnalysisBatch.php
<?php

namespace App\Jobs;

use App\Services\Analysis\AnalysisService;
use DateTimeInterface;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Log;

final class WatchAnalysisBatch implements ShouldQueue
{
    use Queueable;

    public function __construct(public readonly int $batchId)
    {
    }

    public function retryUntil(): DateTimeInterface
    {
        return now()->addMinutes(30);
    }

    public function handle(AnalysisService $analysis): void
    {
        $batch = $analysis->status($this->batchId);

        if (! $batch->finished()) {
            $this->release(5);

            return;
        }

        if ($batch->status === 'failed') {
            $this->fail($batch->error ?? 'the analysis batch failed');

            return;
        }

        Log::info('analysis batch done', ['batch' => $batch->id, 'analysed' => $batch->analysed]);

        $retry = $batch->retryableIds();
        if ($retry !== [] && ! str_ends_with($batch->reference, '-retry')) {
            $next = $analysis->submit($batch->reference . '-retry', $retry);
            self::dispatch($next->id)->delay(now()->addMinutes(2));
        }
    }
}

An exception from status (the service restarting for a moment) fails this attempt, and the queue tries again with its backoff until retryUntil. A failed batch fails the job for good: polling again cannot change the batch’s result.

The worker or the service?

The worker (Week 4)The service
Laravel reaches it withProcess: a binary per batchHttp: one long-running server
Answer timeWhen the batch is doneAt once: 202 and an id
FitsThe nightly run, from a queued jobA button, or another app
RetriesThe queue retries the jobThe reference makes a repeated POST safe
Runs onThe Laravel server, no new process to manageIts own process: systemd, Docker or a Forge daemon

Both use the same analysis code. Many teams keep both: the nightly run as a worker, the button as a service. Week 6 builds this service a third way, on Laravel Go, where the queue is part of the framework.

PracticeTwo extensions

Extension 1: more than one instance

Run two copies behind a load balancer and both resume the same unfinished batches at startup. Make the claim atomic: update analysis_batches set status = 'running', updated_at = now() where id = $1 and (status = 'queued' or (status = 'running' and updated_at < now() - interval '5 minutes')) returning id. Only the copy that gets the row runs the batch. Decide how a long batch keeps its updated_at fresh while it runs, so the other copy does not take it over.

Extension 2: cancel a batch

Add DELETE /api/batches/{id}: it sets a queued batch to cancelled and answers 200, and answers 409 for a batch that is running or finished. Make run skip a cancelled batch, and add cancelled to finished() on the Laravel side.

Remember

  • Answer long work with 202 and an id; a client reference plus a unique index makes a retried POST safe.
  • Background work uses its own context, lives in the database, and is resumed at startup.

Tomorrow: the Week 5 checkpoint, with integration tests that run the real routes against a fresh database for every answer the service can give.