Stage 3 · Build
Observability & Networking
Production HTTP Servers
Graceful shutdown, timeouts, middleware, and httprouter for reliable services.
Server Setup
A production HTTP server needs more than http.ListenAndServe. It needs timeouts, graceful shutdown, structured logging, and health checks. The standard library provides all of these.
Timeout Configuration
Timeouts protect your server from resource exhaustion. Every timeout has a purpose — set them based on your workload characteristics.
Middleware Patterns
Middleware wraps handlers to add cross-cutting behavior. Logging, authentication, CORS, and rate limiting are common middleware.
Graceful Shutdown
Graceful shutdown drains in-flight requests before stopping. This prevents data loss and ensures clean disconnections in Kubernetes.
Router Selection
The standard library ServeMux is sufficient for most services. For more features — path parameters, method matching, middleware chains — use a lightweight router.
| Router | Use Case | Key Features |
|---|---|---|
| net/http ServeMux | Simple services | Standard library, no dependencies |
| chi | REST APIs | Express-like, middleware, URL params |
| httprouter | High performance | Minimal, used by gin |
| gin | Full-featured | Middleware, validation, JSON binding |
Production Checklist
- Set ReadTimeout, WriteTimeout, and IdleTimeout
- Implement graceful shutdown with signal handling
- Add health check endpoints (/healthz, /readyz)
- Use structured logging for request logging
- Add request ID propagation for tracing
- Set up metrics collection (request count, latency)
- Configure TLS for external-facing services
- Add rate limiting for public endpoints
- Use context timeouts for downstream calls
- Test shutdown behavior under load
http.ListenAndServe does not set timeouts, does not handle graceful shutdown, and does not log errors properly. Always create http.Server explicitly with proper timeout and shutdown configuration.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.