A burst-tolerant HTTP handler in Go
This interview exercise applies the bounded-concurrency idea from the WaitGroup and errgroup examples to HTTP traffic. The final result accepts short bursts, sheds sustained overload, measures request duration, and exposes enough profiling data to guide performance work.
Task
Initial task
Implement GET /square?value=12. A successful response is JSON:
{"input":12,"square":144}
The handler will receive high traffic with periodic bursts. Limit concurrent work so the dependency behind the handler cannot be overwhelmed. Let requests wait briefly during a burst, then return 503 Service Unavailable when overload continues.
Follow-up 1: duration middleware
Move duration measurement into reusable HTTP middleware. The measurement must include admission wait, work, and response writing.
Follow-up 2: performance
Add small CPU and allocation benchmarks. Add pprof endpoints and Make targets that generate CPU and memory profiles or inspect a running service.
The code below is the final version after all follow-ups.
Solution
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/pprof"
"strconv"
"time"
)
const retryAfterSeconds = "1"
type SquareFunc func(context.Context, int64) (int64, error)
// SquareHandler limits expensive work while allowing short traffic bursts to wait.
// The HTTP server already starts a goroutine per request; slots bound calls to work,
// while queue bounds how many request goroutines may wait inside this handler.
// A worker pool can avoid one goroutine per accepted request when the transport allows it.
type SquareHandler struct {
slots chan struct{}
queue chan struct{}
maxQueueWait time.Duration
work SquareFunc
}
func NewSquareHandler(
maxConcurrent int,
maxQueued int,
maxQueueWait time.Duration,
work SquareFunc,
) (*SquareHandler, error) {
if maxConcurrent <= 0 {
return nil, errors.New("maxConcurrent must be positive")
}
if maxQueueWait <= 0 {
return nil, errors.New("maxQueueWait must be positive")
}
if maxQueued < 0 {
return nil, errors.New("maxQueued must not be negative")
}
if work == nil {
return nil, errors.New("work must not be nil")
}
return &SquareHandler{
slots: make(chan struct{}, maxConcurrent),
queue: make(chan struct{}, maxQueued),
maxQueueWait: maxQueueWait,
work: work,
}, nil
}
type squareResponse struct {
Input int64 `json:"input"`
Square int64 `json:"square"`
}
func (h *SquareHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.Header().Set("Allow", http.MethodGet)
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
// ParseInt with a 32-bit limit keeps every accepted square inside int64.
// Validating before acquiring a slot keeps bad requests away from scarce capacity.
input, err := strconv.ParseInt(r.URL.Query().Get("value"), 10, 32)
if err != nil {
http.Error(w, "value must be a signed 32-bit integer", http.StatusBadRequest)
return
}
if !h.acquire(r.Context()) {
// Retry-After lets a cooperative client back off instead of retrying immediately.
w.Header().Set("Retry-After", retryAfterSeconds)
http.Error(w, "server busy", http.StatusServiceUnavailable)
return
}
// Always release capacity, including when work returns an error or panics.
// This handler does not recover panics: the net/http server recovers them,
// closes the affected connection, and logs a stack trace.
defer func() { <-h.slots }()
// Use the request context for the actual work. maxQueueWait applies only to
// admission; otherwise a request that waited in the queue would have less time
// to execute. work still has to check ctx for cancellation to be effective.
result, err := h.work(r.Context(), input)
if err != nil {
http.Error(w, "processing failed", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
// Encoder streams directly to the response and avoids an intermediate []byte.
if err := json.NewEncoder(w).Encode(squareResponse{Input: input, Square: result}); err != nil {
// Headers may already be sent, so changing the status is too late. In a real
// service, record this error in logs or metrics instead of writing a second body.
return
}
}
func (h *SquareHandler) acquire(ctx context.Context) bool {
// The common path avoids allocating a timer when capacity is available.
select {
case h.slots <- struct{}{}:
return true
default:
}
// Reserve finite queue capacity before allocating a timer. When the queue is
// full, fail immediately; this keeps memory bounded during sustained overload.
select {
case h.queue <- struct{}{}:
defer func() { <-h.queue }()
default:
return false
}
// Only queued requests create a timer. This bounded wait absorbs a short burst.
timer := time.NewTimer(h.maxQueueWait)
defer timer.Stop()
select {
case h.slots <- struct{}{}:
return true
case <-timer.C:
return false
case <-ctx.Done():
return false
}
}
func square(_ context.Context, input int64) (int64, error) {
return input * input, nil
}
type DurationObserver func(time.Duration)
// MeasureDuration records end-to-end handler time, including queueing and writes.
// The defer also observes requests that panic; panic recovery remains a separate
// middleware concern. observe runs on the request path, so it must be concurrency-safe,
// fast, and must not panic. Production metrics clients usually aggregate in memory.
func MeasureDuration(next http.Handler, observe DurationObserver) http.Handler {
if observe == nil {
observe = func(time.Duration) {}
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
started := time.Now() // Time includes a monotonic reading, avoiding wall-clock jumps.
defer func() {
observe(time.Since(started))
}()
next.ServeHTTP(w, r)
})
}
// NewPprofHandler exposes Go's live profiles without changing http.DefaultServeMux.
// Serve this handler on a separate loopback or authenticated diagnostics listener;
// profiles can contain sensitive data and collecting CPU profiles consumes resources.
func NewPprofHandler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("/debug/pprof/", pprof.Index)
mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
return mux
}
// NewDebugServer gives diagnostics conservative HTTP timeouts. The caller owns
// ListenAndServe and Shutdown, which keeps server lifecycle out of the handler.
func NewDebugServer(addr string) *http.Server {
return &http.Server{
Addr: addr,
Handler: NewPprofHandler(),
ReadHeaderTimeout: 2 * time.Second,
ReadTimeout: 5 * time.Second,
WriteTimeout: 35 * time.Second, // longer than the default 30s CPU profile
IdleTimeout: 30 * time.Second,
}
}
// NewPublicHandler composes the final handler with duration measurement.
func NewPublicHandler(observe DurationObserver) (http.Handler, error) {
handler, err := NewSquareHandler(64, 256, 100*time.Millisecond, square)
if err != nil {
return nil, fmt.Errorf("create square handler: %w", err)
}
return MeasureDuration(handler, observe), nil
}
One semaphore protects the expensive operation and another bounds the waiting set. They do not limit accepted connections or prevent the HTTP server from starting a request goroutine. A short excess can wait; requests beyond the queue capacity, or beyond the wait deadline, receive 503.
The first nonblocking send in acquire matters on a hot path. An earlier version created a derived context and timer for every request. Profiling that version led to the fast path above, where timers exist only while all slots are occupied.
Tests
The first test covers the successful response and middleware. The second holds the only execution slot and verifies overload behavior. The last verifies that profiling was registered on the dedicated diagnostics handler.
package main
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
)
func TestSquareHandler(t *testing.T) {
handler, err := NewSquareHandler(2, 4, 50*time.Millisecond, square)
if err != nil {
t.Fatalf("create handler: %v", err)
}
var measured time.Duration
wrapped := MeasureDuration(handler, func(duration time.Duration) {
measured = duration
})
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodGet, "/square?value=12", nil)
wrapped.ServeHTTP(recorder, request)
if recorder.Code != http.StatusOK {
t.Fatalf("expected status %d, got %d", http.StatusOK, recorder.Code)
}
var actual squareResponse
if err := json.NewDecoder(recorder.Body).Decode(&actual); err != nil {
t.Fatalf("decode response: %v", err)
}
expected := squareResponse{Input: 12, Square: 144}
if actual != expected {
t.Fatalf("expected %+v, got %+v", expected, actual)
}
if measured <= 0 {
t.Fatalf("expected a positive measured duration, got %v", measured)
}
}
func TestSquareHandlerRejectsSustainedOverload(t *testing.T) {
started := make(chan struct{})
release := make(chan struct{})
work := func(ctx context.Context, input int64) (int64, error) {
close(started)
select {
case <-release:
return input * input, nil
case <-ctx.Done():
return 0, ctx.Err()
}
}
handler, err := NewSquareHandler(1, 1, 5*time.Millisecond, work)
if err != nil {
t.Fatalf("create handler: %v", err)
}
firstDone := make(chan struct{})
go func() {
defer close(firstDone)
handler.ServeHTTP(
httptest.NewRecorder(),
httptest.NewRequest(http.MethodGet, "/square?value=2", nil),
)
}()
<-started // the first request owns the only execution slot
recorder := httptest.NewRecorder()
handler.ServeHTTP(
recorder,
httptest.NewRequest(http.MethodGet, "/square?value=3", nil),
)
if recorder.Code != http.StatusServiceUnavailable {
t.Fatalf("expected status %d, got %d", http.StatusServiceUnavailable, recorder.Code)
}
if recorder.Header().Get("Retry-After") != retryAfterSeconds {
t.Fatalf("expected Retry-After %q", retryAfterSeconds)
}
close(release)
<-firstDone
}
func TestPprofHandler(t *testing.T) {
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodGet, "/debug/pprof/", nil)
NewPprofHandler().ServeHTTP(recorder, request)
if recorder.Code != http.StatusOK {
t.Fatalf("expected status %d, got %d", http.StatusOK, recorder.Code)
}
}
Run the suite with go test -race -count=1 ./.... The race detector is useful here because the handler and observer are called concurrently in a real server.
Benchmark tests
The benchmarks reuse the request and a small response writer, keeping request construction and httptest.ResponseRecorder allocations out of the measured loop. The CPU case uses RunParallel; the memory case keeps execution serial so allocation data is easier to read.
package main
import (
"net/http"
"net/http/httptest"
"runtime"
"testing"
"time"
)
type benchmarkResponseWriter struct {
header http.Header
}
func (w *benchmarkResponseWriter) Header() http.Header { return w.header }
func (*benchmarkResponseWriter) WriteHeader(int) {}
func (*benchmarkResponseWriter) Write(body []byte) (int, error) { return len(body), nil }
func benchmarkHandler(b *testing.B) http.Handler {
b.Helper()
handler, err := NewSquareHandler(runtime.GOMAXPROCS(0), runtime.GOMAXPROCS(0), time.Second, square)
if err != nil {
b.Fatal(err)
}
return MeasureDuration(handler, nil)
}
// BenchmarkSquareHandlerCPU runs concurrent requests to reveal contention and CPU cost.
func BenchmarkSquareHandlerCPU(b *testing.B) {
handler := benchmarkHandler(b)
b.ReportAllocs()
b.RunParallel(func(pb *testing.PB) {
// Each benchmark worker owns these values; sharing the header map would race.
writer := &benchmarkResponseWriter{header: make(http.Header)}
request := httptest.NewRequest(http.MethodGet, "/square?value=12", nil)
for pb.Next() {
handler.ServeHTTP(writer, request)
}
})
}
// BenchmarkSquareHandlerMemory isolates per-request allocations in a serial path.
func BenchmarkSquareHandlerMemory(b *testing.B) {
handler := benchmarkHandler(b)
writer := &benchmarkResponseWriter{header: make(http.Header)}
request := httptest.NewRequest(http.MethodGet, "/square?value=12", nil)
b.ReportAllocs()
b.ResetTimer()
for range b.N {
handler.ServeHTTP(writer, request)
}
}
These are microbenchmarks of the handler path. They do not model sockets, TLS, kernel scheduling, downstream latency, or a real burst distribution. Use a load test for end-to-end capacity and tail latency.
Make targets
test:
@go test ./...
test-race:
@go test -race -count=1 ./...
benchmark:
@go test -run '^$$' -bench '^BenchmarkSquareHandler' -benchmem -count=3 .
pprof-cpu:
@mkdir -p .profiles
@go test -run '^$$' -bench '^BenchmarkSquareHandlerCPU$$' -benchtime=5s -cpuprofile=.profiles/cpu.out -o .profiles/test-concurrency6.test .
@go tool pprof -top .profiles/cpu.out
pprof-memory:
@mkdir -p .profiles
@go test -run '^$$' -bench '^BenchmarkSquareHandlerMemory$$' -benchtime=5s -memprofile=.profiles/memory.out -memprofilerate=1 -o .profiles/test-concurrency6.test .
@go tool pprof -top -alloc_space .profiles/memory.out
# These targets connect to a running NewDebugServer on 127.0.0.1:6060.
pprof-live-cpu:
@go tool pprof -top 'http://127.0.0.1:6060/debug/pprof/profile?seconds=30'
pprof-live-heap:
@go tool pprof -top 'http://127.0.0.1:6060/debug/pprof/heap'
.PHONY: test test-race benchmark pprof-cpu pprof-memory pprof-live-cpu pprof-live-heap
pprof-cpu and pprof-memory profile repeatable benchmark workloads. The live targets inspect a service that is already serving NewDebugServer on 127.0.0.1:6060. Keeping the diagnostics listener separate prevents the public mux from exposing profiles.
Output examples
The benchmark below ran on an Apple M1. Absolute values vary by machine, Go version, and system load; compare results produced in the same environment.
$ make benchmark
BenchmarkSquareHandlerCPU-8 3166224 355.4 ns/op 464 B/op 6 allocs/op
BenchmarkSquareHandlerCPU-8 3405649 351.5 ns/op 464 B/op 6 allocs/op
BenchmarkSquareHandlerCPU-8 3392311 354.2 ns/op 464 B/op 6 allocs/op
BenchmarkSquareHandlerMemory-8 2815530 428.5 ns/op 464 B/op 6 allocs/op
BenchmarkSquareHandlerMemory-8 2775781 430.7 ns/op 464 B/op 6 allocs/op
BenchmarkSquareHandlerMemory-8 2714626 434.5 ns/op 464 B/op 6 allocs/op
PASS
The abridged CPU profile shows substantial cumulative time around the semaphore channel under parallel load:
$ make pprof-cpu
flat flat% sum% cum cum%
0.03s 0.13% 87.06% 17.53s 75.11% (*SquareHandler).ServeHTTP
0.02s 0.086% 87.62% 7.71s 33.03% (*SquareHandler).acquire
0.02s 0.086% 87.87% 7.69s 32.95% runtime.chansend
0.01s 0.043% 88.17% 0.81s 3.47% net/url.parseQuery
The abridged allocation profile points first to query parsing, then response headers and JSON:
$ make pprof-memory
flat flat% sum% cum cum%
187879.81kB 79.25% 79.25% 187880.08kB 79.25% net/url.parseQuery
8170.06kB 3.45% 93.03% 8170.06kB 3.45% net/textproto.MIMEHeader.Set
8168.73kB 3.45% 96.47% 237002.76kB 100% (*SquareHandler).ServeHTTP
8168.69kB 3.45% 99.92% 8168.69kB 3.45% reflect.unsafe_New
Those profiles identify candidates, not automatic fixes. A custom query parser could remove allocations but would need to preserve URL escaping, duplicate-key behavior, and validation. Replacing JSON or the channel also adds complexity. Optimize them only when production measurements show that handler overhead matters relative to the actual work.
