By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
http.DefaultClient has no timeout, so a stalled server can hang your request handler indefinitely. Create your own *http.Client with a timeout and tune its Transport: idle connection limits, TLS handshake timeout and response header timeout. A per-request context.WithTimeout gives you the finest control and propagates cancellation from the caller.
Always close the response body, even on non-2xx responses, or the connection cannot be reused and the transport leaks. Drain the body before closing when you intend to reuse the connection. Bound how much of the response you read — a misbehaving peer should not be able to exhaust your memory.
Retrying is not a universal fix. GET, HEAD, PUT and DELETE are idempotent by definition; POST is not, unless the server honors an idempotency key. Retry only on transport errors, 429 and 5xx, use exponential backoff with jitter, cap the attempts and respect Retry-After. Never retry a 400 or a 401 — the same request will fail the same way and you are only adding load.
package main
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"time"
)
func main() {
attempts := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
attempts++
if r.Header.Get("Idempotency-Key") != "evt-1" {
http.Error(w, "missing idempotency key", http.StatusBadRequest)
return
}
if attempts < 3 {
w.WriteHeader(http.StatusServiceUnavailable)
fmt.Fprintln(w, "unavailable")
return
}
w.WriteHeader(http.StatusAccepted)
fmt.Fprintln(w, `{"status":"accepted"}`)
}))
defer server.Close()
client := &http.Client{Timeout: 2 * time.Second}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
body := `{"service":"api","level":"info","status":200}`
backoff := 10 * time.Millisecond
finalStatus := 0
for attempt := 1; attempt <= 3; attempt++ {
req, err := http.NewRequestWithContext(ctx, http.MethodPost, server.URL+"/v1/events", bytes.NewReader([]byte(body)))
if err != nil {
panic(err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", "evt-1")
resp, err := client.Do(req)
if err != nil {
panic(err)
}
payload, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
resp.Body.Close()
finalStatus = resp.StatusCode
fmt.Println("attempt", attempt, "status", resp.StatusCode, "body", strings.TrimSpace(string(payload)))
if resp.StatusCode < 500 {
break
}
time.Sleep(backoff)
backoff *= 2
}
fmt.Println("final", finalStatus)
}| Outcome | Retry? | Notes |
|---|---|---|
| Transport error | Yes | Connection reset, DNS failure, timeout |
| 429 Too Many Requests | Yes | Honor Retry-After and add jitter |
| 500 / 502 / 503 / 504 | Yes, with a cap | Only for idempotent requests or with an idempotency key |
| 400 / 422 | No | The request itself is wrong |
| 401 / 403 | No | Retrying cannot fix credentials or policy |
| 404 | No | Retrying a missing resource is pointless |
Key takeaways
Never use a client without a timeout; configure http.Client and per-request contexts.
Close and drain response bodies so connections are reused and not leaked.
Retry only safe operations or requests with an idempotency key; cap attempts and use jittered backoff.
Respect Retry-After, and do not retry 4xx errors that a retry cannot fix.
Set a total deadline so retries cannot outlive the caller's patience.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.