How golang.org/x/sync/errgroup runs goroutines, returns the first error and cancels the rest, how SetLimit bounds concurrency, and how it compares to sync.WaitGroup in Go backend code.

Backend endpoints often need several independent things before they can respond, such as three database queries for a dashboard, prices from two suppliers or a batch of objects from storage, and doing them one after another adds up their latencies.
The errgroup package runs that work concurrently and handles the part plain goroutines leave to you: collecting the first error and stopping the rest.
errgroup.WithContext returns a group and a context derived from yours. Each g.Go call starts a goroutine, and g.Wait blocks until all of them return and then gives you the first error:
g, ctx := errgroup.WithContext(ctx)
var user User
var orders []Order
g.Go(func() error {
var err error
user, err = fetchUser(ctx, userID)
return err
})
g.Go(func() error {
var err error
orders, err = fetchOrders(ctx, userID)
return err
})
if err := g.Wait(); err != nil {
return nil, err
}
Each goroutine writes to its own variable, so no mutex is needed, and the results are safe to read after Wait returns. The source documents that the derived context is cancelled the first time a function returns a non-nil error or the first time Wait returns, whichever comes first, and since it uses context.WithCancelCause, context.Cause(ctx) reports the error that triggered it.
The group cannot stop a goroutine by itself, so cancellation reaches the work only when every call inside g.Go uses the derived ctx: database queries, HTTP requests built with http.NewRequestWithContext, and loops that check ctx.Err(). A goroutine that ignores ctx keeps running after another one fails, and Wait still waits for it.
Using the outer context by mistake is the most common bug, and shadowing it with g, ctx := errgroup.WithContext(ctx) as above makes that harder to do.
Starting one goroutine per item is fine for three queries and a problem for 5,000 objects, where it opens thousands of connections at once. SetLimit caps the active goroutines, and Go blocks until a slot is free:
g, ctx := errgroup.WithContext(ctx)
g.SetLimit(8)
results := make([]Price, len(skus))
for i, sku := range skus {
g.Go(func() error {
p, err := supplier.Price(ctx, sku)
if err != nil {
return fmt.Errorf("price %s: %w", sku, err)
}
results[i] = p
return nil
})
}
if err := g.Wait(); err != nil {
return nil, err
}
Writing to results[i] from different goroutines is safe because each index is written by exactly one goroutine, and the closures need no copies of i and sku because each loop iteration has its own variables from Go 1.22 on, as the Go 1.22 release notes describe. TryGo is the non-blocking variant, returning false when the limit is reached, which suits load shedding.
If the goroutines cannot fail, or each one logs and handles its own error, sync.WaitGroup is enough, and Go 1.25 added a WaitGroup.Go method that removes the Add/Done bookkeeping, per the Go 1.25 release notes. Reach for errgroup when one failure should fail the whole operation and stop the remaining work.
Two behaviors to keep in mind: a panic inside g.Go is not recovered by the group and crashes the process like any other goroutine panic, and a group is meant for a single task, so create a new one per request instead of reusing it.
Best fit: endpoints and jobs that combine several independent calls that can each fail, and batch work that needs a concurrency cap.
Encore is a backend framework with built-in infrastructure, and its endpoints are ordinary Go functions that receive a context.Context, so errgroup works in them unchanged. This dashboard endpoint runs three queries against the service's Postgres database concurrently:
Run in your terminal to get started locally.
// dashboard/dashboard.go
package dashboard
import (
"context"
"time"
"encore.dev/storage/sqldb"
"golang.org/x/sync/errgroup"
)
// migrations/1_create_orders.up.sql:
// CREATE TABLE orders (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
// customer_id text NOT NULL, total_cents bigint NOT NULL,
// created_at timestamptz NOT NULL DEFAULT now());
var db = sqldb.NewDatabase("dashboard", sqldb.DatabaseConfig{Migrations: "./migrations"})
type Summary struct {
OrdersToday int `json:"orders_today"`
RevenueToday int64 `json:"revenue_today_cents"`
ActiveCustomers int `json:"active_customers_30d"`
}
//encore:api public method=GET path=/dashboard/summary
func GetSummary(ctx context.Context) (*Summary, error) {
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
g, ctx := errgroup.WithContext(ctx)
var s Summary
g.Go(func() error {
return db.QueryRow(ctx, `
SELECT count(*) FROM orders WHERE created_at >= date_trunc('day', now())
`).Scan(&s.OrdersToday)
})
g.Go(func() error {
return db.QueryRow(ctx, `
SELECT coalesce(sum(total_cents), 0) FROM orders
WHERE created_at >= date_trunc('day', now())
`).Scan(&s.RevenueToday)
})
g.Go(func() error {
return db.QueryRow(ctx, `
SELECT count(DISTINCT customer_id) FROM orders
WHERE created_at >= now() - interval '30 days'
`).Scan(&s.ActiveCustomers)
})
if err := g.Wait(); err != nil {
return nil, err
}
return &s, nil
}
Each goroutine scans into a different field of s, so there is no shared write, and the three queries run on separate connections from the service's pool. encore run starts Postgres locally with the migration applied. In the local development dashboard, a trace for this endpoint should show the three queries as overlapping spans if they ran in parallel. The databases docs cover the query API and tracing explains what each span records.
Calls to other Encore services are plain Go function calls that take a context, as the API calls docs show, so a dashboard that aggregates orders, billing and users services uses the same g.Go pattern. An AI coding agent asked to speed up a slow endpoint can make the change and compare the before and after traces locally, without deploying anything, and a test can cover the error path by making one query fail.
Best fit: aggregate endpoints and background jobs that combine several independent queries or service calls.
g.Go. Cancellation never reaches that call.Wait's error. The first error is all you get, so wrap errors with enough context to tell which goroutine failed.errgroup.Group runs functions in goroutines and waits for all of them, like sync.WaitGroup, but each function returns an error and Wait returns the first non-nil one. With errgroup.WithContext, the first error also cancels a shared context so the other goroutines can stop early.
Call g.SetLimit(n) before starting work. After that, g.Go blocks until fewer than n goroutines are active, and g.TryGo returns false instead of blocking when the limit is reached.
Use errgroup when the goroutines can fail and you want the first error or cancellation of the rest. Use sync.WaitGroup, including its Go method added in Go 1.25, when the work cannot fail or each goroutine handles its own errors.
Create the group with errgroup.WithContext(ctx) from the endpoint's context, pass the derived context to each database query or service call inside g.Go, and return the error from g.Wait. Each concurrent query shows up as its own span in the local trace from encore run.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.