Skip to Content
Skip to content
Add Context Deadlines to Outbound HTTP Calls in Go
Intermediate
Tutorials

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.

Updated 4 min read GoAPIs and Integrations

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.Timeout was 5s, the 20ms request context canceled first and returned context.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 150ms left, deriving ctx, 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 checking if err != nil { return err } (a failed request can return a nil response).
  • Read or drain small bodies before closing if you want http.Client to 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

LayerSettingWhat it protects
Client safety netTimeout: 10 * time.SecondPrevents any forgotten request from hanging forever
Per-call budgethttp.NewRequestWithContext(ctx, ...)Propagates caller cancellation and tighter deadlines
Transport dial/TLShttp.Transport{TLSHandshakeTimeout: 5 * time.Second}Fails fast on stalled TCP or TLS handshakes
Connection reuseOne 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.Get or http.Post in services: both use http.DefaultClient with zero timeout.
  • Calling defer cancel() inside a loop: if you retry or loop 100 times, defer does not run until the outer function returns; wrap each attempt in a helper function or call cancel() 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
Was this helpful?
​ 0 ​ 0

Comments

Sign in to comment

No comments yet.