Nov 23, 20267 min read

Go HTTP Client Timeouts for Backend Services

Why Go's default HTTP client never times out, what http.Client.Timeout covers, the Transport timeouts for dialing, TLS and response headers, per-request deadlines with context, connection reuse and MaxIdleConnsPerHost, detecting timeout errors, and calling a third-party API from an Encore service.

Illustration for Go HTTP Client Timeouts for Backend Services

Go's net/http client is good enough that most services never wrap it, which is how a backend ends up with http.Get calls that can hang forever. http.DefaultClient has no timeout, so a payment provider that accepts the connection and stalls holds the goroutine and, eventually, your connection pool.

This guide covers the timeouts that exist, which ones to set and how to detect them.

Which timeouts does a Go HTTP client have?

Timeouts live in three places: the http.Client, its http.Transport and the request's context. The net/http docs define each one, and the Cloudflare guide to net/http timeouts has the classic diagram of where they apply:

SettingCoversDefault
Client.TimeoutDial, redirects, request, headers and reading the whole body0 (none)
net.Dialer.TimeoutEstablishing the TCP connectionNone on a zero Dialer, 30s in DefaultTransport
Transport.TLSHandshakeTimeoutThe TLS handshake10s in DefaultTransport
Transport.ResponseHeaderTimeoutWaiting for response headers after the request is sent0 (none)
Transport.IdleConnTimeoutHow long an idle keep-alive connection stays in the pool90s in DefaultTransport
Context deadlineEverything until the body is closed, per requestNone

Client.Timeout is the simple one and the one people forget is end to end. It includes reading the response body, so a client with a 10-second timeout cannot download a file that takes 11 seconds, even if every byte is arriving.

How should you configure a client for a Third-Party API?

For a JSON API, set a whole-request timeout as the outer bound and the transport timeouts so that a slow dial or a server that never sends headers fails fast. Build it once and share it, since every http.Client with its own transport has its own connection pool:

// rates/client.go package rates import ( "net" "net/http" "time" ) // NewClient returns a client for small JSON APIs. Create one and reuse it. func NewClient() *http.Client { transport := &http.Transport{ Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{ Timeout: 3 * time.Second, KeepAlive: 30 * time.Second, }).DialContext, TLSHandshakeTimeout: 3 * time.Second, ResponseHeaderTimeout: 5 * time.Second, ExpectContinueTimeout: 1 * time.Second, IdleConnTimeout: 90 * time.Second, MaxIdleConns: 100, MaxIdleConnsPerHost: 20, ForceAttemptHTTP2: true, } return &http.Client{ Timeout: 10 * time.Second, Transport: transport, } }

MaxIdleConnsPerHost deserves the attention it rarely gets. Its default is 2, so a service making 50 concurrent calls to one API keeps only two connections warm and opens and closes the rest, paying a TCP and TLS handshake each time. Set it close to the concurrency you expect against that host. Cloning http.DefaultTransport with http.DefaultTransport.(*http.Transport).Clone() and changing a few fields is an alternative that keeps the proxy and HTTP/2 defaults.

How do you set a deadline per request?

Some calls need a shorter limit than the client default, and some need to respect a deadline that came from the caller. A context deadline applies to one request and cancels it wherever it is:

// rates/quote.go package rates import ( "context" "encoding/json" "fmt" "io" "net/http" "time" ) type Quote struct { Carrier string `json:"carrier"` PriceCents int64 `json:"price_cents"` } func GetQuote(ctx context.Context, c *http.Client, apiKey, zip string) (*Quote, error) { ctx, cancel := context.WithTimeout(ctx, 2*time.Second) defer cancel() req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.rates.example/v1/quote?zip="+zip, nil) if err != nil { return nil, err } req.Header.Set("Authorization", "Bearer "+apiKey) resp, err := c.Do(req) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { io.Copy(io.Discard, io.LimitReader(resp.Body, 64<<10)) return nil, fmt.Errorf("rates api: status %d", resp.StatusCode) } var q Quote if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&q); err != nil { return nil, err } return &q, nil }

The effective limit is whichever comes first, the 2-second context, the client's 10 seconds or a deadline already on the incoming ctx, so a handler with 500 milliseconds left never waits two seconds. Closing the body returns the connection to the pool only if it was read to the end, which is why the error path drains a bounded amount before returning. io.LimitReader on the decode stops a misbehaving API from streaming gigabytes into memory.

How do you tell a timeout from other errors?

A context deadline surfaces as an error that matches context.DeadlineExceeded, while Client.Timeout and transport timeouts produce a net.Error whose Timeout() method returns true. Code that wants to retry timeouts or map them to a 504 checks both:

// rates/errors.go package rates import ( "context" "errors" "net" ) func IsTimeout(err error) bool { if errors.Is(err, context.DeadlineExceeded) { return true } var netErr net.Error return errors.As(err, &netErr) && netErr.Timeout() }

Only retry timeouts on requests that are safe to repeat. A POST that creates a charge may have succeeded on the server even though your client gave up, so retries need an idempotency key the provider honours and a backoff between attempts. The bulkhead pattern guide covers keeping one slow upstream from using up every connection.

What about Server-Side timeouts?

The same gap exists on the other side: http.Server has no read or write timeouts by default, so a client that sends headers one byte at a time keeps a connection open indefinitely. Set ReadHeaderTimeout at minimum, plus ReadTimeout, WriteTimeout and IdleTimeout for APIs that do not stream, as the http.Server docs list.

How do you call a Third-Party API from an Encore service?

Encore

