Skip to content

Lesson 4 of 9 · 27m

Timeouts, Contexts, and the Discipline of Giving Up

Set server, client, and dependency deadlines deliberately so slow work cannot consume every goroutine, socket, and database connection.

Production services rarely die because code is slow. They die because slow code waits forever. One dependency stalls, handlers pile up, goroutines multiply, sockets stay open, memory climbs, and the health check fails because nothing healthy remains. Go already wires cancellation into the request lifecycle. Respect it all the way down.

Server timeouts are different controls

http.Server has several knobs and they are not interchangeable:

srv := &http.Server{
    Addr:              ":8080",
    Handler:           handler,
    ReadHeaderTimeout: 5 * time.Second,
    ReadTimeout:       10 * time.Second,
    WriteTimeout:      20 * time.Second,
    IdleTimeout:       60 * time.Second,
}

ReadHeaderTimeout defends against slow header dribbling. WriteTimeout covers response writing and can kill legitimate streaming. Do not blindly apply one mental model to SSE, websockets, and ordinary JSON APIs.

Request context is already cancelled — use it

When a client disconnects or the server shuts down, r.Context() is cancelled:

order, err := s.store.Order(r.Context(), id)

Do not replace it with context.Background() because cancellation caused a flaky test. If work must continue after the request ends, make that architectural choice explicit and move it to a queue or background job.

Bound every dependency call

Every network or database operation needs a deadline:

ctx, cancel := context.WithTimeout(r.Context(), 800*time.Millisecond)
defer cancel()
customer, err := s.customers.Get(ctx, customerID)

Choose deadlines from user-visible budgets. If the endpoint has a two-second budget and calls three dependencies serially, each one cannot have a two-second timeout. Arithmetic applies even when optimism is more comfortable.

Cancellation and timeout are different signals

context.Canceled usually means the caller stopped waiting. context.DeadlineExceeded means your deadline fired:

if errors.Is(err, context.DeadlineExceeded) {
    writeError(w, 504, "dependency_timeout", "dependency timed out", true)
    return
}

Log dependency name and elapsed time at the call site. “Context deadline exceeded” without a dependency label is a riddle, not telemetry.

Goroutines do not make free concurrency

Handlers already run concurrently. If you spawn more goroutines, you own their lifetime. For bounded fan-out, use errgroup and wait before returning:

g, ctx := errgroup.WithContext(r.Context())
g.Go(func() error { return s.customers.Fetch(ctx, id) })
g.Go(func() error { return s.orders.FetchRecent(ctx, id) })
if err := g.Wait(); err != nil {
    return err
}

Fire-and-forget goroutines inside requests leak work exactly when load and shutdown make ownership most important.

Field notes

  • A zero timeout often means “wait forever.” Search for it before production does.
  • Streaming endpoints need deliberate timeout treatment, not an absence of protection.
  • Cancellation is cooperative; CPU-bound code must still check context at boundaries.
  • Measure deadline failures separately from upstream 5xx responses. They have different owners.

Was this lesson helpful?

Sign in to rate