System Design

G16

HTTP

net/http runs in production as it is, but its zero values have no limits. This sheet shows the failures on real connections, and the settings that stop them.

Not startedSaved in this browser only.
  1. 1Every timeout on http.Server and http.DefaultClient is zero, and zero means no limit. Set them.
  2. 2One Transport per process. It holds the pool, and a new one per request dials every time.
  3. 3Close every response body. Read it to EOF to keep the connection.
  4. 4Stop a server with Shutdown: it stops accepting and waits for requests in flight.
G16
    A

    The trap

    the same request, with one field added
    a slow client against the zero valuego
    package main
    
    import (
      "fmt"
      "net"
      "net/http"
      "sync/atomic"
      "time"
    )
    
    func main() {
      var open atomic.Int64
      srv := &http.Server{1
        Handler: http.NotFoundHandler(),
        ConnState: func2(_ net.Conn, s http.ConnState) {
          switch s {
          case http.StateNew:
            open.Add(1)
          case http.StateClosed:
            open.Add(-1)
          }
        },
      }
      ln, _ := net.Listen("tcp", "127.0.0.1:0")
      go srv.Serve(ln)
    
      for range 100 {
        c, _ := net.Dial("tcp", ln.Addr().String())
        defer c.Close()
        c.Write([]byte("GET / HTTP/1.1\r\nHost: x\r\n"3))
      }
      time.Sleep(time.Second)4
      fmt.Println("open connections after 1 s:", open.Load())
    }
    1. 1No timeout fields. http.ListenAndServe builds the same server.
    2. 2Counts connections that the server holds open.
    3. 3The headers never end: no blank line follows. The server waits for the rest.
    4. 4The clients send nothing more.
    serverrecorded outputstatus
    http.Server{}open connections after 1 s: 100Held forever
    ReadHeaderTimeout: 200 msopen connections after 1 s: 0All closed
    • This attack is a slow-loris: many connections, each one sends a request very slowly.
    • Each held connection costs a goroutine and about 9 KB here.
    • The real limit is file descriptors. At the limit, accept fails and normal clients wait (panel Q).
    • A load balancer in front helps, but it holds the same connections unless it also has a limit.

    A server with no timeouts holds a connection for as long as a client wants. I set ReadHeaderTimeout on every server.

    B

    The model: server timeouts

    net/http, Go 1.27
    read headersread bodyhandlerwriteidleone requestReadHeaderReadHeaderTimeoutReadReadTimeoutWriteWriteTimeoutIdleIdleTimeoutEach bar is one deadline on the connection. It is absolute: bytes that trickle in do not extend it.A zero value means no deadline. IdleTimeout falls back to ReadTimeout when it is zero.
    • WriteTimeout starts when the headers end, so it also limits the handler.
    • The TLS handshake uses the smallest of the three positive read and write limits.
    • http.NewResponseController can change a deadline for one request, for example a long download.

    ReadHeaderTimeout covers the headers, ReadTimeout adds the body, WriteTimeout covers the response, and IdleTimeout covers keep-alive.

    C

    Which field stops which attack

    recorded: connections held of 10 after 700 ms, limit 150 ms
    server setsslow headersslow bodyidle keep-aliveslow reader
    all zero10101010
    ReadHeaderTimeout0101010
    and ReadTimeout00010
    and WriteTimeout0000
    • Each row adds one field to the row above it.
    • The two slow attacks send a few bytes every 40 ms. The deadline is absolute, so this does not extend it.
    • ReadTimeout also stops the idle attack, because IdleTimeout falls back to it. Set IdleTimeout too.
    • ReadTimeout limits uploads. For a large upload, use ReadHeaderTimeout and a deadline in the handler.

    Each attack needs its own field. ReadHeaderTimeout alone leaves slow bodies, idle connections and slow readers open.

    D

    ServeMux routing

    since Go 1.22
    patternmatches
    GET /items/{id}One segment. Read it with r.PathValue("id"). GET also matches HEAD.
    /files/{path...}The rest of the path, slashes included.
    /static/A subtree: everything under it.
    /{$}Only the root path.
    example.com/That host. A host pattern wins over a pattern with no host.
    ruleresult
    /items/new against /items/{id}The literal wins.
    GET /x against /xThe method wins.
    Two patterns overlap, neither is more specificPanic at registration.
    Path matches, method does not405 with an Allow header.
    /x when only /x/ exists307 to /x/, since Go 1.26.

    GET /items/{id} and /items/new conflict: one has the method, the other has the literal. Our first draft of the drill panicked on this pair.

    routesgo
    // Routes builds the handler for the service.
    func Routes(s *Store, log *slog.Logger) http.Handler {
      mux := http.NewServeMux()
      mux.HandleFunc("GET /items/{id}", s.get)
      mux.HandleFunc("GET /items/new"1, s.form)
      mux.HandleFunc("POST /items", s.create)
      mux.HandleFunc("GET /report", s.slow)
      mux.HandleFunc("GET /files/{path...}2", s.file)
      mux.HandleFunc("GET /{$}3", s.home)
      return Chain(mux, Recover(log), Logging(log))4
    }
    
    func (s *Store) get(w http.ResponseWriter, r *http.Request) {
      s.mu.Lock()
      item, ok := s.items[r.PathValue("id")5]
      s.mu.Unlock()
      if !ok {
        http.Error(w, "no such item", http.StatusNotFound)
        return
      }
      writeJSON(w, http.StatusOK, item)
    }
    1. 1More specific than GET /items/{id}, so registration order does not matter.
    2. 2A wildcard for the rest of the path. It must be the last segment.
    3. 3Without it, "GET /" would be a subtree and would match every GET.
    4. 4Middleware wraps the whole mux. See panel E.
    5. 5The value of the wildcard, since Go 1.22.

    The most specific pattern wins, and a conflict panics at startup, so the routing table cannot be ambiguous at run time.

    E

    Middleware

    tested
    middlewarego
    // Middleware wraps one handler in another.
    type Middleware func(http.Handler) http.Handler
    
    // Chain applies mw so that the first one runs first.
    func Chain(h http.Handler, mw ...Middleware) http.Handler {
      for _, m := range slices.Backward(mw)1 {
        h = m(h)
      }
      return h
    }
    
    // statusWriter records what the handler sent.
    type statusWriter struct {
      http.ResponseWriter
      status int
    }
    
    func (w *statusWriter) WriteHeader(code int) {
      w.status = code
      w.ResponseWriter.WriteHeader(code)
    }
    
    // Unwrap lets http.ResponseController reach the real writer.
    func (w *statusWriter) Unwrap()3 http.ResponseWriter {
      return w.ResponseWriter
    }
    
    // Logging writes one line per request.
    func Logging(log *slog.Logger) Middleware {
      return func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(
          w http.ResponseWriter, r *http.Request,
        ) {
          start := time.Now()
          sw := &statusWriter{ResponseWriter: w, status: 2002}
          next.ServeHTTP(sw, r)
          log.InfoContext(r.Context(), "request",
            "pattern", r.Pattern4, "status", sw.status,
            "ms", time.Since(start).Milliseconds())
        })
      }
    }
    
    // Recover turns a panic into a 500 and a log line.
    func Recover(log *slog.Logger) Middleware {
      return func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(
          w http.ResponseWriter, r *http.Request,
        ) {
          defer func() {
            v := recover()
            if v == nil {
              return
            }
            if v == http.ErrAbortHandler5 {
              panic(v)
            }
            log.ErrorContext(r.Context(), "panic", "value", v)
            http.Error(w, "internal error", 500)6
          }()
          next.ServeHTTP(w, r)
        })
      }
    }
    1. 1Wrap from the last to the first, so the first in the list is the outermost.
    2. 2A handler that never calls WriteHeader sends 200.
    3. 3A wrapper hides Flusher and deadlines. Unwrap lets ResponseController find them.
    4. 4The matched pattern, since Go 1.23. Use it as a metric label: it has a fixed set of values.
    5. 5A handler uses this panic to abort on purpose, so pass it on.
    6. 6This has no effect on the status if the handler already wrote.

    Middleware is a function from handler to handler. The first in the list runs first, and I wrap ResponseWriter only with an Unwrap method.

    F

    A server with limits

    tested
    servergo
    // NewServer sets every limit. The zero value of each one means
    // no limit at all.
    func NewServer(
      addr string, h http.Handler, log *slog.Logger,
    ) *http.Server {
      return &http.Server{
        Addr:              addr,
        Handler:           h,
        ReadHeaderTimeout: 5 * time.Second1,
        ReadTimeout:       30 * time.Second2,
        WriteTimeout:      30 * time.Second3,
        IdleTimeout:       2 * time.Minute4,
        MaxHeaderBytes:    64 << 105,
        ErrorLog: slog.NewLogLogger(6
          log.Handler(), slog.LevelWarn),
      }
    }
    1. 1Closes the slow-loris from panel A.
    2. 2Headers and body together. Above the largest upload you accept.
    3. 3Above the slowest handler. Past it, the client gets a closed connection, not a status.
    4. 4Keep-alive connections end here. Keep it above the load balancer idle timeout.
    5. 5The default is 1 MB.
    6. 6net/http writes accept errors and panics to ErrorLog, so send them to the structured log.
    rulestatus
    Pass ctx with its own budget in each handlerApproved
    http.ListenAndServe in productionNo timeouts
    http.TimeoutHandler on a streaming routeIt buffers the response

    My constructor sets every limit, and a test fails if one is zero.

    G

    Graceful shutdown

    the program sends itself SIGTERM during a request
    shutdowngo
    // Run serves until ctx ends, then drains requests for up to
    // grace, then closes what remains.
    func Run(
      ctx context.Context, srv *http.Server, ln net.Listener,
      grace time.Duration,
    ) error {
      errc := make(chan error, 1)1
      go func() { errc <- srv.Serve(ln) }()
    
      select {
      case err := <-errc:
        return fmt.Errorf("serve: %w", err)
      case <-ctx.Done():
      }
    
      drain, cancel := context.WithTimeout(
        context.WithoutCancel(ctx)2, grace)
      defer cancel()
      if err := srv.Shutdown(drain)3; err != nil {
        return errors.Join(
          fmt.Errorf("shutdown: %w", err), srv.Close()4)
      }
      if err := <-errc; !errors.Is(err, http.ErrServerClosed5) {
        return fmt.Errorf("serve: %w", err)
      }
      return nil
    }
    1. 1One slot, so the Serve goroutine can always exit.
    2. 2ctx has already ended. The drain needs a new deadline from its values.
    3. 3Closes listeners, closes idle connections, and waits for active ones.
    4. 4The deadline passed. Close the connections that remain.
    5. 5Serve returns this after Shutdown. It is the normal case.
    recorded output, in order
    signal: terminated signal received
    shutdown: <nil>
    in-flight request: 200 OK
    serve closed: true
    new request refused: true
    • Create ctx in main with signal.NotifyContext. Since Go 1.26, context.Cause names the signal.
    • Shutdown does not cancel request contexts. To stop long handlers, connect BaseContext to your own signal.
    • Shutdown ignores hijacked connections. Close WebSockets with RegisterOnShutdown.
    • Keep the grace below the platform kill timeout. Kubernetes defaults to 30 s.

    On SIGTERM I fail readiness, call Shutdown with a deadline, and let requests in flight finish. After the deadline I call Close.

    H

    Read a body safely

    tested
    bodygo
    // ReadJSON reads one JSON value of at most MaxBody bytes.
    func ReadJSON(w http.ResponseWriter, r *http.Request, v any) error {
      r.Body = http.MaxBytesReader(w, r.Body, MaxBody)1
      dec := json.NewDecoder(r.Body)
      dec.DisallowUnknownFields()3
      if err := dec.Decode(v); err != nil {
        _, big := errors.AsType[*http.MaxBytesError](err)2
        if big {
          return ErrTooLarge
        }
        return fmt.Errorf("%w: %v", ErrInvalid, err)
      }
      if err := dec.Decode(&struct{}{})4; !errors.Is(err, io.EOF) {
        return fmt.Errorf("%w: data after the value", ErrInvalid)
      }
      return nil
    }
    1. 1Returns an error past the limit, and marks the connection to close after the response.
    2. 2The typed error survives the decoder. Answer 413.
    3. 3See G15 for why, and for the v2 form.
    4. 4Rejects data after the first value.

    The server closes r.Body itself. A handler needs no Close, and unread request data up to 256 KB is read for you.

    MaxBytesReader limits the body and tells the server to close the connection. io.ReadAll with no limit lets a client choose my memory use.

    I

    Request context

    tested
    contextgo
    // slow answers GET /report. The context ends when the client
    // leaves or when the budget ends.
    func (s *Store) slow(w http.ResponseWriter, r *http.Request) {
      ctx, cancel := context.WithTimeout(2
        r.Context()1, 2*time.Second)
      defer cancel()
    
      out, err := s.report(ctx)
      switch {
      case errors.Is(err, context.Canceled)3:
        return // The client left, so no one reads a response.
      case errors.Is(err, context.DeadlineExceeded):
        http.Error(w, "backend too slow", http.StatusGatewayTimeout4)
      case err != nil:
        http.Error(w, "backend failed", http.StatusBadGateway)
      default:
        writeJSON(w, http.StatusOK, map[string]string{"report": out})
      }
    }
    1. 1Ends when the client disconnects, when the HTTP/2 stream resets, or when ServeHTTP returns.
    2. 2A budget for this call, below WriteTimeout, so the client gets a real status.
    3. 3The client left. Do not count this as a server error.
    4. 4The budget ended first: answer 504.
    rulestatus
    Work after the response: context.WithoutCancelWith its own timeout
    Use r.Context in a goroutine that outlives the handlerIt ends at return
    Use r, w after the handler returnsNot approved

    r.Context ends when the client leaves. I add a budget and pass it to every call, so the work stops when the answer has no reader.

    J

    TLS

    tested
    tlsgo
    // ServeTLS serves HTTPS, with HTTP/2 on by default.
    func ServeTLS(
      srv *http.Server, ln net.Listener, cert tls.Certificate,
    ) error {
      srv.TLSConfig = &tls.Config{
        MinVersion:   tls.VersionTLS121,
        Certificates: []tls.Certificate{cert},
      }
      return srv.ServeTLS(ln, "", "")2
    }
    1. 1A test proves that a TLS 1.1 client fails here.
    2. 2Empty file names: the certificate comes from TLSConfig.
    rulestatus
    Use GetCertificate to rotate a certificate with no restartApproved
    Set timeouts: they also limit the handshakeApproved
    InsecureSkipVerify in productionNot approved
    Set a CipherSuites list for TLS 1.3It has no effect on 1.3

    A new HTTPS connection costs 2.22 ms here, and a reused one costs 0.07 ms. Reuse matters most with TLS.

    net/http negotiates HTTP/2 over TLS with no extra code. I set a minimum version, and I terminate at the load balancer if the platform does.

    K

    The model: the client pool

    net/http transport.go, Go 1.27
    ClientTimeoutTransport: one per processidle pool for one host, MaxIdleConnsPerHost = 2 by defaultconnconna third idle conn closesin usereadLoop, writeLoop goroutinesresp.Bodyyours until EOF or CloseBody at EOFthe connection returns to the poolClose with data leftGo 1.27 reads up to 256 KB for up to 50 ms.Past either limit, the connection closes.Neitherthe connection and its goroutines stay until the process ends
    • A client and a Transport are safe for concurrent use, so share them.
    • Each connection costs 2 goroutines in the client: readLoop and writeLoop.
    • Each host keeps 2 idle connections by default, a low limit for a busy service.

    Client is a small wrapper. Transport owns the pool. A connection returns to the pool when its body reaches EOF.

    L

    Client rules

    the idiom and the trap
    rulewhystatus
    One Transport per processIt holds the pool.Approved
    Clone DefaultTransport, then change itKeeps the proxy, dial and TLS limits.Approved
    Set Client.Timeout or a ctx deadlineThe default is none.Approved
    Raise MaxIdleConnsPerHost for one busy hostThe default of 2 forces new connections.Approved
    defer resp.Body.Close() after the err checkOn error, resp is nil.Approved
    http.Get in productionIt uses DefaultClient, with no timeout.Not approved
    A new Client or Transport per requestEach one dials, and keeps its idle connection.Not approved
    Treat err == nil as successA 500 returns nil.Not approved

    Client.Timeout includes reading the body, so a streaming download needs a ctx instead.

    The default client has no timeout, so one stuck server can stop a goroutine forever. Each call has a context or a client timeout.

    M

    One client, every body closed

    tested
    clientgo
    // NewClient returns the one client a process shares. Its
    // Transport keeps the connection pool, so create it once.
    func NewClient() *http.Client {
      t := http.DefaultTransport.(*http.Transport).Clone()1
      t.MaxIdleConns = 100
      t.MaxIdleConnsPerHost = 32
      t.ResponseHeaderTimeout2 = 5 * time.Second
      return &http.Client{Transport: t, Timeout: 10 * time.Second3}
    }
    1. 1Keeps the proxy, HTTP/2 and dial settings.
    2. 2Limits the wait for the first response byte.
    3. 3Limits the whole call, including the body.
    fetchgo
    // GetJSON fetches url into v. On every path it ends with the
    // body read and closed, so the connection returns to the pool.
    func GetJSON(
      ctx context.Context, c *http.Client, url string, v any,
    ) error {
      req, err := http.NewRequestWithContext(1
        ctx, http.MethodGet, url, nil)
      if err != nil {
        return fmt.Errorf("new request: %w", err)
      }
      resp, err := c.Do(req)
      if err != nil {
        return fmt.Errorf("get: %w", err)
      }
      defer discard(resp)2
      if resp.StatusCode != http.StatusOK3 {
        return &StatusError{resp.StatusCode}
      }
      if err := json.NewDecoder(resp.Body).Decode(v); err != nil {
        return fmt.Errorf("decode: %w", err)
      }
      return nil
    }
    
    // discard reads what is left, up to a limit, and closes. A
    // failed read costs only this connection, so it needs no report.
    func discard(resp *http.Response) {
      _, _ = io.CopyN(io.Discard, resp.Body, maxDrain)4
      resp.Body.Close()
    }
    1. 1The context can cancel the request at any stage.
    2. 2After the err check, because resp is nil on error.
    3. 3A 500 arrives here with err == nil.
    4. 4A bound: an endless body cannot hold this call.

    I build one client at startup. After each call I read what is left, up to a limit, and close the body, so the connection goes back to the pool.

    N

    Drain the body

    recorded: real connections, counted by the server
    client coderequestsopenedopen at endgoroutines
    read to EOF, then Close200113Approved
    Close only, 1 KB body200113Approved
    Close only, 1 MB body20020000Not approved
    Close only, body still arriving505000Not approved
    decode one value, then Close200113Approved
    read to EOF, no Close200113Reuses, but still call Close
    no read, no Close200200200600Not approved
    new Transport per request200200200600Not approved
    32 workers, idle limit 2100037426Not approved
    32 workers, idle limit 321000333296Approved

    Goroutines are the growth in the process: 2 in the client and 1 in the server per open connection.

    • Each opened connection costs about 0.13 ms more on loopback, and more across a network.
    • On Go 1.26 the 1 KB row opens 200 connections: we ran it. Go 1.27 opens 1.
    • The drain runs after Close returns, so a request that follows at once can dial a second connection.
    • A leak shows up as a growing connection count and goroutine count, not as an error.

    Below 256 KB, Go 1.27 drains on Close for up to 50 ms. Above that, Close drops the connection. With no Close, the connection leaks.

    O

    Retries with context

    tested on a fake clock
    retrygo
    // Retry sends req up to tries times, with exponential backoff
    // and jitter. Only an idempotent request is sent twice.
    func Retry(
      ctx context.Context, c *http.Client, req *http.Request,
      tries int,
    ) (*http.Response, error) {
      if !idempotent(req)1 {
        tries = 1
      }
      delay := 100 * time.Millisecond
      for try := 1; ; try++ {
        resp, err := send(ctx, c, req)
        if try == tries || !transient(ctx, resp, err) {
          return resp, err
        }
        wait := delay/2 + rand.N(delay/2)2
        if resp != nil {
          wait = max(wait, retryAfter(resp))3
          discard(resp)4
        }
        select {
        case <-time.After(wait):
        case <-ctx.Done():5
          return nil, context.Cause(ctx)
        }
        delay *= 2
      }
    }
    
    // send makes a fresh copy of req, with a rewound body.
    func send(
      ctx context.Context, c *http.Client, req *http.Request,
    ) (*http.Response, error) {
      r := req.Clone(ctx)6
      if req.GetBody != nil {
        body, err := req.GetBody()7
        if err != nil {
          return nil, fmt.Errorf("rewind body: %w", err)
        }
        r.Body = body
      }
      return c.Do(r)
    }
    
    func idempotent(r *http.Request) bool {
      switch r.Method {
      case http.MethodGet, http.MethodHead, http.MethodPut,
        http.MethodDelete:
        return true
      }
      return r.Header.Get("Idempotency-Key") != ""
    }
    
    func transient(
      ctx context.Context, resp *http.Response, err error,
    ) bool {
      if ctx.Err() != nil {
        return false
      }
      if err != nil {
        return true
      }
      switch resp.StatusCode {
      case 429, 502, 503, 504:8
        return true
      }
      return false
    }
    
    func retryAfter(resp *http.Response) time.Duration {
      s, err := strconv.Atoi(resp.Header.Get("Retry-After"))
      if err != nil || s < 0 {
        return 0
      }
      return time.Duration(s) * time.Second
    }
    1. 1A retry of a POST can charge twice. An Idempotency-Key makes it safe; see the design sheets.
    2. 2Jitter spreads clients that failed together.
    3. 3The server knows its own recovery time.
    4. 4Read and close before the next try, or each retry costs a connection.
    5. 5The total budget lives in ctx, not in the number of tries.
    6. 6A request is single use. Each try needs a fresh copy.
    7. 7A body is a stream. NewRequest sets GetBody for common readers, so it can rewind.
    8. 8Only statuses that can change. A 400 will fail again.

    I retry only idempotent requests, with backoff and jitter, and I stop at the context deadline. A POST needs an idempotency key first.

    P

    Test with httptest

    tested
    a table of routesgo
    func TestRoutes(t *testing.T) {
      h := newRoutes()
      tests := []struct {
        method, path, body string
        want               int
      }{
        {"POST", "/items", `{"name":"pen"}`, 201},
        {"GET", "/items/1", "", 200},
        {"GET", "/items/2", "", 404},
        {"GET", "/items/new", "", 200},
        {"DELETE", "/items", "", 405},
        {"POST", "/items", `{"nam":"pen"}`, 400},
        {"POST", "/items", `{"name":"a"} x`, 400},
      }
      for _, tt := range tests {
        t.Run(tt.method+" "+tt.path, func(t *testing.T) {
          w := httptest.NewRecorder()1
          r := httptest.NewRequest(2
            tt.method, tt.path, strings.NewReader(tt.body))
          h.ServeHTTP(w, r)3
          if w.Code != tt.want {
            t.Fatalf("got %d: %s", w.Code, w.Body)
          }
        })
      }
    }
    1. 1A ResponseWriter that records. No socket, so thousands of cases run in a second.
    2. 2A server-side request. Use http.NewRequest only for a client.
    3. 3Through the mux and the middleware, as in production.
    a timeout on a fake clockgo
    func TestReportHasABudget(t *testing.T) {
      synctest.Test(t, func(t *testing.T) {
        store := NewStore(
          func(ctx context.Context) (string, error) {
            <-ctx.Done()
            return "", ctx.Err()
          })
        srv := httptest.NewTestServer(1
          t, Routes(store, discardLog()))
    
        start := time.Now()
        resp, err := srv.Client().Get("http://x/report")2
        if err != nil {
          t.Fatal(err)
        }
        defer resp.Body.Close()
        if resp.StatusCode != http.StatusGatewayTimeout {
          t.Fatalf("got %d", resp.StatusCode)
        }
        if d := time.Since(start); d != 2*time.Second3 {
          t.Fatalf("took %v", d)
        }
      })
    }
    1. 1Go 1.27: an in-memory network, so synctest can see every goroutine.
    2. 2The client sends every host to this server.
    3. 3An exact check: the test takes no real time.
    tooluse it for
    NewRecorderHandler logic and routes
    NewTestServerClient code, timeouts, retries
    server.StartReal TCP: connection counts, keep-alive

    NewRecorder tests a handler with no network. NewTestServer gives a whole client and server in memory, on the fake clock of synctest.

    Q

    See it: a slow-loris stops normal requests

    recorded: a real server process and a real ramp
    ReadHeaderTimeout
    064100200

    t = 986 ms

    94 attack connections are open.

    A normal request timed out after 80 ms.

    25 of 30 normal requests failed; 10 accept errors logged.

    • Attack connections open
    • Normal request failed
    • Normal request served
    • Dashed line: the limit of 64 file descriptors
    • The server runs in its own process with a limit of 64 file descriptors. Your real limit is higher, and the shape is the same.
    • The attacker opens 10 connections every 100 ms, up to 200, and sends one header line every 200 ms.
    • With no timeout, normal requests fail from 512 ms: 25 of 30 fail, and the server logs "accept tcp 127.0.0.1:64306: accept: too many open files".
    • With a timeout of 300 ms, the open count peaks at 40, and every normal request succeeds.
    • Click a column to read that moment. Each failed request waited for a server that could not accept.

    The attack does not need bandwidth. It needs the file descriptor limit, so a short header timeout keeps the open count below it.

    R

    New in recent Go

    checked against each release's notes
    sincewhat changedwhat it means here
    1.20http.ResponseController with SetReadDeadline and SetWriteDeadline. ReverseProxy.Rewrite.Per-request deadlines with no type assertions.
    1.21ResponseController.EnableFullDuplex. ErrSchemeMismatch.An HTTP/1 handler can read and write together.
    1.22ServeMux accepts methods and wildcards. Request.PathValue and SetPathValue.Most routers are no longer needed.
    1.23Request.Pattern. Spaces or tabs after the method. ParseCookie, ParseSetCookie.Log the pattern, not the path.
    1.24Server.Protocols, Transport.Protocols and the HTTP2 config field. Unencrypted HTTP/2.h2c needs no extra module.
    1.25http.CrossOriginProtection. testing/synctest.CSRF protection with no tokens.
    1.26ServeMux trailing-slash redirects use 307. Transport.NewClientConn. HTTP2Config.StrictMaxConcurrentRequests. signal.NotifyContext sets a cause.A POST to /x keeps its method through the redirect.
    1.27HTTP/1 Response.Body drains on Close, up to a limit. Server.MaxHeaderValueCount. httptest.NewTestServer. The HTTP/2 server accepts RFC 9218 priorities, and Server.DisableClientPriority turns that off.Small unread bodies keep their connection. Timeouts can be tested on a fake clock.
    S

    In the round

    45 minutes of build, 45 minutes of talk
    whenthe momentwhat to do or say
    buildYou type main.go from the K1 kit.http.ListenAndServe is fine for 45 minutes. It has no timeouts, so name that in the talk.
    buildThe kit registers GET /items/{key}.Use the method and the wildcard. ServeMux gives you 405 and path values for free.
    buildYou add a route with a literal segment.Run the program once: a conflict panics at startup, and the message names both patterns.
    buildThe handler needs a test.A table with NewRecorder, as in the kit's do helper. Go through routes, not through the handler alone.
    talk"What do you change for production?"NewServer with timeouts, Shutdown on SIGTERM, MaxBytesReader, and a Recover and a Logging middleware.
    talk"What does a zero timeout mean?"No limit. Then name which field stops which attack: panel C has the recorded table.
    talk"The service calls another service. What do you set?"One shared client, a Timeout, a ctx with the request budget, MaxIdleConnsPerHost, and retries for idempotent calls only.
    talk"Connections to a dependency keep growing."Look for a body with no Close, a Transport per request, or an idle limit of 2 under load. Panel N has the counts.

    The kit server has no timeouts on purpose. In the talk I say so first, and I list what I would add.

    T

    Drill

    each answer is the output of a real run

    0 of 11 known

    1. Predict the output. Each line shows the pattern that matched.

      package main
      
      import (
        "fmt"
        "net/http"
        "net/http/httptest"
      )
      
      func main() {
        mux := http.NewServeMux()
        for _, p := range []string{
          "/items/{id}", "GET /items/new", "GET /items/{id}", "/",
        } {
          mux.HandleFunc(p, func(w http.ResponseWriter, r *http.Request) {
            fmt.Println(r.Method, r.URL.Path, "->", r.Pattern)
          })
        }
        for _, t := range [][2]string{
          {"GET", "/items/new"}, {"POST", "/items/new"},
          {"GET", "/items/7"}, {"PUT", "/items/7"},
          {"GET", "/items/7/parts"},
        } {
          w := httptest.NewRecorder()
          mux.ServeHTTP(w, httptest.NewRequest(t[0], t[1], nil))
        }
      }
    2. Predict the output: status, then the Allow header.

      package main
      
      import (
        "fmt"
        "net/http"
        "net/http/httptest"
      )
      
      func main() {
        mux := http.NewServeMux()
        mux.HandleFunc("GET /items", func(http.ResponseWriter, *http.Request) {})
      
        for _, method := range []string{"GET", "HEAD", "POST"} {
          w := httptest.NewRecorder()
          mux.ServeHTTP(w, httptest.NewRequest(method, "/items", nil))
          fmt.Println(method, w.Code, w.Header().Get("Allow"))
        }
      }
    3. Predict the output: path, status, Location.

      package main
      
      import (
        "fmt"
        "net/http"
        "net/http/httptest"
      )
      
      func main() {
        mux := http.NewServeMux()
        mux.HandleFunc("/static/", func(w http.ResponseWriter, r *http.Request) {
          fmt.Fprint(w, "subtree")
        })
        mux.HandleFunc("/exact/{$}", func(w http.ResponseWriter, r *http.Request) {
          fmt.Fprint(w, "exact")
        })
        for _, path := range []string{"/static/a/b", "/static", "/exact/", "/exact/x"} {
          w := httptest.NewRecorder()
          mux.ServeHTTP(w, httptest.NewRequest("GET", path, nil))
          fmt.Println(path, w.Code, w.Header().Get("Location"))
        }
      }
    4. Does this program print "registered both"? The deferred function prints whether the panic mentions a conflict.

      package main
      
      import (
        "fmt"
        "net/http"
        "strings"
      )
      
      func main() {
        defer func() {
          text := fmt.Sprint(recover())
          first, _, _ := strings.Cut(text, "\n")
          fmt.Println(strings.Contains(first, "conflicts"))
        }()
        mux := http.NewServeMux()
        mux.HandleFunc("/{a}/x", func(http.ResponseWriter, *http.Request) {})
        mux.HandleFunc("/y/{b}", func(http.ResponseWriter, *http.Request) {})
        fmt.Println("registered both")
      }
    5. Predict the output.

      package main
      
      import (
        "fmt"
        "net/http"
        "net/http/httptest"
      )
      
      func main() {
        h := func(w http.ResponseWriter, r *http.Request) {
          fmt.Fprint(w, "body")
          w.Header().Set("X-Late", "1")
        }
        srv := httptest.NewServer(http.HandlerFunc(h))
        defer srv.Close()
      
        resp, err := http.Get(srv.URL)
        if err != nil {
          panic(err)
        }
        defer resp.Body.Close()
        fmt.Println(resp.StatusCode, "X-Late:", resp.Header.Get("X-Late"))
      }
    6. Predict the output. The server answers 500.

      package main
      
      import (
        "fmt"
        "net/http"
        "net/http/httptest"
      )
      
      func main() {
        srv := httptest.NewServer(http.HandlerFunc(
          func(w http.ResponseWriter, r *http.Request) {
            http.Error(w, "boom", 500)
          }))
        defer srv.Close()
      
        resp, err := http.Get(srv.URL)
        fmt.Println(err)
        defer resp.Body.Close()
        fmt.Println(resp.StatusCode)
      }
    7. Predict the output. The client posts "hi" to each path.

      package main
      
      import (
        "fmt"
        "io"
        "net/http"
        "net/http/httptest"
        "strings"
      )
      
      func main() {
        mux := http.NewServeMux()
        mux.HandleFunc("/a", func(w http.ResponseWriter, r *http.Request) {
          http.Redirect(w, r, "/end", http.StatusFound)
        })
        mux.HandleFunc("/b", func(w http.ResponseWriter, r *http.Request) {
          http.Redirect(w, r, "/end", http.StatusTemporaryRedirect)
        })
        mux.HandleFunc("/end", func(w http.ResponseWriter, r *http.Request) {
          b, _ := io.ReadAll(r.Body)
          fmt.Fprintf(w, "%s body=%q", r.Method, b)
        })
        srv := httptest.NewServer(mux)
        defer srv.Close()
      
        for _, path := range []string{"/a", "/b"} {
          resp, _ := http.Post(srv.URL+path, "text/plain", strings.NewReader("hi"))
          b, _ := io.ReadAll(resp.Body)
          resp.Body.Close()
          fmt.Println(path, string(b))
        }
      }
    8. Predict the output.

      package main
      
      import (
        "fmt"
        "io"
        "net/http/httptest"
        "strings"
      )
      
      func main() {
        r := httptest.NewRequest("POST", "/", strings.NewReader("hello"))
        first, _ := io.ReadAll(r.Body)
        second, _ := io.ReadAll(r.Body)
        fmt.Printf("%q %q\n", first, second)
      }
    9. Predict the output. The limit is 4 bytes and the body has 10.

      package main
      
      import (
        "errors"
        "fmt"
        "io"
        "net/http"
        "net/http/httptest"
        "strings"
      )
      
      func main() {
        h := func(w http.ResponseWriter, r *http.Request) {
          r.Body = http.MaxBytesReader(w, r.Body, 4)
          b, err := io.ReadAll(r.Body)
          var tooBig *http.MaxBytesError
          fmt.Printf("%q %v\n", b, errors.As(err, &tooBig))
          http.Error(w, "too large", http.StatusRequestEntityTooLarge)
        }
        srv := httptest.NewServer(http.HandlerFunc(h))
        defer srv.Close()
      
        resp, err := http.Post(srv.URL, "text/plain", strings.NewReader("0123456789"))
        if err != nil {
          panic(err)
        }
        defer resp.Body.Close()
        fmt.Println(resp.StatusCode, "close:", resp.Close)
      }
    10. Predict the output.

      package main
      
      import (
        "errors"
        "fmt"
        "io"
        "log"
        "net/http"
        "net/http/httptest"
      )
      
      func main() {
        mux := http.NewServeMux()
        mux.HandleFunc("/boom", func(http.ResponseWriter, *http.Request) {
          panic("boom")
        })
        mux.HandleFunc("/ok", func(w http.ResponseWriter, _ *http.Request) {
          fmt.Fprint(w, "alive")
        })
        srv := httptest.NewUnstartedServer(mux)
        srv.Config.ErrorLog = log.New(io.Discard, "", 0)
        srv.Start()
        defer srv.Close()
      
        _, err := http.Get(srv.URL + "/boom")
        fmt.Println(errors.Is(err, io.EOF))
      
        resp, err := http.Get(srv.URL + "/ok")
        if err != nil {
          panic(err)
        }
        defer resp.Body.Close()
        b, _ := io.ReadAll(resp.Body)
        fmt.Println(string(b))
      }
    11. Predict the output: server timeouts, client timeouts, idle limits, then Transport timers.

      package main
      
      import (
        "fmt"
        "net/http"
      )
      
      func main() {
        var s http.Server
        fmt.Println(s.ReadHeaderTimeout, s.ReadTimeout, s.WriteTimeout, s.IdleTimeout)
      
        t := http.DefaultTransport.(*http.Transport)
        fmt.Println(http.DefaultClient.Timeout, t.ResponseHeaderTimeout)
        fmt.Println(t.MaxIdleConns, t.MaxIdleConnsPerHost, http.DefaultMaxIdleConnsPerHost)
        fmt.Println(t.IdleConnTimeout, t.TLSHandshakeTimeout)
      }
    U

    Numbers to say

    measured on loopback
    reused GET
    0.07 ms.
    new TCP
    0.20 ms, 2.8 times a reused one.
    new TLS
    2.22 ms, 30 times a reused one.
    held conn
    1 goroutine and about 9 KB, measured over 1,000 connections.
    idle limit
    2 per host by default: 374 connections for 1,000 requests, against 33 with a limit of 32.
    drain
    Up to 256 KB and 50 ms on Close, from the net/http source.

    Go 1.27.3, 8-core Intel i9 laptop, GOMAXPROCS 16, median of 3 interleaved runs of 1,000 requests, on a busy machine. Use these as orders of magnitude.