Encore is a backend framework with built-in infrastructure, and an outbound call to a third-party API inside an Encore endpoint is the same code as above, so everything above applies as written. What Encore adds is the context: each endpoint receives the request's ctx, the API key is a secret loaded into a struct instead of an environment variable, and a timeout can be returned as a typed API error that becomes a 504 for the caller.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.

Set up the app

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

Run in your terminal to get started locally.

~
$ encore app create shipping-api --example=hello-world$ cd shipping-api && mkdir shipping

The service declares the secret and one shared client at package level, and the endpoint maps timeouts to DeadlineExceeded and other upstream failures to Unavailable:

// shipping/shipping.go package shipping import ( "context" "encoding/json" "errors" "fmt" "io" "net" "net/http" "net/url" "time" "encore.dev/beta/errs" "encore.dev/rlog" ) var secrets struct { RatesAPIKey string } var client = &http.Client{ Timeout: 10 * time.Second, Transport: &http.Transport{ DialContext: (&net.Dialer{Timeout: 3 * time.Second, KeepAlive: 30 * time.Second}).DialContext, TLSHandshakeTimeout: 3 * time.Second, ResponseHeaderTimeout: 5 * time.Second, IdleConnTimeout: 90 * time.Second, MaxIdleConnsPerHost: 20, ForceAttemptHTTP2: true, }, } type QuoteParams struct { Zip string `query:"zip"` } type QuoteResponse struct { Carrier string `json:"carrier"` PriceCents int64 `json:"price_cents"` } //encore:api public method=GET path=/shipping/quote func GetQuote(ctx context.Context, p *QuoteParams) (*QuoteResponse, error) { if len(p.Zip) < 3 || len(p.Zip) > 10 { return nil, errs.B().Code(errs.InvalidArgument).Msg("invalid zip").Err() } ctx, cancel := context.WithTimeout(ctx, 2*time.Second) defer cancel() req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.rates.example/v1/quote?zip="+url.QueryEscape(p.Zip), nil) if err != nil { return nil, err } req.Header.Set("Authorization", "Bearer "+secrets.RatesAPIKey) resp, err := client.Do(req) if err != nil { var netErr net.Error if errors.Is(err, context.DeadlineExceeded) || (errors.As(err, &netErr) && netErr.Timeout()) { rlog.Warn("rates api timed out", "zip", p.Zip) return nil, errs.B().Code(errs.DeadlineExceeded).Msg("rates provider timed out").Err() } return nil, errs.B().Code(errs.Unavailable).Cause(err).Msg("rates provider unreachable").Err() } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { io.Copy(io.Discard, io.LimitReader(resp.Body, 64<<10)) return nil, errs.B().Code(errs.Unavailable).Msg(fmt.Sprintf("rates provider returned %d", resp.StatusCode)).Err() } var q QuoteResponse if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&q); err != nil { return nil, errs.B().Code(errs.Unavailable).Cause(err).Msg("bad response from rates provider").Err() } return &q, nil }

Set the carrier API key for local development and call the endpoint:

~/shipping-api
$ encore secret set --type dev,local RatesAPIKey$ encore run$ curl "localhost:4000/shipping/quote?zip=10115"

The secret value is set per environment with encore secret set and is not stored in the repository, so a coding agent working in it cannot read or leak the key. Each request to the endpoint appears with its duration in the local development dashboard's traces, so a slow provider shows up as a slow endpoint before you add any logging. On deploy to your own cloud, the service runs with the same client settings and the secret is read from the cloud's secret store.

An agent asked to add a second carrier copies the endpoint, points it at the new API and tests the timeout path locally against a stub server, all inside one service.

Best fit: Backends that call payment, shipping or other third-party APIs and want typed errors, per-environment secrets and request tracing around each call.

Go HTTP client timeout checklist

  • Never use http.DefaultClient or http.Get for calls to other services.
  • Set Client.Timeout as the outer bound, plus dial, TLS and response header timeouts.
  • Use http.NewRequestWithContext so incoming deadlines and per-call limits apply.
  • Share one client per upstream and raise MaxIdleConnsPerHost to match concurrency.
  • Close and drain response bodies, and cap reads with io.LimitReader.
  • Detect timeouts with errors.Is and net.Error, and retry only idempotent calls.

Frequently asked questions

Does Go's http.Client have a default timeout?

No. http.DefaultClient and a zero-value http.Client have Timeout set to zero, which means no timeout, so a server that accepts the connection and never answers blocks the call forever. Always create your own client with a Timeout or use a context deadline per request.

What does http.Client.Timeout include?

It covers the whole exchange: connecting, any redirects, sending the request and reading the entire response body. A large download that takes longer than the timeout is cut off partway through, so streaming clients usually set Transport timeouts and a context deadline instead.

How do I set a timeout for a single HTTP request in Go?

Create a context with context.WithTimeout, build the request with http.NewRequestWithContext(ctx, ...), and call client.Do. The request is cancelled when the deadline passes, and the error matches errors.Is(err, context.DeadlineExceeded).

How do I check if a Go HTTP error was a timeout?

Use errors.Is(err, context.DeadlineExceeded) for context deadlines, and for Client.Timeout or Transport timeouts check errors.As(err, &netErr) with a net.Error and netErr.Timeout(). Both forms are needed in code that uses both kinds of timeout.

Does Encore change how HTTP client timeouts are set?

No. Outbound HTTP clients in an Encore service use the standard library Timeout or a per-request context deadline. Encore provisions the service's infrastructure; it does not wrap the HTTP client.

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