Nov 23, 20265 min read

Go Context Timeouts for Backend APIs

How context.WithTimeout and deadlines work in Go services, where to set them for database queries and outbound HTTP calls, how to tell a timeout from a cancellation, and how to return the right error to the caller.

Illustration for Go Context Timeouts for Backend APIs

A Go service without timeouts behaves well until one dependency gets slow, and then every request that touches it waits, connections pile up and the service stops answering anything, including requests that never needed the slow dependency.

Go's answer is a deadline carried in context.Context, which works only if you set it in the right place and pass it all the way down.

At a glance

ToolWhat it doesTypical use
context.WithTimeout(ctx, d)Cancels after a durationOutbound HTTP calls, queries
context.WithDeadline(ctx, t)Cancels at a point in timeSharing one deadline across steps
context.WithTimeoutCause(ctx, d, err)Same, with a custom causeTelling which timeout fired
context.Cause(ctx)Returns the cause of cancellationLogging and error mapping
http.Client.TimeoutCaps a whole HTTP exchangeA safety net per client
http.Server timeoutsCap reading and writing a requestProtecting the server itself

How WithTimeout works

context.WithTimeout returns a child context that is cancelled when the duration passes, when you call cancel, or when the parent is cancelled, whichever happens first. The context package documentation says to call cancel as soon as the work completes, and go vet flags a discarded cancel because the timer otherwise lives until the deadline:

ctx, cancel := context.WithTimeout(ctx, 2*time.Second) defer cancel() req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil { return err } resp, err := http.DefaultClient.Do(req) if errors.Is(err, context.DeadlineExceeded) { // the supplier took longer than 2s }

A child context can only shorten a deadline, so wrapping a context that expires in 500 ms with a 2-second timeout still expires in 500 ms, which is what you want when the caller's own budget is smaller.

The timeout only applies to calls that take ctx

A deadline does nothing unless the code doing the waiting watches it. Database drivers such as pgx abort the query and cancel it on the server, http.NewRequestWithContext aborts the request, and select statements need a case <-ctx.Done() branch. A call made with context.Background() deep in a helper, or an http.Get without a context, ignores every timeout above it.

Timeout or cancellation?

Both end the work, but context.DeadlineExceeded is your own timeout firing, usually a slow dependency, and is worth an alert if it happens often. context.Canceled usually means the client disconnected or a sibling goroutine failed, and it is normally not an error on your side. The errors.Is check works on wrapped errors, so check both before deciding what to log.

WithTimeoutCause, added in Go 1.21, attaches a custom error that context.Cause returns, which makes logs say "supplier quote timeout" instead of a bare deadline message when several timeouts are nested.

Budgeting timeouts across a request

Set the outer limit at the edge and give each dependency a smaller one inside it. A request with a 5-second budget might allow 2 seconds for a supplier call and 1 second for each query, so a slow supplier fails fast and still leaves time to return a useful error or a cached value. Retries need to fit inside the same budget, so check ctx.Err() before each attempt instead of retrying past the deadline.

For HTTP clients, keep http.Client.Timeout as a ceiling for any request made with that client and use the context for per-call limits. For servers, the net/http Server fields such as ReadHeaderTimeout protect against clients that open connections and send headers slowly.

Best fit: a deadline on every outbound call, set from the request's context, with an outer budget at the endpoint.

Timeouts in an Encore endpoint

Encore

Encore is a backend framework with built-in infrastructure, and its Go endpoints receive a context.Context like any handler, so the same timeout pattern applies. This shipping service asks a carrier API for a rate with a 2-second limit and returns a typed error the caller can act on:

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

// shipping/rates.go package shipping import ( "context" "encoding/json" "errors" "fmt" "net/http" "net/url" "time" "encore.dev/beta/errs" "encore.dev/rlog" ) var secrets struct { CarrierAPIKey string } var errCarrierTimeout = errors.New("carrier rate request timed out") type RateParams struct { FromZip string `query:"from"` ToZip string `query:"to"` WeightKg int `query:"weight_kg"` } type Rate struct { AmountCents int64 `json:"amount_cents"` Service string `json:"service"` } //encore:api public method=GET path=/rates func GetRate(ctx context.Context, p *RateParams) (*Rate, error) { ctx, cancel := context.WithTimeoutCause(ctx, 2*time.Second, errCarrierTimeout) defer cancel() q := url.Values{} q.Set("from", p.FromZip) q.Set("to", p.ToZip) q.Set("weight_kg", fmt.Sprint(p.WeightKg)) req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.carrier.example/v1/rates?"+q.Encode(), nil) if err != nil { return nil, err } req.Header.Set("Authorization", "Bearer "+secrets.CarrierAPIKey) resp, err := http.DefaultClient.Do(req) if errors.Is(err, context.DeadlineExceeded) { rlog.Warn("carrier timeout", "cause", context.Cause(ctx)) return nil, &errs.Error{Code: errs.DeadlineExceeded, Message: "carrier did not respond in time"} } if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, &errs.Error{Code: errs.Unavailable, Message: "carrier returned " + resp.Status} } var r Rate if err := json.NewDecoder(resp.Body).Decode(&r); err != nil { return nil, err } return &r, nil }

The carrier key is an Encore secret, set per environment with encore secret set and kept out of the repository, so an AI coding agent working in the codebase never sees the value. errs.DeadlineExceeded maps to an HTTP 504 according to the API errors docs, which tells clients the request may succeed on retry, and structured logging with rlog records the cause next to the request's trace.

encore run traces the outbound HTTP call, so you can point the URL at a slow local stub and watch the span end at two seconds. A test can do the same against an httptest.Server that sleeps, which keeps the timeout from being removed by a later refactor.

Best fit: endpoints that depend on third-party APIs or slow queries and need to fail fast with a clear error.

Frequently asked questions

How do I set a timeout on a function call in Go?

Derive a context with ctx, cancel := context.WithTimeout(ctx, 2*time.Second), defer cancel(), and pass ctx to the call. The call has to accept and respect a context, which database drivers and http.NewRequestWithContext do, otherwise the timeout has no effect.

Why do I need to call cancel after context.WithTimeout?

cancel releases the timer and the resources tied to the derived context as soon as the work finishes. Without it they stay alive until the deadline passes, and go vet reports the missing call as a possible context leak.

How do I check if a Go context timed out?

Check errors.Is(err, context.DeadlineExceeded) for a timeout and errors.Is(err, context.Canceled) for an explicit cancellation, such as a client that went away. ctx.Err() returns the same values, and context.Cause(ctx) returns a custom cause if you set one.

How do I add a timeout to an outbound call in an Encore endpoint?

Wrap the endpoint's context with context.WithTimeout before the call, use http.NewRequestWithContext with that context, and return an errs.Error with code DeadlineExceeded when errors.Is(err, context.DeadlineExceeded). The local trace from encore run shows how long the call took before it was cut off.

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.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders