Course › Week 6 · Laravel Go › Day 6 · lesson 41 of 42 · 55 min reading + 3 h practice
Build the service on Laravel Go
The Week 5 analysis service again: the queue takes over the background work, the rules stay yours.
On this page
The Week 5 build day wrote an analysis service on net/http: config, error mapping, a goroutine runner that resumed batches at startup, a two-stage graceful shutdown. Today the same service on Laravel Go, with the same API, so the PHP client of that day works unchanged.
The point of the day is the split. The framework takes over what every service needs (routes, validation, the queue, retries of a job, shutdown). The rules that make this service correct are still yours to write, and the code below keeps them where you can read them.
#backendFriday 11:10
Omar · backendThe analysis service works, but I’m the only one who can change it. It has its own runner, its own shutdown code, its own error mapping. Nobody else on the team reads that.
Lina · tech leadLaravel Go is out. Can we move it there and keep the API exactly as it is? The Laravel job that polls it must not change.
Omar · backendAnd keep the guarantees: a retried POST never starts a second batch, and a deploy never loses one. Our app’s tables stay in our database; the service doesn’t get to create a users table next to ours.
The design
| Week 5, by hand | Laravel Go |
|---|---|
config.go: env vars, checked at startup | services/services.go, .env, and checks where each value is used |
http.go: errors mapped to statuses, JSON, the request log | web.Fail, web.Abortf, the framework’s JSON errors and log |
storeRequest.validate | StoreBatch.Rules, a 422 in Laravel’s shape |
db.go: SQL in strings, rows scanned by hand | models, model.Create, With("failures") |
process.go: a goroutine runner, resume at startup | a queued job: it is a row in jobs until it has run |
main.go: signals, two-stage shutdown | built in: the server and the worker finish what is in progress |
| one database, shared with the PHP app | its own database, and a laravel connection for the PHP app’s tables |
The last row is Omar’s condition. A Laravel Go app has framework tables with the same names as PHP Laravel’s: users, sessions, cache, jobs, failed_jobs. Pointed at the PHP app’s database, migrate would collide with them. So the service keeps its own database (DATABASE_URL) for its batches and its queue, and reaches evaluations and answers through a second connection.
analysis/ (laravel new analysis --go)
├── bootstrap/app.go (+ the "laravel" database connection)
├── services/services.go (SERVICE_API_KEY, ANALYSIS_URL, ANALYSIS_CONCURRENCY)
├── apikeys/apikeys.go (the Bearer key)
├── database/migrations/ (+ analysis_batches, analysis_batch_failures)
├── models/
│ ├── analysis_batch.go (this app's tables)
│ └── evaluation.go (the PHP app's tables)
├── analysis/analysis.go (the analysis API client)
├── jobs/analyse_batch.go (the work, and the rules)
├── handlers/batches/batches.go (POST and GET)
└── routes/api.go
Step 1: settings and the second database
Configure adds named database connections. "laravel" reads its URL from LARAVEL_DATABASE_URL; an empty one makes each query on that connection fail with an error that says so, and connections open on the first query, so a database that is down does not stop the app from starting.
package bootstrap
import (
laravel "go.laravel.com"
"go.laravel.com/auth"
"go.laravel.com/config"
"go.laravel.com/db"
"go.laravel.com/db/postgres"
"go.laravel.com/inertia"
"go.laravel.com/web"
"app/commands"
"app/database/migrations"
"app/database/schema"
"app/database/seeders"
"app/jobs"
"app/listeners"
"app/models"
"app/resources"
"app/routes"
"app/services"
)
func Options() laravel.Options {
return laravel.Options{
Routes: laravel.Routes{
Web: routes.Web,
API: routes.API,
Channels: routes.Channels,
Health: "/up",
},
Middleware: func(m *laravel.Middleware, cfg *config.Config) {
m.Web.Append(auth.Session[models.User]{})
m.Web.Append(inertia.Middleware{
Share: share,
ErrorPage: "Error",
})
},
Views: resources.Views,
Drivers: []db.Driver{postgres.Driver},
Migrations: migrations.All,
Schema: schema.Dumps,
Seeders: seeders.All,
Commands: commands.All,
Schedule: commands.Schedule,
Listeners: listeners.All,
Jobs: jobs.All,
Services: laravel.BuildServices(services.New),
Configure: configure,
}
}
// configure adds the PHP Laravel app's database as the "laravel" connection: its evaluations and
// answers are read and written there, never copied.
func configure(cfg *config.Config, env *config.Env) {
cfg.Database.Connections = map[string]config.Connection{
"laravel": {URL: env.String("LARAVEL_DATABASE_URL", "")},
}
}
func share(r *web.Request) (inertia.Props, error) {
return inertia.Props{
"name": config.From(r).App.Name,
"status": r.Session().Get("status"),
}, nil
}
The service’s own settings. Each has a fallback, and the code that uses a setting checks it, so migrate and key:generate run on a fresh clone:
package services
import (
"context"
laravel "go.laravel.com"
"go.laravel.com/config"
)
type Services struct {
// APIKey is the key the Laravel app sends as a Bearer token.
APIKey string
// AnalysisURL is the endpoint that scores one evaluation's comments.
AnalysisURL string
// Concurrency is how many evaluations of a batch are analysed at the same time.
Concurrency int
}
func New(env *config.Env, app *laravel.App) Services {
return Services{
APIKey: env.String("SERVICE_API_KEY", ""),
AnalysisURL: env.String("ANALYSIS_URL", ""),
Concurrency: env.Int("ANALYSIS_CONCURRENCY", 8),
}
}
func From(ctx context.Context) *Services {
return laravel.ServicesOf[*Services](ctx)
}
The routes lesson’s middleware, with Week 5’s rule that a key shorter than 20 characters is no key at all:
package apikeys
import (
"crypto/subtle"
"errors"
"net/http"
"strings"
"go.laravel.com/web"
"app/services"
)
// Required lets a request through only with the API key as its Bearer token.
type Required struct{}
func (Required) Handle(r *web.Request, next web.Next) *web.Response {
key := services.From(r).APIKey
if len(key) < 20 {
return web.Fail(errors.New("apikeys: SERVICE_API_KEY must be set, with at least 20 characters"))
}
sent, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
if !ok || subtle.ConstantTimeCompare([]byte(sent), []byte(key)) != 1 {
return web.Abort(http.StatusUnauthorized)
}
return next(r)
}
Step 2: tables and models
Week 5 stored the ids in a Postgres bigint[]. The schema builder writes SQL for four databases and has no array column, so the ids go into a jsonb column instead. unique() on reference is still what makes a retried POST safe when two copies arrive at once.
package migrations
import (
"context"
"go.laravel.com/schema"
)
func createAnalysisBatchesTables(ctx context.Context) error {
err := schema.Create(ctx, "analysis_batches", func(table *schema.Blueprint) {
table.ID()
table.String("reference").Length(100).Unique()
table.JSONB("evaluation_ids")
table.String("status").Length(20).Default("queued")
table.Integer("total")
table.Integer("analysed").Default(0)
table.Integer("failed").Default(0)
table.String("error").Nullable()
table.Timestamps()
})
if err != nil {
return err
}
return schema.Create(ctx, "analysis_batch_failures", func(table *schema.Blueprint) {
table.ID()
table.ForeignID("analysis_batch_id").Constrained().CascadeOnDelete()
table.BigInteger("evaluation_id")
table.String("reason")
table.Boolean("retryable")
})
}
The batch, its failures, and the statuses as constants:
package models
import (
"time"
"go.laravel.com/db"
)
type BatchStatus string
const (
Queued BatchStatus = "queued"
Running BatchStatus = "running"
Done BatchStatus = "done"
Failed BatchStatus = "failed"
)
type AnalysisBatch struct {
ID int64 `json:"id"`
Reference string `json:"reference"`
EvaluationIDs db.JSON[[]int64] `json:"-" db:"evaluation_ids"`
Status BatchStatus `json:"status" db:",default"`
Total int `json:"total"`
Analysed int `json:"analysed" db:",default"`
Failed int `json:"failed" db:",default"`
Error *string `json:"error"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Failures []AnalysisBatchFailure `json:"failures,omitzero" model:"has_many"`
}
type AnalysisBatchFailure struct {
ID int64 `json:"-"`
AnalysisBatchID int64 `json:"-"`
EvaluationID int64 `json:"evaluation_id"`
Reason string `json:"reason"`
Retryable bool `json:"retryable"`
}
Look at the tag on EvaluationIDs. Without it, the column name is the field’s name in snake case, and the snake case of EvaluationIDs is evaluation_i_ds: every insert failed with “column evaluation_i_ds does not exist” until the tag named the column. A field with an initialism (IDs, URL, HTTP) needs a db tag whenever the column is not what the rule makes of it.
db.JSON[[]int64] stores the slice as JSON and gives it back in .V. json:"-" keeps the ids out of the API’s answers, as in Week 5. Failures is a has_many: the foreign key is the model’s name plus _id, analysis_batch_id.
The PHP app’s two tables, as models. Nothing in them says which database they live in: that is decided by the context each query gets.
package models
import "time"
// Evaluation and Answer are tables of the PHP Laravel app, on the "laravel" connection.
type Evaluation struct {
ID int64 `json:"id"`
School string `json:"school"`
Status string `json:"status"`
AverageTenths *int `json:"average_tenths"`
Positive *int `json:"positive"`
Negative *int `json:"negative"`
Neutral *int `json:"neutral"`
AnalysedAt *time.Time `json:"analysed_at"`
CreatedAt *time.Time `json:"created_at"`
UpdatedAt *time.Time `json:"updated_at"`
Answers []Answer `json:"answers,omitzero" model:"has_many"`
}
type Answer struct {
ID int64 `json:"id"`
EvaluationID int64 `json:"evaluation_id"`
Question string `json:"question"`
Score int `json:"score"`
Comment *string `json:"comment"`
}
Every column the PHP migration made nullable is a pointer here, and there is no migration for these tables in this app: they belong to the PHP app, which migrates them.
Step 3: the analysis client
Week 5’s Analyser was 97 lines with its own retry loop. httpclient has retries: Retry(3, waits…) with RetryWhen choosing which errors are worth another try. EnsureSuccessful makes any status outside 2xx an error, so a 422 is a *StatusError that retryable rejects:
package analysis
import (
"context"
"errors"
"fmt"
"net/http"
"time"
"go.laravel.com/httpclient"
)
// 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
}
// Analyse makes up to three attempts. Only connection failures, timeouts, 429 and 5xx are retried.
func Analyse(ctx context.Context, url string, evaluationID int64, comments []string) (Sentiment, *Failure) {
res, err := httpclient.EnsureSuccessful().
Timeout(10*time.Second).
Retry(3, 200*time.Millisecond, 400*time.Millisecond).
RetryWhen(retryable).
JSON(map[string]any{"evaluation_id": evaluationID, "comments": comments}).
Post(ctx, url)
if err != nil {
return Sentiment{}, &Failure{Reason: err.Error(), Retryable: retryable(err, 0)}
}
s, err := res.JSON[Sentiment]()
if err != nil {
return Sentiment{}, &Failure{Reason: fmt.Sprintf("the analysis API sent an unexpected body: %v", err)}
}
return s, nil
}
// retryable is true for an error that may go away: no connection, a timeout, 429 or 5xx.
func retryable(err error, attempt int) bool {
var unreachable *httpclient.ConnectionError
if errors.As(err, &unreachable) {
return true
}
var status *httpclient.StatusError
if errors.As(err, &status) {
return status.Response.Status == http.StatusTooManyRequests || status.Response.Status >= 500
}
return false
}
The rule is Week 4’s: retry no connection, timeouts, 429 and 5xx; never a 4xx, because the same request gets the same answer. A Failure remembers whether it was temporary, which the job needs.
Step 4: the job
Everything that was process.go, as a job. db.Connection(ctx, "laravel") returns a context whose queries run on the PHP app’s database; FindMany loads the batch’s evaluations with their answers in two queries, and task.Map analyses them with at most Concurrency calls at once (the queues and tasks lesson).
package jobs
import (
"cmp"
"context"
"fmt"
"log/slog"
"slices"
"time"
"go.laravel.com/db"
"go.laravel.com/model"
"go.laravel.com/queue"
"go.laravel.com/task"
"app/analysis"
"app/models"
"app/services"
)
// AnalyseBatch analyses every evaluation of a batch and saves the results.
type AnalyseBatch struct {
Batch models.AnalysisBatch `queue:"model"`
}
func (AnalyseBatch) JobOptions() queue.Options {
return queue.Options{
Tries: 3,
Backoff: []time.Duration{10 * time.Second, time.Minute},
Timeout: 2 * time.Minute,
}
}
// result is one evaluation's outcome: a sentiment, or why there is none.
type result struct {
evaluation models.Evaluation
sentiment analysis.Sentiment
failure *analysis.Failure
}
func (j AnalyseBatch) Handle(ctx context.Context) error {
batch := j.Batch
if batch.Status == models.Done || batch.Status == models.Failed {
return nil // a job that ran twice: the first run finished it
}
if err := model.Update(ctx, &batch, db.Values{"status": models.Running}); err != nil {
return err
}
laravel := db.Connection(ctx, "laravel")
evaluations, err := model.Query[models.Evaluation]().
With("answers").
OrderBy("id").
FindMany(laravel, batch.EvaluationIDs.V)
if err != nil {
return fmt.Errorf("loading the evaluations of batch %d: %w", batch.ID, err)
}
var failures []models.AnalysisBatchFailure
found := map[int64]bool{}
var todo []models.Evaluation
for _, e := range evaluations {
found[e.ID] = true
if len(e.Answers) == 0 {
failures = append(failures, models.AnalysisBatchFailure{EvaluationID: e.ID, Reason: "no answers"})
continue
}
todo = append(todo, e)
}
for _, id := range batch.EvaluationIDs.V {
if !found[id] {
failures = append(failures, models.AnalysisBatchFailure{EvaluationID: id, Reason: "no such evaluation"})
}
}
url := services.From(ctx).AnalysisURL
results, err := task.Map(ctx, todo, services.From(ctx).Concurrency, func(ctx context.Context, e models.Evaluation) (result, error) {
var comments []string
for _, a := range e.Answers {
if a.Comment != nil {
comments = append(comments, *a.Comment)
}
}
s, failure := analysis.Analyse(ctx, url, e.ID, comments)
return result{evaluation: e, sentiment: s, failure: failure}, nil
})
if err != nil {
return err
}
var analysed []result
for _, r := range results {
if r.failure != nil {
failures = append(failures, models.AnalysisBatchFailure{EvaluationID: r.evaluation.ID, Reason: r.failure.Reason, Retryable: r.failure.Retryable})
continue
}
analysed = append(analysed, r)
}
slices.SortFunc(failures, func(a, b models.AnalysisBatchFailure) int { return cmp.Compare(a.EvaluationID, b.EvaluationID) })
// Nothing analysed, and every failure temporary: the analysis API is down. The batch fails as a
// whole and nothing is saved, so the Laravel app can send it again later.
if len(analysed) == 0 && len(failures) > 0 && !slices.ContainsFunc(failures, func(f models.AnalysisBatchFailure) bool { return !f.Retryable }) {
reason := "the analysis API is unavailable: " + failures[0].Reason
slog.WarnContext(ctx, "batch failed", "batch", batch.ID, "reason", reason)
return model.Update(ctx, &batch, db.Values{"status": models.Failed, "error": reason})
}
// The results go to the Laravel app's database in one transaction...
err = db.Transaction(laravel, func(ctx context.Context) error {
for _, r := range analysed {
e := r.evaluation
_, err := model.Query[models.Evaluation]().WhereEq("id", e.ID).Update(ctx, db.Values{
"status": "analysed",
"average_tenths": averageTenths(e.Answers),
"positive": r.sentiment.Positive,
"negative": r.sentiment.Negative,
"neutral": r.sentiment.Neutral,
"analysed_at": time.Now(),
})
if err != nil {
return fmt.Errorf("saving evaluation %d: %w", e.ID, err)
}
}
return nil
})
if err != nil {
return err
}
// ...and the batch's outcome to this app's database, in another. A crash between the two runs the
// job again, which writes the same results again: harmless.
return db.Transaction(ctx, func(ctx context.Context) error {
for i := range failures {
failures[i].AnalysisBatchID = batch.ID
}
if len(failures) > 0 {
if err := model.CreateMany(ctx, failures); err != nil {
return fmt.Errorf("saving the failures of batch %d: %w", batch.ID, err)
}
}
if err := model.Update(ctx, &batch, db.Values{"status": models.Done, "analysed": len(analysed), "failed": len(failures)}); err != nil {
return err
}
slog.InfoContext(ctx, "batch done", "batch", batch.ID, "analysed", len(analysed), "failed", len(failures))
return nil
})
}
// averageTenths is the average score × 10, in whole numbers: [5, 4, 4] is 43.
func averageTenths(answers []models.Answer) int {
sum := 0
for _, a := range answers {
sum += a.Score
}
return sum * 10 / max(len(answers), 1)
}
The decisions are Week 5’s, line for line: an evaluation that does not exist or has no answers is a failure that is not retryable; when nothing was analysed and every failure was temporary, the API is down, the batch fails as a whole and nothing is saved.
Two databases means two transactions, not one: there is no transaction across two databases. So the order matters. The results go first, to the PHP app; the batch is marked done second. A crash between the two leaves the batch running, the job runs again (it has Tries: 3), and it writes the same results again, which is harmless. The other order could mark a batch done whose results were never saved.
The first if makes a job that runs twice harmless too. The resume-at-startup code of Week 5 is gone: when a worker is killed or its server crashes, the job it was running is still reserved in jobs, and another worker reclaims it about a minute later; the interrupted run counts as one of its 3 tries.
Step 5: the handlers
Store keeps Omar’s three cases. The batch is created and the job dispatched in one transaction: the job is pushed only when the batch is committed (the queues lesson), so a worker never looks for a batch that is not there yet, and a failed insert dispatches nothing.
package batches
import (
"context"
"fmt"
"net/http"
"slices"
"go.laravel.com/db"
"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 StoreBatch struct {
Reference string `json:"reference"`
EvaluationIDs []int64 `json:"evaluation_ids"`
}
func (f *StoreBatch) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.Reference, rule.Required, rule.Max(100)),
rule.Field(&f.EvaluationIDs, rule.Required, rule.Max(1000), rule.Each(rule.Min(1))),
)
}
// Store answers 202 for a new batch, 200 for a retry of the same one, and 409 for a reference that
// was already used for other evaluations.
func Store(r *web.Request) *web.Response {
form, err := r.Validate[StoreBatch]()
if err != nil {
return web.Fail(err)
}
ids := slices.Clone(form.EvaluationIDs)
slices.Sort(ids)
ids = slices.Compact(ids)
batch := models.AnalysisBatch{Reference: form.Reference, EvaluationIDs: db.NewJSON(ids), Total: len(ids)}
err = db.Transaction(r, func(ctx context.Context) error {
if err := model.Create(ctx, &batch); err != nil {
return err
}
_, err := queue.Dispatch(ctx, jobs.AnalyseBatch{Batch: batch})
return err
})
if db.IsUniqueViolation(err) {
existing, err := model.Query[models.AnalysisBatch]().With("failures").WhereEq("reference", form.Reference).First(r)
if err != nil {
return web.Fail(err)
}
if !slices.Equal(existing.EvaluationIDs.V, ids) {
return web.Abortf(http.StatusConflict, "The reference %q was already used for other evaluations.", form.Reference)
}
return web.JSON(existing)
}
if err != nil {
return web.Fail(err)
}
batch.Failures = []models.AnalysisBatchFailure{} // a new batch has none yet: [] in the JSON, as in Show
return web.JSON(batch).WithStatus(http.StatusAccepted).WithHeader("Location", fmt.Sprintf("/api/batches/%d", batch.ID))
}
func Show(r *web.Request) *web.Response {
batch, err := model.Query[models.AnalysisBatch]().With("failures").FromRoute(r, "batch")
if err != nil {
return web.Fail(err)
}
return web.JSON(batch)
}
A second POST with the same reference breaks the unique index. db.IsUniqueViolation(err) recognises it, the stored batch is read, and the sorted ids decide: the same ids are a retry and get 200, others get 409. Week 5 did the same with on conflict do nothing; here the database’s refusal is the signal.
Two routes behind the key, with the same paths as Week 5:
package routes
import (
"go.laravel.com/config"
"go.laravel.com/routing"
"app/apikeys"
"app/handlers/batches"
)
func API(route *routing.Router, cfg *config.Config) {
route.Middleware(apikeys.Required{}).Resource("batches", routing.Resource{
Store: batches.Store,
Show: batches.Show,
})
}
Method URI Name Handler
POST /api/batches batches.store batches.Store
⇂ apikeys.Required
GET|HEAD /api/batches/{batch} batches.show batches.Show
⇂ apikeys.Required
ANY /api/{fallback...} go.laravel.com.notFoundRun it: one click
HTTP/1.1 202 Accepted
Content-Length: 202
Content-Type: application/json
Location: /api/batches/1
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: f8558a2e9fd2cadb72084485de7fdecc
{"id":1,"reference":"dashboard-7f3a","status":"queued","total":4,"analysed":0,"failed":0,"error":null,"created_at":"2026-12-03T19:43:02.201889Z","updated_at":"2026-12-03T19:43:02.201889Z","failures":[]}4 s later:
{"id":1,"reference":"dashboard-7f3a","status":"done","total":4,"analysed":2,"failed":2,"error":null,"created_at":"2026-12-03T19:43:02.201889Z","updated_at":"2026-12-03T19:43:04.350525Z","failures":[{"evaluation_id":1044,"reason":"no answers","retryable":false},{"evaluation_id":9999,"reason":"no such evaluation","retryable":false}]}HTTP/1.1 200 OK
Content-Length: 333
Content-Type: application/json
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: 92fc0a09213ff3d5b2a07ea204788354
{"id":1,"reference":"dashboard-7f3a","status":"done","total":4,"analysed":2,"failed":2,"error":null,"created_at":"2026-12-03T19:43:02.201889Z","updated_at":"2026-12-03T19:43:04.350525Z","failures":[{"evaluation_id":1044,"reason":"no answers","retryable":false},{"evaluation_id":9999,"reason":"no such evaluation","retryable":false}]}HTTP/1.1 409 Conflict
Content-Length: 86
Content-Type: application/json
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: 5e732b3c5933fa5b9af7cee295aefb59
{"message":"The reference \"dashboard-7f3a\" was already used for other evaluations."}Server running at `http://127.0.0.1:8080`. Press Ctrl+C to stop.
POST 202 /api/batches 9.7ms
GET 200 /api/batches/1 2.2ms
POST 200 /api/batches 2.4ms
POST 409 /api/batches 3.4ms
Stopping. Waiting up to 20s for the work in progress.Processing jobs from `database:default`. Press Ctrl+C to stop.
time=2026-12-03T21:43:04.350+02:00 level=INFO msg="batch done" batch=1 analysed=2 failed=2 job=app/jobs.AnalyseBatch job_id=01a23d6e-823b-71f6-9e24-9a9c3890f5df
jobs.AnalyseBatch 122.9msThe same answers as Week 5: 202 with a Location and the batch queued, then done with two evaluations analysed and two failures with their reasons; the retry with the ids in another order gets 200 and the same batch; other ids get 409.
The worker’s log has the job and the batch done line, which carries the job’s name and ID because it was logged with slog.InfoContext(ctx, …). The results are in the PHP app’s evaluations rows 1042 and 1043, where the Laravel dashboard reads them.
HTTP/1.1 401 Unauthorized
Content-Length: 26
Content-Type: application/json
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: fc96c535f74f99c80268a083f3e62057
{"message":"Unauthorized"}HTTP/1.1 422 Unprocessable Entity
Content-Length: 195
Content-Type: application/json
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: 2ae9b8f2ad46ba35aa4338052ca4d93c
{"message":"The reference field is required. (and 1 more error)","errors":{"reference":["The reference field is required."],"evaluation_ids.1":["The evaluation_ids.1 field must be at least 1."]}}{"message":"db: no row in analysis_batches matched the query"}Server running at `http://127.0.0.1:8080`. Press Ctrl+C to stop.
POST 401 /api/batches 0.3ms
POST 422 /api/batches 0.7ms
GET 404 /api/batches/77 7.1ms
Stopping. Waiting up to 20s for the work in progress.Processing jobs from `database:default`. Press Ctrl+C to stop.No key: 401. A bad body: 422 with every field’s message, including the id at index 1. A batch that does not exist: 404.
When things go wrong
The analysis API is down
HTTP/1.1 202 Accepted
Content-Length: 202
Content-Type: application/json
Location: /api/batches/1
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: 47fe5410f2809d74482e7b47bc2c4bd7
{"id":1,"reference":"dashboard-9d22","status":"queued","total":2,"analysed":0,"failed":0,"error":null,"created_at":"2026-12-03T19:43:15.258027Z","updated_at":"2026-12-03T19:43:15.258027Z","failures":[]}4 s later:
{"id":1,"reference":"dashboard-9d22","status":"failed","total":2,"analysed":0,"failed":0,"error":"the analysis API is unavailable: httpclient: the request to http://127.0.0.1:8999/api/analyse failed: dial tcp 127.0.0.1:8999: connect: connection refused","created_at":"2026-12-03T19:43:15.258027Z","updated_at":"2026-12-03T19:43:17.889473Z","failures":[]}Server running at `http://127.0.0.1:8080`. Press Ctrl+C to stop.
POST 202 /api/batches 9.8ms
GET 200 /api/batches/1 2.6ms
Stopping. Waiting up to 20s for the work in progress.Processing jobs from `database:default`. Press Ctrl+C to stop.
time=2026-12-03T21:43:17.889+02:00 level=WARN msg="batch failed" batch=1 reason="the analysis API is unavailable: httpclient: the request to http://127.0.0.1:8999/api/analyse failed: dial tcp 127.0.0.1:8999: connect: connection refused" job=app/jobs.AnalyseBatch job_id=01a23d6e-b53b-7776-aead-acc728d96984
jobs.AnalyseBatch 621.9msEach call was tried three times, 200 ms and 400 ms apart, then the batch failed as a whole with the reason, and no evaluation was touched: Week 5’s outcome, without its retry loop.
A deploy during a batch
Ctrl-C, or the SIGTERM of a deploy, tells the worker to stop claiming jobs and to finish the ones in progress, as the server finishes its requests. A worker killed before it finishes loses nothing: its job is reclaimed and runs again, and the order of the two transactions makes running it again safe. The docs’ rule for the stop timeout of your process manager: more than twice the longest job’s Timeout, here 2 minutes, so more than 4.
The Laravel side
Nothing changes. The client class and the polling job of the Week 5 build day call the same paths with the same key and get the same JSON, which is the whole point of keeping the API. Only ANALYSIS_SERVICE_URL points at the new app.
What changes is on the Go side’s servers: two processes instead of one. ./app serves and ./app queue:work analyses; run both under your process manager, and scale them separately.
What you wrote, and what you did not
Week 5 (net/http) | Week 6 (Laravel Go) | |
|---|---|---|
| Lines of Go you wrote (without tests) | 790 | 467 in the files above, plus 10 in bootstrap/app.go and 1 in migrations.go |
| Processes in production | one | two: the server and the worker |
| A batch survives a crash because | resume at startup, written by hand | the job is a row until it has run |
| Dependencies | pgx, errgroup | go.laravel.com v0.1.1, a beta, and everything it requires |
| Someone else can change it if | they read your runner and shutdown code | they know Laravel |
Neither is the right answer everywhere. The checkpoint ends the course with when to pick which.
PracticeTwo databases; a retry for a failed batch
Read “Using more than one database” and “Transactions” in database.md, in the app’s bundled docs.
Exercise: POST /api/batches/{batch}/retry
A batch that failed because the analysis API was down can be sent again with the same reference. Add a retry handler package: for a failed batch, set it back to queued, clear error, and dispatch AnalyseBatch again, all in one db.Transaction; answer 202. Any other status is a 409. Try it with ANALYSIS_URL pointing at a closed port, then at the stand-in API, and check the batch ends done.
Remember
- Keep a Laravel Go app in its own database; reach the PHP app’s tables through a named connection.
- Two databases are two transactions: write the results first and mark the work done last, so a rerun is safe.
- A field with an initialism (
IDs,URL) needs adbtag.
Tomorrow: the Week 6 checkpoint: tests through the whole app, and when to choose net/http, Laravel Go or PHP Laravel.