Protect Endpoints With Rate Limiting and Panic Recovery
Wrap handlers with panic recovery that logs stack traces safely and enforce simple per-key request limits. After this, one unexpected panic or burst will not take down the server.
Course content
Sign in to save your progress.
-
Bounded Concurrency and Worker Pools
-
Bound Concurrency With a Worker Pool
-
Coordinate Shared State With sync.Mutex and atomic
-
-
-
Memory, Allocations, and Benchmarking
-
Measure Speed and Allocations With go test -bench
-
Cut Allocations With Pre-Sizing and sync.Pool
-
-
-
Profiling and Diagnostics
-
Find CPU and Heap Hotspots With pprof
-
Catch Goroutine Leaks and Slow Tests Early
-
-
-
Resilience and Defensive HTTP
-
Add Retries With Backoff and Jitter
-
Protect Endpoints With Rate Limiting and Panic Recovery
-
-
-
Production Builds and Containers
-
Embed Static Assets and Version Info With embed and ldflags
-
Ship a Multi-Stage Scratch Go Container
-
-
-
Fuzzing, GC Tuning, Tracing, and Reflection
-
Fuzz Testing Parsers and Decoders With go test -fuzz
-
Escape Analysis and GC Tuning (-gcflags="-m", GOGC, GOMEMLIMIT)
-
Execution Tracing and Block/Mutex Contention Profiling
-
Reflection, Struct Tags, and go generate
-
-
In Go's net/http server, a panic inside a request handler does not kill the whole process—net/http catches it internally—but the client receives an abruptly dropped TCP connection with no HTTP status code and no JSON error body. Meanwhile, an unguarded json.NewDecoder(r.Body).Decode(...) happily reads a 500 MB upload straight into heap memory until the kernel OOM-kills your container.
Pairing an outer panic-recovery middleware with http.MaxBytesReader (and per-client rate limiting) turns both failures into clean, predictable 500, 413, and 429 JSON responses while keeping the server healthy.
Skip ahead
If you already wrap routers in recover() middleware (re-panicking http.ErrAbortHandler), cap bodies with http.MaxBytesReader, and map *http.MaxBytesError to HTTP 413, take the section quiz or move on to "Embed Static Assets and Version Info With embed and ldflags."
Experiment 1: Structured 500 on panics and 413 on oversized JSON bodies
Watch both guards in action in one runnable program—testing a panicking /boom route and a 2 KB payload hitting a 1 KB limit on /items:
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
)
func recoverMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if rec := recover(); rec != nil {
if rec == http.ErrAbortHandler {
panic(rec)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(`{"error":"internal server error"}`))
}
}()
next.ServeHTTP(w, r)
})
}
func createItem(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, 1024)
var body struct{ Name string `json:"name"` }
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
var maxErr *http.MaxBytesError
if errors.As(err, &maxErr) {
http.Error(w, `{"error":"payload too large"}`, http.StatusRequestEntityTooLarge)
return
}
http.Error(w, `{"error":"invalid json"}`, http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusCreated)
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/boom", func(w http.ResponseWriter, r *http.Request) { panic("nil lookup") })
mux.HandleFunc("/items", createItem)
h := recoverMiddleware(mux)
rec1 := httptest.NewRecorder()
h.ServeHTTP(rec1, httptest.NewRequest(http.MethodGet, "/boom", nil))
fmt.Printf("boom status=%d body=%s\n", rec1.Code, rec1.Body.String())
big := bytes.Repeat([]byte("a"), 2048)
req := httptest.NewRequest(http.MethodPost, "/items", bytes.NewReader(append([]byte(`{"name":"`), append(big, []byte(`"}`)...)...)))
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req)
fmt.Printf("big status=%d body=%s", rec2.Code, rec2.Body.String())
}
$ go run .
boom status=500 body={"error":"internal server error"}
big status=413 body={"error":"payload too large"}
Experiment 2: Why checking http.ErrAbortHandler and logging debug.Stack() matters
Two production details separate robust recovery middleware from a toy wrapper:
- Log
recplusstring(debug.Stack())withslog.Error: Returning500without logging the stack trace hides the bug forever—yet never send the stack trace in the HTTP response body, where it leaks internal file paths and implementation details to callers. - Re-panic on
http.ErrAbortHandler: Streaming handlers intentionally callpanic(http.ErrAbortHandler)to abort a broken response silently; re-panicking letsnet/httpclose the connection without writing a bogus500or logging a false alert.
Experiment 3: Adding a token-bucket rate limiter with x/time/rate
To prevent one abusive client or buggy script from saturating your API, guard expensive endpoints with a non-blocking token-bucket limiter from golang.org/x/time/rate:
limiter := rate.NewLimiter(rate.Limit(20), 40) // 20 req/s steady, burst up to 40
func rateLimitMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !limiter.Allow() {
w.Header().Set("Retry-After", "1")
http.Error(w, `{"error":"rate limit exceeded"}`, http.StatusTooManyRequests)
return
}
next.ServeHTTP(w, r)
})
}
Using limiter.Allow() fails fast with 429 Too Many Requests instead of queueing thousands of goroutines in RAM waiting for tokens.
Experiment 4: The goroutine panic trap
recover() only catches panics on the exact goroutine where defer recover() was registered. If an HTTP handler spawns a fire-and-forget goroutine (go sendWebhook(ev)) and that child goroutine hits a nil pointer panic, recoverMiddleware on the request goroutine cannot catch it—the entire Go server crashes immediately! Always add a defer recover() inside any background goroutine you launch.
Common mistakes
- Forgetting
http.MaxBytesReaderon JSON endpoints: Allows a single malicious 500 MB POST to OOM-kill your container. - Using
io.LimitReaderinstead ofhttp.MaxBytesReaderon HTTP bodies:LimitReadersilently truncates without returning*http.MaxBytesErroror telling the HTTP server to stop draining the excess bytes. - Swallowing panics without logging
debug.Stack(): Turns real nil-pointer bugs into mysterious silent500s.
💡 Tip
Put recoverMiddleware as the outermost middleware in your chain—outside logging and rate limiting—so even a panic inside another middleware still produces a clean JSON 500.
What happens if you skip this step
Without MaxBytesReader and recovery middleware, one malformed giant upload can OOM-kill every active user on that pod, and one unhandled panic drops connections mid-response with zero structured diagnostics.
Your HTTP server uses recoverMiddleware around every route, and a handler starts go auditLog(user) where auditLog panics on a nil pointer. Does recoverMiddleware catch that panic and keep the server running?
About
Wrap handlers with panic recovery that logs stack traces safely and enforce simple per-key request limits. After this, one unexpected panic or burst will not take down the server.
- Duration
- 5 min
- Last update
- 11/27/2026
Comments
Sign in to commentNo comments yet.