Set Timeouts on HTTP Clients and Server Handlers
Replace http.Get with http.NewRequestWithContext and configure explicit client and server timeouts. After this, external API calls and incoming requests respect strict time budgets.
Course content
Sign in to save your progress.
-
Interfaces and Standard Abstractions
-
Interfaces Are Satisfied Implicitly
-
Read and Stream With io.Reader and io.Writer
-
-
-
Context, Timeouts, and Cancellation
-
Use context.Context for Deadlines and Cancellation
-
Set Timeouts on HTTP Clients and Server Handlers
-
-
-
Goroutines, Channels, and Coordination
-
Run Concurrent Work Safely With sync.WaitGroup
-
Coordinate Pipelines and Timeouts With Channels and select
-
-
-
Structured Logging and Databases
-
Write Structured JSON Logs With log/slog
-
Query Relational Data Safely With database/sql
-
-
-
Middleware and Production-Ready Services
-
Wrap HTTP Handlers With Middleware
-
Build a Multi-Route Service With Graceful Shutdown
-
-
-
Generics, Transactions, Timers, and Test Doubles
-
Generics, Constraints, and slices/maps Packages
-
SQL Transactions and Connection Pool Limits
-
Timers, Tickers, and Avoiding time.After Leaks
-
Testing With Interface Fakes, t.TempDir, and testdata
-
-
Two of the most convenient functions in Go's standard library are also two of the most common causes of production outages: http.Get(url) uses http.DefaultClient—which has no timeout at all—and http.ListenAndServe(":8080", h) creates an http.Server with no timeouts at all.
A single hung upstream API can leave outbound goroutines blocked forever, and a few hundred slow-loris TCP connections can exhaust your server's file descriptors until healthy traffic is rejected.
Skip ahead
If you already configure reusable *http.Client timeouts with http.NewRequestWithContext and always set ReadHeaderTimeout and IdleTimeout on *http.Server, take the section quiz or move on to "Run Concurrent Work Safely With sync.WaitGroup."
Experiment 1: Watching a hung upstream get caught cleanly by http.Client.Timeout
Never use http.Get in production code. Construct a reusable *http.Client with an explicit Timeout, and build each request with http.NewRequestWithContext so caller cancellation aborts in-flight calls too:
package main
import (
"context"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"time"
)
func main() {
slow := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
select {
case <-time.After(200 * time.Millisecond):
w.WriteHeader(200)
case <-r.Context().Done():
}
}))
defer slow.Close()
client := &http.Client{Timeout: 40 * time.Millisecond}
req, _ := http.NewRequestWithContext(context.Background(), "GET", slow.URL, nil)
_, err := client.Do(req)
fmt.Printf("timed_out=%v err_is_deadline=%v\n", err != nil, errors.Is(err, context.DeadlineExceeded))
}
timed_out=true err_is_deadline=true
Notice two critical details: first, errors.Is(err, context.DeadlineExceeded) matches cleanly so your handler can return 504 Gateway Timeout; second, client.Timeout covers the entire round-trip (DNS + TCP dial + TLS handshake + headers + reading resp.Body).
Experiment 2: Reuse one *http.Client across requests
Creating client := &http.Client{Timeout: 5 * time.Second} once at startup and sharing it across all goroutines is completely safe—*http.Client is designed for concurrent reuse. Creating a new &http.Client{} inside every request handler bypasses TCP/TLS keep-alive pooling and leaks idle sockets under load.
Experiment 3: Inbound server protection—why ReadHeaderTimeout beats a short ReadTimeout
Think through what happens when a malicious (or flaky cellular) client opens 2,000 TCP sockets, sends GET / HTTP/1.1\r\n, and stops sending bytes. With http.ListenAndServe, those 2,000 sockets stay open indefinitely. Setting an explicit *http.Server stops that cold:
srv := &http.Server{
Addr: ":8080",
Handler: mux,
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 15 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
}
Why do we care about the difference between ReadHeaderTimeout and ReadTimeout?
ReadHeaderTimeout: 5sbounds only the tiny HTTP headers—stopping slow-loris attacks immediately without hurting legitimate users uploading a 20 MB file over slow mobile data.ReadTimeout: 15scovers the entire body read; raise or omit it on large upload endpoints and cap size withhttp.MaxBytesReaderinstead.WriteTimeout: 15sstarts ticking right after headers are read—which means slow database queries inside your handler count againstWriteTimeouttoo! For long Server-Sent Events (SSE) streams, leaveWriteTimeoutoff and usehttp.NewResponseController(w).SetWriteDeadlineper route.IdleTimeout: 60scloses idle keep-alive sockets cleanly; set it slightly higher than your reverse proxy's (Nginx/ALB) idle timeout to avoid race-condition 502 errors.
Common mistakes
- Calling
http.Get(url)in services: Useshttp.DefaultClientwith an infinite timeout—one hung vendor API stalls every worker. - Forgetting
defer resp.Body.Close(): Even after checkingresp.StatusCode, an unclosed body preventshttp.Transportfrom reusing the TCP connection. - Setting a 5-second global
WriteTimeouton streaming endpoints: Kills valid SSE or large file downloads mid-stream.
💡 Tip
If an endpoint receives a 500 error body you don't plan to parse, drain a small prefix before closing (io.Copy(io.Discard, io.LimitReader(resp.Body, 4096)); resp.Body.Close()) so Go's HTTP transport can still reuse the TCP connection cleanly.
What happens if you skip this step
Your service runs cleanly in staging where every upstream answers in 20 ms, then locks up completely in production the first afternoon a third-party webhook endpoint drops packets without closing the TCP socket.
Your API accepts 50 MB video uploads over slow mobile connections, and you set ReadTimeout: 5 * time.Second on http.Server. What happens to legitimate mobile uploads, and which timeout should you use instead?
About
Replace http.Get with http.NewRequestWithContext and configure explicit client and server timeouts. After this, external API calls and incoming requests respect strict time budgets.
- Duration
- 5 min
- Last update
- 11/27/2026
Comments
Sign in to commentNo comments yet.