HTTP services in Go
The net/http package is enough to build a real API. If you understand handlers and the Go 1.22 routing, middleware, one goroutine per request, server and client timeouts, safe JSON reading, graceful shutdown in Kubernetes and the database connection pool, you can answer most interview questions.
Author: bezzad
Contents
The problem: an order API that breaks under load
The order API of our shop works well in tests. But in production we have these reports:
- During a sale the last pair of shoes was sold twice.
- On every deploy a few dozen users get a 502 error.
- When the payment provider is slow, all payment requests get stuck and the service stops answering.
- A broken client sent a 100 MB JSON body, and the pod ran out of memory.
All of these come from a few default behaviors of net/http that you must know. In this lesson we build a small order API that is ready for production.
The Handler type
Everything in net/http is built around one small interface:
type Handler interface {
ServeHTTP(ResponseWriter, *Request)
}
- Any type with a ServeHTTP method is a handler.
- The HandlerFunc type turns a normal function into a handler. So most of the time we just write a function.
- The router (ServeMux) is a handler too. Middleware is also a handler. So they can all be wrapped inside each other.
Routing with ServeMux
Since Go 1.22 the standard router understands the HTTP method and path variables. For most APIs you do not need a router library anymore:
func (a *API) Routes() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /orders/{id}", a.getOrder)
mux.HandleFunc("POST /orders", a.createOrder)
mux.HandleFunc("GET /healthz", a.healthz)
return RequestID(Logging(a.log, Recover(a.log, mux)))
}
func (a *API) getOrder(w http.ResponseWriter,
r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.Error(w, "bad order id", http.StatusBadRequest)
return
}
o, err := a.store.Order(r.Context(), id)
if errors.Is(err, ErrNotFound) {
http.Error(w, "order not found", http.StatusNotFound)
return
}
if err != nil {
a.log.Error("get order", "id", id, "err", err)
http.Error(w, "server error",
http.StatusInternalServerError)
return
}
writeJSON(w, http.StatusOK, o)
}
- The order pattern with GET only matches GET requests. For another method, the router returns 405 by itself.
- The PathValue method returns the value of a path variable. Always check it, because it comes from the user.
- When two patterns match one path, the more specific pattern wins.
- Always return after http.Error. Writing to the response again gives a “superfluous WriteHeader” warning.
The middleware chain
A middleware is a function that takes a handler and returns a new handler. It does work that all requests share, then calls the next handler:
func Logging(log *slog.Logger, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter,
r *http.Request) {
start := time.Now()
rec := &statusRecorder{ResponseWriter: w, status: 200}
next.ServeHTTP(rec, r)
log.Info("request", "method", r.Method,
"path", r.URL.Path, "status", rec.status,
"took", time.Since(start))
})
}
// statusRecorder remembers the status code for the log.
type statusRecorder struct {
http.ResponseWriter
status int
}
func (s *statusRecorder) WriteHeader(code int) {
s.status = code
s.ResponseWriter.WriteHeader(code)
}
- Code before next.ServeHTTP runs on the way in, and code after it runs on the way back.
- The order matters. The outer layer runs first. Recover must be inside Logging, so a 500 error is logged too.
- Common layers: request id, logging, recover, authentication, rate limiting and CORS.
Each request is a goroutine
The net/http server runs each connection in its own goroutine. So your handler may run thousands of times at the same moment. This is our first bug:
// Bad: a shared map changed by many goroutines
var stock = map[string]int{"shoe": 1}
func (a *API) buy(w http.ResponseWriter, r *http.Request) {
sku := r.PathValue("sku")
if stock[sku] > 0 {
stock[sku]-- // two requests can both get here
}
}
- Two requests read “1 left” at the same time, both pass the check, and both sell.
- Concurrent writes to a map can even stop the whole process with a fatal error.
- Anything shared between requests (handler fields, global variables, caches) must be read-only, or protected with a mutex or the sync/atomic types.
- The real stock must be reduced in the database with a conditional update. A mutex only works inside one pod.
Run your tests with the race flag. The race detector finds this kind of bug in concurrent tests.
Reading JSON safely
Our fourth bug was a huge body. Never read a request body without a limit:
func (a *API) createOrder(w http.ResponseWriter,
r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, 1<<20) // 1 MB
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
var in NewOrder
if err := dec.Decode(&in); err != nil {
http.Error(w, "bad JSON", http.StatusBadRequest)
return
}
if len(in.Items) == 0 {
http.Error(w, "no items",
http.StatusUnprocessableEntity)
return
}
o, err := a.store.Create(r.Context(), in)
if err != nil {
http.Error(w, "server error",
http.StatusInternalServerError)
return
}
writeJSON(w, http.StatusCreated, o)
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(v)
}
- The MaxBytesReader function stops reading with an error after 1 MB.
- The DisallowUnknownFields method rejects misspelled fields, instead of silently ignoring them.
- Set headers before WriteHeader. Changing a header after it has no effect.
- Validate the input after Decode. Valid JSON can still contain meaningless data.
Server timeouts
The http.ListenAndServe function makes a server with no timeouts at all. A slow or malicious client can keep connections open forever. Always build an http.Server with timeouts:
srv := &http.Server{
Addr: ":8080",
Handler: api.Routes(),
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 10 * time.Second,
WriteTimeout: 30 * time.Second,
IdleTimeout: 60 * time.Second,
}
- ReadHeaderTimeout limits reading the headers. It stops the Slowloris attack, which sends headers very slowly.
- ReadTimeout limits reading the whole request, including the body.
- WriteTimeout limits writing the response. It must be longer than your slowest normal endpoint.
- IdleTimeout says how long an idle keep-alive connection stays open.
The HTTP client
Our third bug came from the client. The default http.DefaultClient also has no timeout:
// One client for the whole service, made at startup.
var payClient = &http.Client{Timeout: 10 * time.Second}
req, err := http.NewRequestWithContext(ctx, "POST", url, body)
if err != nil {
return err
}
resp, err := payClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
- Make one shared client and reuse it. The client keeps connections and reuses them.
- Build the request with a context, so a cancelled user request also stops the outside call.
- Always close the response body, even when the status code is an error. An unclosed body holds the connection.
The database connection pool
The sql.DB type is not one connection. It is a pool of connections, and it is safe for concurrent use. Make it once at startup and pass it everywhere:
db, err := sql.Open("pgx", os.Getenv("DATABASE_URL"))
if err != nil {
return err
}
db.SetMaxOpenConns(20)
db.SetMaxIdleConns(20)
db.SetConnMaxLifetime(30 * time.Minute)
- Without SetMaxOpenConns, the number of connections has no limit. Under load you may go over the connection limit of the database.
- Count the limit with the number of pods. 10 pods times 20 connections is 200 database connections.
- Always call rows.Close. Each open rows value has borrowed one connection from the pool.
Graceful shutdown
Our second bug happened on every deploy. Kubernetes sends SIGTERM to stop a pod. If the program does not catch it, it exits at once and running requests are cut:
func run(api *API, ready *atomic.Bool) error {
srv := newServer(api) // the http.Server with timeouts above
ctx, stop := signal.NotifyContext(context.Background(),
syscall.SIGTERM, os.Interrupt)
defer stop()
errCh := make(chan error, 1)
go func() { errCh <- srv.ListenAndServe() }()
ready.Store(true)
select {
case err := <-errCh:
return err // could not start, e.g. port in use
case <-ctx.Done():
}
ready.Store(false) // readyz now returns 503
time.Sleep(5 * time.Second) // let the load balancer notice
shutCtx, cancel := context.WithTimeout(
context.Background(), 20*time.Second)
defer cancel()
return srv.Shutdown(shutCtx)
}
- The signal.NotifyContext function gives a context that is cancelled by SIGTERM.
- The readyz endpoint now returns 503. Kubernetes takes the pod out of the Service endpoints.
- Waiting a few seconds is needed, because removing the pod from the load balancer happens at the same time as SIGTERM, with a small delay.
- The Shutdown method stops accepting new connections and waits until running requests finish, up to the limit of shutCtx.
- All the waits together must be shorter than the Kubernetes grace period (30 seconds by default). After that, Kubernetes sends SIGKILL.
Common mistakes
| Mistake | Result | The right way |
|---|---|---|
| Using http.ListenAndServe | The server has no timeouts. | An http.Server with ReadHeaderTimeout and the others |
| Using http.DefaultClient or http.Get | An outside call can hang forever. | One shared client with a Timeout and a context |
| Not closing the response body on the error path | A connection leak | A deferred resp.Body.Close right after Do |
| A shared map or variable without a lock | A data race and double selling | A lock, atomic, or the database |
| Reading the body without a limit | Out of memory from one big request | The MaxBytesReader function |
| Forgetting return after http.Error | The response is written twice. | Always return after writing an error. |
| Exiting at once on SIGTERM | 502 errors on every deploy | NotifyContext and Shutdown |
| Making an sql.DB per request | Connections run out. | One pool at startup |
Summary in seven lines
- Everything in net/http is a handler: handlers, the router and middleware.
- Since Go 1.22 the standard router understands methods and path variables.
- Each request runs in its own goroutine. Protect shared data and run tests with the race flag.
- Read the body with a limit, validate the input, and return after writing an error.
- The default server and client have no timeouts. Always set them yourself.
- Make one sql.DB and one http.Client for the whole program, and set a connection limit.
- On SIGTERM, report not ready, wait a little, and shut down gracefully with Shutdown.