Go Playbook

Course › Week 4 · Concurrency and plugging into Laravel › Day 5 · lesson 26 of 42 · 25 min reading + 60–75 min practice

errgroup, worker pools and the race detector

Run many tasks with a limit, stop all of them on the first error, and catch data races with -race.

errgroupSetLimitworker pools-race

On this page
  1. errgroup
  2. A pool of workers
  3. The race detector
  4. Coming from PHP
  5. Practice
  6. Remember

A WaitGroup waits; it does not care whether the work failed. Real concurrent work returns errors, and when one task fails you usually want the first error, and the other tasks to stop. That is errgroup, from golang.org/x/sync, a module maintained by the Go team outside the standard library.

Today: errgroup, stopping the others, a limit on how many tasks run at once, a pool of long-lived workers, and the race detector that finds the bug of the goroutines lesson.

errgroup

1. The first error

g.Go(func() error { … }) starts a task; g.Wait() waits for all of them and returns the first non-nil error. Each task writes its own slot of the results.

main.go
package main

import (
	"context"
	"encoding/json/v2"
	"fmt"
	"net/http"
	"os"
	"time"

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

type Booking struct {
	ID    int    `json:"id"`
	Guest string `json:"guest"`
}

func fetchBooking(ctx context.Context, client *http.Client, id int) (Booking, error) {
	url := fmt.Sprintf("http://127.0.0.1:8000/api/bookings/%d", id)
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
	if err != nil {
		return Booking{}, err
	}
	resp, err := client.Do(req)
	if err != nil {
		return Booking{}, fmt.Errorf("fetching booking %d: %w", id, err)
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return Booking{}, fmt.Errorf("fetching booking %d: status %d", id, resp.StatusCode)
	}
	var body struct {
		Data Booking `json:"data"`
	}
	if err := json.UnmarshalRead(resp.Body, &body); err != nil {
		return Booking{}, fmt.Errorf("decoding booking %d: %w", id, err)
	}
	return body.Data, nil
}

func main() {
	client := &http.Client{Timeout: 5 * time.Second}
	ctx := context.Background()
	ids := []int{5521, 5522, 9999, 5524}

	bookings := make([]Booking, len(ids))
	var g errgroup.Group
	for i, id := range ids {
		g.Go(func() error {
			b, err := fetchBooking(ctx, client, id)
			if err != nil {
				return err
			}
			bookings[i] = b
			return nil
		})
	}
	if err := g.Wait(); err != nil {
		fmt.Fprintln(os.Stderr, "loading the bookings:", err)
		os.Exit(1)
	}
	fmt.Println(bookings)
}
$ go run .
loading the bookings: fetching booking 9999: status 404
exit status 1

go get golang.org/x/sync adds the module. The golang.org/x/… modules are the Go team’s, with the same care as the standard library and a faster release cycle.

One booking does not exist, so the whole load fails with that error, like Promise.all in JavaScript. When one failure must not stop the rest, do not return it: record it in the task’s own slot and return nil, as the build day does.

2. WithContext stops the others

errgroup.WithContext(ctx) returns a group and a context that is cancelled as soon as one task fails. Pass that context to every task, and the others stop instead of finishing work nobody will use.

main.go
package main

import (
	"context"
	"fmt"
	"net/http"
	"os"
	"time"

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

func get(ctx context.Context, client *http.Client, path string) error {
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://127.0.0.1:8000"+path, nil)
	if err != nil {
		return err
	}
	resp, err := client.Do(req)
	if err != nil {
		return fmt.Errorf("GET %s: %w", path, err)
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("GET %s: status %d", path, resp.StatusCode)
	}
	return nil
}

func main() {
	client := &http.Client{Timeout: 10 * time.Second}
	start := time.Now()

	g, ctx := errgroup.WithContext(context.Background())
	for _, path := range []string{"/api/slow", "/api/slow", "/api/bookings/9999"} {
		g.Go(func() error {
			err := get(ctx, client, path)
			if err != nil && ctx.Err() != nil {
				fmt.Println(path, "stopped early:", err)
			}
			return err
		})
	}
	err := g.Wait()
	fmt.Println("took", time.Since(start).Round(10*time.Millisecond))
	if err != nil {
		fmt.Fprintln(os.Stderr, "error:", err)
		os.Exit(1)
	}
}
$ go run .
/api/slow stopped early: GET /api/slow: Get "http://127.0.0.1:8000/api/slow": GET /api/bookings/9999: status 404
/api/slow stopped early: GET /api/slow: Get "http://127.0.0.1:8000/api/slow": GET /api/bookings/9999: status 404
took 10ms
error: GET /api/bookings/9999: status 404
exit status 1

The 404 came back at once and cancelled the context, so both 3-second calls stopped too, and the whole group took a few milliseconds instead of 3 seconds. ctx.Err() is non-nil once the context has ended, which is how a task tells “I was stopped” from “I failed”.

errgroup cancels the context with the first error as its cause, so the stopped calls report the 404 that stopped them instead of a bare “context canceled”: every line says why. Wait returns that first error.

3. SetLimit: at most n at a time

Starting one goroutine per item is fine for 10 items and dangerous for 10,000: the API you call gets 10,000 requests at once and starts answering 429. g.SetLimit(n) makes g.Go wait while n tasks are running.

Here 9 calls to the analysis API, which takes about 100 ms per call, with at most 3 at a time:

main.go
package main

import (
	"bytes"
	"context"
	"encoding/json/v2"
	"fmt"
	"net/http"
	"os"
	"time"

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

type Analysis struct {
	EvaluationID int `json:"evaluation_id"`
	Positive     int `json:"positive"`
	Negative     int `json:"negative"`
}

func analyse(ctx context.Context, client *http.Client, evaluationID int, comments []string) (Analysis, error) {
	payload, err := json.Marshal(map[string]any{"evaluation_id": evaluationID, "comments": comments})
	if err != nil {
		return Analysis{}, err
	}
	req, err := http.NewRequestWithContext(ctx, http.MethodPost, "http://127.0.0.1:8000/api/analyse", bytes.NewReader(payload))
	if err != nil {
		return Analysis{}, err
	}
	req.Header.Set("Content-Type", "application/json")
	resp, err := client.Do(req)
	if err != nil {
		return Analysis{}, fmt.Errorf("analysing %d: %w", evaluationID, err)
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return Analysis{}, fmt.Errorf("analysing %d: status %d", evaluationID, resp.StatusCode)
	}
	var result Analysis
	if err := json.UnmarshalRead(resp.Body, &result); err != nil {
		return Analysis{}, fmt.Errorf("decoding the analysis of %d: %w", evaluationID, err)
	}
	return result, nil
}

func main() {
	client := &http.Client{Timeout: 5 * time.Second}
	ids := []int{1042, 1043, 1044, 1045, 1046, 1047, 1048, 1049, 1050}
	start := time.Now()

	results := make([]Analysis, len(ids))
	g, ctx := errgroup.WithContext(context.Background())
	g.SetLimit(3)
	for i, id := range ids {
		g.Go(func() error {
			r, err := analyse(ctx, client, id, []string{"Clear explanations", "Too fast"})
			if err != nil {
				return err
			}
			results[i] = r
			return nil
		})
	}
	if err := g.Wait(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	fmt.Println(len(results), "analysed in", time.Since(start).Round(100*time.Millisecond))
	fmt.Printf("%+v\n", results[0])
}
$ go run .
9 analysed in 300ms
{EvaluationID:1042 Positive:1 Negative:1}

9 calls, 3 at a time, about 100 ms each: three rounds, about 300 ms, instead of 900 one after another or 100 all at once. The limit is the knob you tune for the service on the other end, usually from an environment variable.

map[string]any is a quick way to build a small JSON object with values of different types. It is Laravel’s Http::pool with a concurrency cap, which Http::pool does not have.

A pool of workers

4. Workers reading from a channel

SetLimit is right when the list of tasks is known. When work arrives as a stream (rows from a database cursor, lines of a file), start a fixed number of workers that each read from one jobs channel (the channels lesson) until it is closed.

main.go
package main

import (
	"fmt"
	"strings"
	"sync"
)

type Result struct {
	Line  int
	Words int
}

func main() {
	comments := []string{"Clear explanations, thank you", "Too fast", "The homework was useful", "Great teacher", "Confusing"}

	jobs := make(chan int)
	results := make(chan Result)

	var workers sync.WaitGroup
	for range 2 {
		workers.Go(func() {
			for line := range jobs {
				results <- Result{Line: line, Words: len(strings.Fields(comments[line]))}
			}
		})
	}

	go func() {
		for line := range comments {
			jobs <- line
		}
		close(jobs)
	}()
	go func() {
		workers.Wait()
		close(results)
	}()

	total := 0
	for r := range results {
		total += r.Words
	}
	fmt.Println("words:", total)
}
$ go run .
words: 13

Three pieces: a goroutine feeds the jobs and closes the channel; two workers read jobs until it is closed; a third goroutine waits for the workers and then closes results, which ends the range in main. Each channel is closed by the only goroutine that sends on it, after its last send.

for line := range comments over a slice with one variable gives the index. It is a Laravel queue with two workers, inside one process.

The race detector

5. go test -race

The counter of the goroutines lesson lost additions without any warning. Build or test with -race, and Go adds checks to every memory access and reports two goroutines touching the same variable without synchronisation, with both places in the code.

Here a Stats type counts processed rows, and its test uses it from 4 goroutines:

stats/stats_test.gonew file
package stats

import (
	"sync"
	"testing"
)

func TestStatsFromManyGoroutines(t *testing.T) {
	var s Stats

	var wg sync.WaitGroup
	for range 4 {
		wg.Go(func() {
			for range 1000 {
				s.Add()
			}
		})
	}
	wg.Wait()

	if got := s.Processed(); got != 4000 {
		t.Errorf("Processed() = %d, want 4000", got)
	}
}
$ go test -race
==================
WARNING: DATA RACE
Read at 0x00c000114168 by goroutine 10:
  stats.(*Stats).Add()
      /tmp/go-playbook/stats/stats.go:9 +0x3a
  stats.TestStatsFromManyGoroutines.func1()
      /tmp/go-playbook/stats/stats_test.go:15 +0x35

Previous write at 0x00c000114168 by goroutine 11:
  stats.(*Stats).Add()
      /tmp/go-playbook/stats/stats.go:9 +0x4c
  stats.TestStatsFromManyGoroutines.func1()
      /tmp/go-playbook/stats/stats_test.go:15 +0x35

Goroutine 10 (running) created at:
  sync.(*WaitGroup).Go()
      /usr/local/go/src/sync/waitgroup.go:238 +0x72
  testing.tRunner()
      /usr/local/go/src/testing/testing.go:2195 +0x21c
  testing.(*T).Run.gowrap1()
      /usr/local/go/src/testing/testing.go:2260 +0x38

Goroutine 11 (running) created at:
  sync.(*WaitGroup).Go()
      /usr/local/go/src/sync/waitgroup.go:238 +0x72
  testing.tRunner()
      /usr/local/go/src/testing/testing.go:2195 +0x21c
  testing.(*T).Run.gowrap1()
      /usr/local/go/src/testing/testing.go:2260 +0x38
==================
==================
WARNING: DATA RACE
Write at 0x00c000114168 by goroutine 10:
  stats.(*Stats).Add()
      /tmp/go-playbook/stats/stats.go:9 +0x4c
  stats.TestStatsFromManyGoroutines.func1()
      /tmp/go-playbook/stats/stats_test.go:15 +0x35

Previous write at 0x00c000114168 by goroutine 11:
  stats.(*Stats).Add()
      /tmp/go-playbook/stats/stats.go:9 +0x4c
  stats.TestStatsFromManyGoroutines.func1()
      /tmp/go-playbook/stats/stats_test.go:15 +0x35

Goroutine 10 (running) created at:
  sync.(*WaitGroup).Go()
      /usr/local/go/src/sync/waitgroup.go:238 +0x72
  testing.tRunner()
      /usr/local/go/src/testing/testing.go:2195 +0x21c
  testing.(*T).Run.gowrap1()
      /usr/local/go/src/testing/testing.go:2260 +0x38

Goroutine 11 (running) created at:
  sync.(*WaitGroup).Go()
      /usr/local/go/src/sync/waitgroup.go:238 +0x72
  testing.tRunner()
      /usr/local/go/src/testing/testing.go:2195 +0x21c
  testing.(*T).Run.gowrap1()
      /usr/local/go/src/testing/testing.go:2260 +0x38
==================
--- FAIL: TestStatsFromManyGoroutines (0.00s)
    testing.go:1867: race detected during execution of test
FAIL
exit status 1
FAIL	stats	0.012s

A “Read at” and a “Previous write at” in two different goroutines, each with its line: stats.go:9, the s.processed++. The test fails because a race was found, even when the count happened to come out right. The fix is the sync.Mutex from the goroutines lesson inside Stats.

The race detector only sees races that happen while it runs, so run your tests with -race in CI, always. It makes programs several times slower, which is why it is not on by default. It needs cgo, which is on by default on macOS and Linux with a C compiler installed.

Coming from PHP

AnalyseEvaluations.php
<?php
$responses = Http::pool(fn (Pool $pool) => array_map(
    fn ($id) => $pool->post('http://127.0.0.1:8000/api/analyse', ['evaluation_id' => $id]),
    $ids,
));                                     // all at once: no limit, no early stop

foreach ($responses as $response) {
    $response->throw();                 // the first failure, after everything finished
}

Http::pool sends every request at once and waits for all of them; a failure shows up only after the slowest one. errgroup with WithContext and SetLimit adds what a batch job needs: a cap on load, and stopping as soon as the batch is lost.

PHP has no data races between requests because each has its own memory. A Go service has one memory for all requests, so the race detector is as important as the test suite.

PracticeLearn Go with Tests: Sync and Context

Do Sync (a counter made safe with a mutex, tested with -race) and Context in Learn Go with Tests.

Exercise: a limit from the environment

Take section 3 and read the limit from ANALYSIS_CONCURRENCY: a whole number from 1 to 32, default 4, anything else a usage error with exit code 2. Run it with 1, 3 and 9 and write down the times. Then fix Stats in section 5 and run its test with -race until it passes.

Remember

  • Use errgroup for tasks that can fail; WithContext stops the others, SetLimit protects the service you call.
  • A failure that must not stop the batch is recorded in its slot, not returned.
  • Run tests with -race in CI, always.

Tomorrow is the build day: a Go worker that Laravel runs, which loads a batch from Postgres, analyses it concurrently and saves it in one transaction.