Course › Week 4 · Concurrency and plugging into Laravel › Day 7 · lesson 28 of 42 · 35 min reading + 1–2 h practice
Week 4 checkpoint
Kill the database mid-run: Laravel gets a clear error and no half-written batch.
On this page
Five problems, all of them the kind a worker meets in production. Problem 1 is the one this week’s design exists for: the database fails in the middle of saving a batch. It runs against the real Postgres, where a trigger makes the third update fail as a full disk would.
As before: decide what is wrong and why before you open the answer.
1. The database fails halfway through a save
Three results to save. The third update fails:
package main
import (
"context"
"database/sql"
"fmt"
"os"
"time"
_ "github.com/jackc/pgx/v5/stdlib"
)
type Result struct {
ID int64
AverageTenths int
}
// save writes the results one update at a time.
func save(ctx context.Context, db *sql.DB, results []Result) error {
for _, r := range results {
_, err := db.ExecContext(ctx, "update evaluations set status = 'analysed', average_tenths = $2 where id = $1", r.ID, r.AverageTenths)
if err != nil {
return fmt.Errorf("saving evaluation %d: %w", r.ID, err)
}
}
return nil
}
// printStatuses shows what a Laravel dashboard would show afterwards.
func printStatuses(ctx context.Context, db *sql.DB) error {
rows, err := db.QueryContext(ctx, "select id, status from evaluations order by id")
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
var id int64
var status string
if err := rows.Scan(&id, &status); err != nil {
return err
}
fmt.Printf(" #%d: %s\n", id, status)
}
return rows.Err()
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
db, err := sql.Open("pgx", os.Getenv("DATABASE_URL"))
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
defer db.Close()
results := []Result{{1042, 43}, {1043, 30}, {1045, 50}}
if err := save(ctx, db, results); err != nil {
fmt.Println("save failed:", err)
}
if err := printStatuses(ctx, db); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
save failed: saving evaluation 1045: ERROR: could not extend file: No space left on device (simulated for evaluation 1045) (SQLSTATE P0001)
#1042: analysed
#1043: analysed
#1045: pendingShow the solution
One sentence: each update was committed on its own, so the first two stayed saved when the third failed: the batch is half-written, and retrying it would analyse 1042 and 1043 a second time.
The fix: one transaction around the whole batch, exactly the worker’s save. The failure rolls back the first two updates, and the batch is either entirely saved or entirely retryable.
package main
import (
"context"
"database/sql"
"fmt"
"os"
"time"
_ "github.com/jackc/pgx/v5/stdlib"
)
type Result struct {
ID int64
AverageTenths int
}
// save writes every result in one transaction: all of them, or none.
func save(ctx context.Context, db *sql.DB, results []Result) 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 where id = $1", r.ID, r.AverageTenths)
if err != nil {
return fmt.Errorf("saving evaluation %d: %w", r.ID, err)
}
}
return tx.Commit()
}
// printStatuses shows what a Laravel dashboard would show afterwards.
func printStatuses(ctx context.Context, db *sql.DB) error {
rows, err := db.QueryContext(ctx, "select id, status from evaluations order by id")
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
var id int64
var status string
if err := rows.Scan(&id, &status); err != nil {
return err
}
fmt.Printf(" #%d: %s\n", id, status)
}
return rows.Err()
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
db, err := sql.Open("pgx", os.Getenv("DATABASE_URL"))
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
defer db.Close()
results := []Result{{1042, 43}, {1043, 30}, {1045, 50}}
if err := save(ctx, db, results); err != nil {
fmt.Println("save failed:", err)
}
if err := printStatuses(ctx, db); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
save failed: saving evaluation 1045: ERROR: could not extend file: No space left on device (simulated for evaluation 1045) (SQLSTATE P0001)
#1042: pending
#1043: pending
#1045: pending2. Results that never arrive
Three evaluations analysed at the same time, then printed:
package main
import (
"fmt"
"time"
)
func analyse(id int) int {
time.Sleep(100 * time.Millisecond) // the analysis API takes about 100 ms
return id % 7
}
func main() {
ids := []int{1042, 1043, 1045}
scores := make([]int, len(ids))
for i, id := range ids {
go func() {
scores[i] = analyse(id)
}()
}
fmt.Println("scores:", scores)
}
scores: [0 0 0]Show the solution
One sentence: nothing waited for the goroutines, so main printed the slice while all three were still waiting for the API, and the program ended before they finished.
The fix: a sync.WaitGroup and Wait before the results are read (the goroutines lesson). go test -race on this code would also have reported the read in main racing with the writes.
package main
import (
"fmt"
"sync"
"time"
)
func analyse(id int) int {
time.Sleep(100 * time.Millisecond) // the analysis API takes about 100 ms
return id % 7
}
func main() {
ids := []int{1042, 1043, 1045}
scores := make([]int, len(ids))
var wg sync.WaitGroup
for i, id := range ids {
wg.Go(func() {
scores[i] = analyse(id)
})
}
wg.Wait()
fmt.Println("scores:", scores)
}
scores: [6 0 2]3. A 503 saved as zero comments
The analysis API is overloaded and answers 503 Service Unavailable. The worker carries on:
package main
import (
"encoding/json/v2"
"fmt"
"net/http"
"os"
)
type Sentiment struct {
Positive int `json:"positive"`
Negative int `json:"negative"`
}
func main() {
resp, err := http.Get("http://127.0.0.1:8000/api/unstable?key=checkpoint-4")
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
defer resp.Body.Close()
var s Sentiment
if err := json.UnmarshalRead(resp.Body, &s); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Printf("saving %+v\n", s)
}
saving {Positive:0 Negative:0}Show the solution
One sentence: a 503 is a successful HTTP call, and its body {"message": …} decoded into a Sentiment without an error, as zero positive and zero negative comments, which the worker would have saved as a real result.
The fix: check the status before decoding (the context lesson), and treat 429 and 5xx as retryable, as the worker’s try does. Run against the same overloaded API, the program now says so and exits 1, and nothing is saved.
package main
import (
"encoding/json/v2"
"fmt"
"net/http"
"os"
)
type Sentiment struct {
Positive int `json:"positive"`
Negative int `json:"negative"`
}
func main() {
resp, err := http.Get("http://127.0.0.1:8000/api/unstable?key=checkpoint-4-fixed")
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= 500 {
fmt.Fprintln(os.Stderr, "the analysis API answered", resp.Status, "- retry later")
os.Exit(1)
}
if resp.StatusCode != http.StatusOK {
fmt.Fprintln(os.Stderr, "the analysis API answered", resp.Status)
os.Exit(1)
}
var s Sentiment
if err := json.UnmarshalRead(resp.Body, &s); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Printf("saving %+v\n", s)
}
the analysis API answered 503 Service Unavailable - retry later
exit status 14. One friendly line too many
Someone added a progress message to the worker’s run. The Go side works:
package main
import (
"encoding/json/v2"
"fmt"
"os"
)
type Output struct {
Analysed []int64 `json:"analysed"`
}
func main() {
fmt.Println("analysing 2 evaluations...")
if err := json.MarshalWrite(os.Stdout, Output{Analysed: []int64{1042, 1043}}); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Println()
}
analysing 2 evaluations...
{"analysed":[1042,1043]}Laravel’s json_decode($result->output(), flags: JSON_THROW_ON_ERROR) now throws Syntax error on every run, and the runner reports WorkerFailed: the job retries five times and fails, although every batch was saved.
Show the solution
One sentence: stdout is the worker’s result channel, and a progress line on it turns the JSON document into text that is not JSON.
The fix: every message goes to stderr, through the logger (the slog lesson); stdout carries the result and nothing else. The output above now holds only the JSON line, and the message is on stderr.
package main
import (
"encoding/json/v2"
"fmt"
"log/slog"
"os"
)
type Output struct {
Analysed []int64 `json:"analysed"`
}
func main() {
logger := slog.New(slog.NewTextHandler(os.Stderr, nil))
logger.Info("analysing", "evaluations", 2)
if err := json.MarshalWrite(os.Stdout, Output{Analysed: []int64{1042, 1043}}); err != nil {
logger.Error("writing the result", "err", err)
os.Exit(1)
}
fmt.Println()
}
time=2026-12-03T18:57:42.959+02:00 level=INFO msg=analysing evaluations=2
{"analysed":[1042,1043]}The page mixes the two streams to show them in order. Run it as ./hello 2>/dev/null and only the JSON is left.
5. A deadline nobody passed on
The run has half a second left, and gives itself a deadline:
package main
import (
"context"
"fmt"
"net/http"
"os"
"time"
)
func fetch(ctx context.Context, url string) (int, error) {
resp, err := http.Get(url)
if err != nil {
return 0, err
}
defer resp.Body.Close()
return resp.StatusCode, nil
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
defer cancel()
start := time.Now()
status, err := fetch(ctx, "http://127.0.0.1:8000/api/slow")
fmt.Println("took", time.Since(start).Round(100*time.Millisecond))
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Println("status:", status)
}
took 3s
status: 200Show the solution
One sentence: fetch takes the context and never uses it, so http.Get ran without a deadline and waited the full 3 seconds.
The fix: attach the context to the request with http.NewRequestWithContext (the context lesson). A ctx parameter that is never passed on is the most common context bug, because it looks right in the signature.
package main
import (
"context"
"fmt"
"net/http"
"os"
"time"
)
func fetch(ctx context.Context, url string) (int, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return 0, err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return 0, err
}
defer resp.Body.Close()
return resp.StatusCode, nil
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
defer cancel()
start := time.Now()
status, err := fetch(ctx, "http://127.0.0.1:8000/api/slow")
fmt.Println("took", time.Since(start).Round(100*time.Millisecond))
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Println("status:", status)
}
took 500ms
Get "http://127.0.0.1:8000/api/slow": context deadline exceeded
exit status 1The worker exit check
Before Week 5, your worker from the build day must pass every line of this table.
| Check | How |
|---|---|
| A database failure during the save leaves nothing written | Add the trigger from problem 1 to a scratch database, run a batch, check the statuses. |
| Each of the four outcomes has its exit code: 0, 3, 1, 2 | The runs of the build day, against your own Postgres. |
| Only JSON on stdout | echo '{"evaluation_ids":[1042]}' | ./worker 2>/dev/null | jq . |
| Every HTTP and database call gets the run’s context | Search for http.Get, db.Query( and db.Exec( without Context: there should be none. |
No goroutine is left unwaited, and go test -race ./... passes | Run it. |
| The API being down saves nothing and exits 1 | Run with a wrong ANALYSIS_URL port. |
gofmt -l ., go vet ./... and staticcheck ./... print nothing | Run all three. |
What PHP would have done
The same five mistakes in a Laravel job:
| Mistake | PHP | Go |
|---|---|---|
| 1. A batch saved without a transaction | The same bug; DB::transaction is the fix | The same bug; BeginTx is the fix |
| 2. Work started and never waited for | Not possible inside one request: everything waits | Goroutines that main outruns |
| 3. A 503 used as data | Http::post() without ->throw(): the same bug | No status check: the same bug |
| 4. A message mixed into the result | echo in a command whose output is parsed: the same bug | fmt.Println on stdout |
| 5. A deadline that is not passed on | No equivalent: each Guzzle call has its own timeout | A ctx that never reaches the request |
Remember
- A
ctxparameter that is never passed on is a deadline nobody enforces.
Week 5 starts the HTTP service: routing and handlers with net/http, and the patterns Go 1.22 added to ServeMux.