TExcelTAD
Home › Automation Scripting: Bash, Python & Go › Concurrent Checks in Go

Concurrent Checks in Go

Operations tools often do the same thing to many targets: check 200 health endpoints, query 30 clusters, scan 1,000 repositories. Doing them one after another is slow (the total is the sum of every latency); doing them all at once can overload the targets or your own machine. Go makes the middle ground easy: run checks in parallel, with a limit, an overall deadline, and results collected in a deterministic order.

Sequential vs parallel

Each test server below answers after a different delay. The sequential loop waits for each in turn; the parallel version starts one goroutine per target and waits for all of them with a sync.WaitGroup:

go · try it yourself
package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"sync"
	"time"
)

func slowServer(delay time.Duration) *httptest.Server {
	return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		time.Sleep(delay)
		fmt.Fprint(w, "ok")
	}))
}

func check(client *http.Client, url string) string {
	resp, err := client.Get(url)
	if err != nil {
		return "error"
	}
	resp.Body.Close()
	return resp.Status
}

func main() {
	var servers []*httptest.Server
	for _, ms := range []int{150, 100, 200, 120} {
		s := slowServer(time.Duration(ms) * time.Millisecond)
		defer s.Close()
		servers = append(servers, s)
	}
	client := &http.Client{Timeout: 2 * time.Second}

	start := time.Now()
	for _, s := range servers {
		check(client, s.URL)
	}
	seq := time.Since(start)

	start = time.Now()
	results := make([]string, len(servers)) // one slot per target: no locking needed
	var wg sync.WaitGroup
	for i, s := range servers {
		wg.Add(1)
		go func() {
			defer wg.Done()
			results[i] = check(client, s.URL)
		}()
	}
	wg.Wait()
	par := time.Since(start)

	fmt.Println("results:", results)
	fmt.Println("sequential took at least 570ms:", seq >= 570*time.Millisecond)
	fmt.Println("parallel took less than 400ms:", par < 400*time.Millisecond)
}
results: [200 OK 200 OK 200 OK 200 OK]
sequential took at least 570ms: true
parallel took less than 400ms: true

The sequential run takes the sum of the delays (570 ms), the parallel one roughly the slowest (200 ms). The program prints comparisons rather than the durations themselves, because timings differ on every run.

Two details make the parallel version correct:

  • Each goroutine writes only its own results[i], so no mutex is needed and the results stay in input order, whatever order the goroutines finish in.
  • Since Go 1.22, each loop iteration has its own i and s, so the closure captures the right values. (Older code passed them as arguments: go func(i int, s *httptest.Server) {…}(i, s).)

Limiting concurrency and setting a deadline

Five hundred simultaneous connections can trip rate limits or exhaust file descriptors. A buffered channel used as a semaphore caps how many checks run at once, and a context deadline bounds the whole run:

go · try it yourself
package main

import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"net/http/httptest"
	"sort"
	"sync"
	"sync/atomic"
	"time"
)

type Result struct {
	Name   string
	Status string
}

func main() {
	var inFlight, maxInFlight atomic.Int32
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		n := inFlight.Add(1)
		defer inFlight.Add(-1)
		for { // remember the highest concurrency the server saw
			m := maxInFlight.Load()
			if n <= m || maxInFlight.CompareAndSwap(m, n) {
				break
			}
		}
		switch r.URL.Path {
		case "/db-1":
			http.Error(w, "down", http.StatusServiceUnavailable)
		case "/cache-2":
			select { // hangs past the deadline
			case <-time.After(3 * time.Second):
			case <-r.Context().Done():
			}
		default:
			time.Sleep(50 * time.Millisecond)
		}
	}))
	defer srv.Close()

	targets := []string{"web-1", "web-2", "web-3", "db-1", "cache-1", "cache-2", "api-1", "api-2"}
	ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
	defer cancel()
	client := &http.Client{}

	sem := make(chan struct{}, 3) // at most 3 checks at a time
	results := make([]Result, len(targets))
	var wg sync.WaitGroup
	for i, name := range targets {
		wg.Add(1)
		go func() {
			defer wg.Done()
			sem <- struct{}{}        // acquire a slot (blocks while 3 are busy)
			defer func() { <-sem }() // release it
			results[i] = Result{name, probe(ctx, client, srv.URL+"/"+name)}
		}()
	}
	wg.Wait()

	sort.Slice(results, func(a, b int) bool { return results[a].Name < results[b].Name })
	failed := 0
	for _, r := range results {
		fmt.Printf("%-8s %s\n", r.Name, r.Status)
		if r.Status != "ok" {
			failed++
		}
	}
	fmt.Printf("%d of %d checks failed; max concurrent requests seen by the server: %d\n",
		failed, len(results), maxInFlight.Load())
}

func probe(ctx context.Context, client *http.Client, url string) string {
	req, _ := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
	resp, err := client.Do(req)
	switch {
	case errors.Is(err, context.DeadlineExceeded):
		return "timeout"
	case err != nil:
		return "error"
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return fmt.Sprintf("HTTP %d", resp.StatusCode)
	}
	return "ok"
}
api-1    ok
api-2    ok
cache-1  ok
cache-2  timeout
db-1     HTTP 503
web-1    ok
web-2    ok
web-3    ok
2 of 8 checks failed; max concurrent requests seen by the server: 3
  • The server never saw more than 3 requests at once: the semaphore works.
  • cache-2 hung, and the shared deadline turned it into timeout instead of stalling the whole run.
  • The results are sorted before printing, so the report is identical however the goroutines were scheduled.

The module golang.org/x/sync/errgroup packages the same pattern (g.SetLimit(3), g.Go(func() error {…}), g.Wait() returns the first error and cancels the rest); it is not in the standard library, so it is shown here rather than run:

go
g, ctx := errgroup.WithContext(ctx)
g.SetLimit(3)
for i, name := range targets {
	g.Go(func() error {
		results[i] = Result{name, probe(ctx, client, base+"/"+name)}
		return nil // return an error instead to cancel the remaining checks
	})
}
if err := g.Wait(); err != nil {
	return err
}

Test yourself

Why can each goroutine write results[i] without a mutex?

  1. Slices are thread-safe in Go
  2. Each goroutine writes a different element and the main goroutine reads only after wg.Wait()
  3. Goroutines run one at a time
  4. The compiler adds a lock

What does sem := make(chan struct{}, 3) do in the second example?

  1. Creates three goroutines
  2. Acts as a semaphore: sending blocks once 3 slots are taken, so at most 3 checks run at once
  3. Sets a 3-second timeout
  4. Retries 3 times

Why does the report sort results before printing?

  1. Sorting is required by fmt
  2. Goroutines finish in an unpredictable order; sorting makes the output deterministic
  3. To find the slowest check
  4. To remove duplicates