Trace HTTP requests and design bounded retries
Trace HTTP requests and design bounded retries
httptrace attaches hooks to a request context to observe events such as connection acquisition. Retry only operations whose semantics permit it, with bounded attempts and an overall deadline. An idempotent operation has the same intended effect when repeated; even GET must actually obey its contract. Do not blindly retry mutations after ambiguous failures.
package main
import ( "context" "fmt" "io" "net/http" "net/http/httptest" "net/http/httptrace" "sync/atomic" "time")
func check(err error) { if err != nil { panic(err) }}func fixture(h http.HandlerFunc) (*httptest.Server, *http.Client) { s := httptest.NewServer(h) c := s.Client() c.Timeout = 2 * time.Second return s, c}func main() { s, c := fixture(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "ok") }) defer s.Close() for i := 0; i < 2; i++ { var reused atomic.Bool trace := &httptrace.ClientTrace{GotConn: func(info httptrace.GotConnInfo) { reused.Store(info.Reused) }} ctx := httptrace.WithClientTrace(context.Background(), trace) req, e := http.NewRequestWithContext(ctx, http.MethodGet, s.URL, nil) check(e) res, e := c.Do(req) check(e) _, e = io.Copy(io.Discard, res.Body) check(e) check(res.Body.Close()) fmt.Println(reused.Load()) }}GotConn reports whether the connection had already been used. In this simple HTTP/1.1 fixture with small bodies read to EOF, the second request reuses the connection. Real reuse is not guaranteed. Hooks can execute concurrently or multiple times; atomic storage keeps the last observation race-safe. Do not log secrets or full URLs indiscriminately.
Expected output:
falsetrueRetry a read-only request at most once
package main
import ( "context" "errors" "fmt" "io" "net/http" "net/http/httptest" "sync/atomic" "time")
func check(err error) { if err != nil { panic(err) }}func fixture(h http.HandlerFunc) (*httptest.Server, *http.Client) { s := httptest.NewServer(h) c := s.Client() c.Timeout = 2 * time.Second return s, c}func getRetry(ctx context.Context, c *http.Client, u string) (int, error) { for attempt := 0; attempt < 2; attempt++ { req, e := http.NewRequestWithContext(ctx, http.MethodGet, u, nil) if e != nil { return 0, e } res, e := c.Do(req) if e != nil { return 0, e } status := res.StatusCode _, e = io.Copy(io.Discard, io.LimitReader(res.Body, 1024)) ce := res.Body.Close() if e != nil { return 0, e } if ce != nil { return 0, ce } if status != 503 || attempt == 1 { return status, nil } } return 0, errors.New("unreachable")}func main() { var calls atomic.Int32 s, c := fixture(func(w http.ResponseWriter, r *http.Request) { if calls.Add(1) == 1 { w.WriteHeader(503) return } w.WriteHeader(200) }) defer s.Close() ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() status, e := getRetry(ctx, c, s.URL) check(e) fmt.Println(status, calls.Load())}This local GET retries only 503, twice total at most; transport errors return immediately. It discards at most 1024 bytes per attempt, closes each body and returns the final status. No delay is used in this fixture. In production use capped backoff with jitter, honor applicable Retry-After within the deadline, stop on cancellation and avoid retry amplification. A POST idempotency header alone does not establish server-side replay safety. Go Transport can also retry some network failures under documented conditions; application attempt counts are not necessarily wire counts.
Expected output:
200 2Try it locally
Use getRetry with a server always returning 503. Print final status and number of handler calls.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
HTTP clients 08: Trace HTTP requests and design bounded retries
Check the lesson objective before moving on.
What does GotConnInfo.Reused indicate?
What should govern a retry after ambiguous failure?