Add Context Deadlines to Outbound HTTP Calls in Go
Replace http.Get with http.NewRequestWithContext, combine Client.Timeout with per-call context.WithTimeout, and detect DeadlineExceeded cleanly. After this, slow upstream APIs cannot hang your service.
Skip ahead: If you already use http.NewRequestWithContext, skip to "Case 2: Client.Timeout vs. context.WithTimeout" or the timeout table below.
Calling http.Get(url) in Go uses http.DefaultClient, which has no timeout and ignores caller cancellation. If an upstream API stalls or drops packets silently, your goroutine stays blocked forever and holds a socket open. Using an explicit http.Client together with http.NewRequestWithContext bounds every outbound call. Verified on golang:trixie (Go 1.27.4).
Case 1: abort a slow upstream call with context.WithTimeout
This test server stalls for 100ms, while the caller gives the request a 20ms context budget:
package main
import (
"context"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"time"
)
func main() {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
select {
case <-time.After(100 * time.Millisecond):
w.Write([]byte("ok"))
case <-r.Context().Done():
return
}
}))
defer srv.Close()
client := &http.Client{Timeout: 5 * time.Second}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
defer cancel()
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL, nil)
_, err := client.Do(req)
fmt.Println("is DeadlineExceeded:", errors.Is(err, context.DeadlineExceeded))
fmt.Println("err:", err)
}
is DeadlineExceeded: true
err: Get "http://127.0.0.1:40213": context deadline exceeded
Notice two things:
- Even though
client.Timeoutwas5s, the20msrequest context canceled first and returnedcontext.DeadlineExceeded. - Inside the test server, listening on
<-r.Context().Done()stopped the handler immediately instead of wasting 80 more milliseconds.
Case 2: Client.Timeout vs. context.WithTimeout
Why use both? client.Timeout acts as a safety ceiling across the whole client (covering DNS, TCP connect, TLS handshake, response headers, and reading resp.Body), while context.WithTimeout lets individual endpoints set tighter budgets or inherit r.Context() from an incoming HTTP request:
- If an incoming user request only has
150msleft, derivingctx, cancel := context.WithTimeout(r.Context(), 100*time.Millisecond)ensures the outbound call stops if either the 100ms budget expires or the browser closes the tab. - Always call
defer cancel()right after creating the context so Go frees the internal timer immediately when the call succeeds early.
Case 3: remember to close resp.Body
Whenever client.Do(req) returns err == nil, you must close resp.Body—even if you ignore its contents or only check resp.StatusCode:
- Call
defer resp.Body.Close()only after checkingif err != nil { return err }(a failed request can return anilresponse). - Read or drain small bodies before closing if you want
http.Clientto reuse the underlying keep-alive TCP connection.
Case 4: reuse one *http.Client across your service
Creating &http.Client{...} inside every function allocates a brand-new http.Transport and connection pool per call, opening new TCP/TLS handshakes every time and leaking idle sockets. Build one shared *http.Client at startup and pass it into your handlers or service struct.
Outbound HTTP timeout checklist
| Layer | Setting | What it protects |
|---|---|---|
| Client safety net | Timeout: 10 * time.Second | Prevents any forgotten request from hanging forever |
| Per-call budget | http.NewRequestWithContext(ctx, ...) | Propagates caller cancellation and tighter deadlines |
| Transport dial/TLS | http.Transport{TLSHandshakeTimeout: 5 * time.Second} | Fails fast on stalled TCP or TLS handshakes |
| Connection reuse | One shared *http.Client + defer resp.Body.Close() | Avoids socket exhaustion and repeated TLS handshakes |
⚠ Warning: If you call cancel() before finishing io.ReadAll(resp.Body), reading the body will fail mid-stream with context canceled. Keep defer cancel() in the function that reads resp.Body, not in a helper that returns the open body.
Common mistakes
- Using
http.Getorhttp.Postin services: both usehttp.DefaultClientwith zero timeout. - Calling
defer cancel()inside a loop: if you retry or loop 100 times,deferdoes not run until the outer function returns; wrap each attempt in a helper function or callcancel()explicitly after reading the response.
What happens if you skip this
One slow third-party webhook or stalled DNS lookup piles up blocked goroutines and open file descriptors until your service hits too many open files or stops responding to healthy endpoints.
Related course: Go Intermediate.
About
Replace http.Get with http.NewRequestWithContext, combine Client.Timeout with per-call context.WithTimeout, and detect DeadlineExceeded cleanly. After this, slow upstream APIs cannot hang your service.
- Responsible
- Jay P
- Last Update
- 11/27/2026
- Reading Time
- 4 min
Reviews
Sign in to write a reviewComments
Sign in to commentNo comments yet.