RC RANDOM CHAOS

Go's httptrace: Per-Request Hooks for DNS, TLS, and TTFB Timing

· via Hacker News

Original source

Tracing HTTP Requests with Go's net/HTTP/httptrace

Hacker News →

Go’s net/http/httptrace package, in the standard library since 1.7, exposes hooks for the internal phases of an outgoing HTTP request — DNS resolution, connection acquisition, TLS handshake, request write, and first response byte. Rather than registering a tracer on http.Client, callers attach a ClientTrace struct of optional callback fields to a context.Context, and the transport pulls it out via httptrace.ContextClientTrace at the relevant moments. This design means traces ride along with the request context, propagate through any middleware that forwards context, allow concurrent requests on the same client to carry distinct traces, and cost nothing when unused.

The article works through two practical applications. The first is a curl —trace-style CLI that captures time.Now() in each hook and prints a breakdown of DNS, TCP, TLS, server processing, and content transfer durations — no APM agent or external dependency required. The second wraps the pattern in an http.RoundTripper so every request through a given client is logged automatically. Two gotchas are worth noting: attaching a trace via httptrace.WithClientTrace composes with any existing trace rather than replacing it, and RoundTrip returns when response headers arrive, not when the body finishes, so capturing full request time requires wrapping the response body’s Close.

The broader point is that httptrace gives Go developers fine-grained visibility into HTTP client behavior using only the standard library, useful for diagnosing whether latency lives in DNS, the handshake, the server, or the wire.

Read the full article

Continue reading at Hacker News →

This is an AI-generated summary. Read the original for the full story.