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.

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.
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:
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.
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.
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.
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.
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.
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.

Run in your terminal to get started locally.
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:
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.
http.DefaultClient or http.Get for calls to other services.Client.Timeout as the outer bound, plus dial, TLS and response header timeouts.http.NewRequestWithContext so incoming deadlines and per-call limits apply.MaxIdleConnsPerHost to match concurrency.io.LimitReader.errors.Is and net.Error, and retry only idempotent calls.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.
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.
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).
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.
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.