System Design

G19

Libraries that matter

A Go backend needs few libraries. Here is each one with a verdict, a reason and its current version, and the standard-library code for each row where the standard library wins.

Not startedSaved in this browser only.
  1. 1Each dependency needs a reason that the standard library cannot meet. Routing and test assertions no longer pass that test.
  2. 2Add a library for a contract or a hard algorithm: pgx, sqlc, connect-go, x/sync, JWT parsing.
  3. 3Pin security options yourself. A library default is not your threat model.
  4. 4A version below 1.0 is a reason to pin, not a reason to refuse.
G19
    A

    The trap

    the standard router, a real run
    two routes that overlapgo
    package main
    
    import (
      "fmt"
      "net/http"
      "strings"
    )
    
    func ok(http.ResponseWriter, *http.Request) {}
    
    func main() {
      defer func() {
        // The first line of the panic names source files. Skip it.
        _, why, _ := strings.Cut(fmt.Sprint(recover()), "\n")
        fmt.Println("panic:")
        fmt.Println(why)
      }()
      mux := http.NewServeMux()
      mux.HandleFunc("GET /items/{id}"1, ok)
      fmt.Println("first route added")
      mux.HandleFunc("GET /{kind}/7"2, ok)
      fmt.Println("second route added")
    }
    1. 1Matches /items/7, and /items/x.
    2. 2Also matches /items/7. Neither pattern is more specific, so this line panics.
    recorded outputoutput
    first route added
    panic:
    GET /{kind}/7 and GET /items/{id} both match some paths, like "/items/7".
    But neither is more specific than the other.
    GET /{kind}/7 matches "/kind/7", but GET /items/{id} doesn't.
    GET /items/{id} matches "/items/id", but GET /{kind}/7 doesn't.
    • Moving to ServeMux from a router that takes the first match can show conflicts that were silent.
    • The panic runs at startup, so a test that builds the router finds it.
    • A literal beats a wildcard, so /items/new and /items/{id} can live together.

    ServeMux checks routes when you register them. Two patterns with no winner panic at startup, so a conflict cannot reach production.

    B

    The status table

    versions and dates from the Go module proxy, 31 October 2026
    library, latest releaseverdict and reason
    pgx
    v5.12.0, Oct 2026
    Use
    The Postgres driver: pool, COPY, batches, LISTEN, native types (G17).
    sqlc
    v1.31.1, Apr 2026
    Use
    Generates typed Go from SQL, and checks queries against the schema before run time.
    goose
    v3.29.0, Oct 2026
    Use
    Plain SQL files, embedded in the binary, with an advisory lock.
    Atlas
    v1.3.0, Jul 2026
    For diffed schemas
    Plans a migration from a desired schema. The community edition lacks down migrations, views and triggers; lint needs a login.
    connect-go v2
    v2.0.2, Oct 2026
    Use for new code
    A schema, generated clients, and Connect, gRPC and gRPC-Web on one handler (G18).
    connect-go v1
    v1.21.1, Oct 2026
    Existing code
    Bug fixes and security patches only. New features go to v2.
    Vanguard
    v0.5.0, Oct 2026
    When REST clients stay
    Serves one handler as REST too, from google.api.http rules. The version is below 1.0, so pin it.
    chi
    v5.5.0, Oct 2026
    Prefer the stdlib
    ServeMux has methods and wildcards. chi stays worth it for deep route trees with many middleware groups.
    x/sync
    v0.24.0, Sep 2026
    Use
    errgroup, semaphore and singleflight have no standard equivalent (G12).
    x/time/rate
    v0.16.0, Aug 2026
    Use
    A token bucket with Wait and Allow. For a single process only (G12).
    testcontainers-go
    v0.44.0, Aug 2026
    When CI has Docker
    A real Postgres per test run. Slower than a shared server, and it needs a container runtime.
    OpenTelemetry
    v1.47.0, Oct 2026
    Use
    The vendor-neutral API for traces and metrics. Traces and metrics are stable; logs are a release candidate.
    golang-jwt
    v5.3.1, Jan 2026
    Use, with pinned options
    Do not write JWT parsing yourself. Pin the method, issuer and audience (panel J).
    testify
    v1.12.1, Aug 2026
    Prefer the stdlib
    Three small helpers cover most of it, with no dependency and a better failure line.

    All GitHub-hosted projects here were unarchived with commits in October 2026, checked on the same day. A red mark means prefer the standard library: the project itself is healthy.

    I keep the list short. Every row has a reason, and the standard library wins wherever it now covers the need.

    C

    chi against the standard library

    what each one gives
    needServeMuxchi
    Method match1.22Yes
    Wildcards1.22Yes
    405 with AllowYesYes
    Matched route in logsr.Pattern, 1.23Yes
    Middleware stackChain, 3 linesYes
    Route groupsA sub-muxYes
    Regex in a path segmentNoYes
    A dependencyNoneOne small module

    Both use http.Handler, so middleware moves across unchanged.

    I start on ServeMux. I move to chi when route groups with their own middleware fill the file, and that move is small.

    D

    Routes, with no dependency

    tested
    NewRoutergo
    // NewRouter covers the routes most APIs need with no dependency. Methods,
    // wildcards and most-specific-wins matching are in net/http since Go 1.22.
    func NewRouter(log *slog.Logger, key string) http.Handler {
      mux := http.NewServeMux()
      mux.HandleFunc("GET /{$}"1, show("home"))
      mux.HandleFunc("GET /items/{id}", show("item"))
      mux.HandleFunc("GET /items/new"2, show("new item form"))
      mux.HandleFunc("POST /items", show("create item"))
      mux.HandleFunc("GET /files/{path...}"3, show("file"))
      mux.Handle("/admin/", http.StripPrefix("/admin", admin(key))4)
      return Chain(mux, Logged(log))
    }
    
    func show(name string) http.HandlerFunc {
      return func(w http.ResponseWriter, r *http.Request) {
        id, path := r.PathValue("id"), r.PathValue("path")
        fmt.Fprintf(w, "%s id=%q path=%q", name, id, path)
      }
    }
    1. 1The exact root. A bare "/" is a subtree that catches every path.
    2. 2A literal beats the wildcard route above, in any order.
    3. 3A final wildcard takes the rest of the path, with its slashes.
    4. 4A route group: the inner router sees /users/7.

    Methods, wildcards and most-specific-wins are in net/http. r.PathValue reads a wildcard.

    E

    Middleware, in 3 lines

    tested
    Chain, Loggedgo
    // Chain applies middleware so that the first one listed runs first. This is
    // what chi's Use does, in 3 lines.
    func Chain(h http.Handler, mw ...Middleware) http.Handler {
      for _, m := range slices.Backward(mw)1 {
        h = m(h)
      }
      return h
    }
    
    // Logged logs each request. r.Pattern2 is the route that matched, so the log
    // groups requests by route and not by raw path.
    func Logged(log *slog.Logger) Middleware {
      return func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
          start := time.Now()
          next.ServeHTTP(w, r)
          log.Info("request", "pattern", r.Pattern,
            "took", time.Since(start))
        })
      }
    }
    1. 1Go 1.23. The last middleware wraps first, so the first one listed runs first.
    2. 2Go 1.23. Logs and metrics group by route. A raw path has too many values.

    Middleware is a function from Handler to Handler. Chain applies a list, and that is all of chi.Use I need here.

    F

    A route group

    tested
    RequireKey, admingo
    // RequireKey is a middleware for one group of routes.
    func RequireKey(key string) Middleware {
      return func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
          if r.Header.Get("X-Api-Key") != key {
            http.Error(w, "no key", http.StatusUnauthorized)
            return
          }
          next.ServeHTTP(w, r)
        })
      }
    }
    
    // admin is a route group: its own mux with its own middleware.
    func admin(key string) http.Handler {
      mux := http.NewServeMux()
      mux.HandleFunc("GET /users/{id}", show("admin user"))
      return Chain(mux, RequireKey(key))1
    }
    1. 1This middleware covers the group only.

    chi writes this as r.Route with r.Use. The mechanism is the same: one handler wraps another.

    A group is a smaller ServeMux with its own middleware, mounted under a prefix.

    G

    See it: the router's decisions

    recorded: each answer is a real request

    GET /items/7 : 200

    r.Pattern GET /items/{id}

    body item id="7" path=""

    The most specific route that matches wins.

    405 comes free, and the most specific pattern wins. I log r.Pattern, so metrics stay grouped by route.

    H

    testify against the standard library

    prefer the standard library
    testifystandard library
    assert.Equalif got != want, or equal[T]
    assert.Equal on slicesslices.Equal, or deepEqual
    assert.ElementsMatchslices.Sort, then slices.Equal
    require.NoErrort.Fatalf, or noError
    assert.ErrorIserrors.Is
    assert.ErrorAserrors.AsType[T] (1.26)
    suite.Suitet.Run, t.Cleanup
    mock.MockA small fake that implements the interface

    Keep testify where a test suite already uses it. A rewrite gains little.

    Three helpers replace most of testify in my tests. They add no dependency, and each failure points at the right line.

    I

    Three helpers and a table test

    tested
    test helpersgo
    // equal fails the test with both values. t.Helper makes the failure point
    // at the caller, which is the line the reader needs.
    func equal[T comparable](t *testing.T, got, want T) {
      t.Helper()1
      if got != want {
        t.Errorf("got %v, want %v", got, want)
      }
    }
    
    // deepEqual is for slices, maps and structs that hold them.
    func deepEqual[T any](t *testing.T, got, want T) {
      t.Helper()
      if !reflect.DeepEqual(got, want)2 {
        t.Errorf("got %+v, want %+v", got, want)
      }
    }
    
    // noError stops the test, as require.NoError does, because the next lines
    // use the result.
    func noError(t *testing.T, err error) {
      t.Helper()
      if err != nil {
        t.Fatalf3("unexpected error: %v", err)
      }
    }
    1. 1The failure reports the caller's line, not this one.
    2. 2A nil slice and an empty slice differ here (see the drill).
    3. 3Stops this test. t.Errorf continues, so one run shows many failures.
    TestRoutergo
    func TestRouter(t *testing.T) {
      log := slog.New(slog.NewTextHandler(io.Discard, nil))
      srv := httptest.NewServer(NewRouter(log, "k"))
      defer srv.Close()
    
      tests := []struct {
        name, method, path string
        wantStatus         int
        wantBody           string
      }{
        {"wildcard", "GET", "/items/7", 200, `item id="7"`},
        {"literal wins", "GET", "/items/new", 200, `new item form`},
        {"rest of path", "GET", "/files/a/b.txt", 200, `file id=""`},
        {"wrong method", "DELETE", "/items/7", 405, ""},
        {"exact root only", "GET", "/nope", 404, ""},
        {"group needs key", "GET", "/admin/users/7", 401, ""},
      }
      for _, tt := range tests {
        t.Run(tt.name1, func(t *testing.T) {
          req, err := http.NewRequestWithContext(t.Context(),
            tt.method, srv.URL+tt.path, nil)
          noError(t, err)
          res, err := srv.Client().Do(req)
          noError(t, err)
          defer res.Body.Close()2
          body, err := io.ReadAll(res.Body)
          noError(t, err)
          equal(t, res.StatusCode, tt.wantStatus)
          equal(t, strings.HasPrefix(string(body), tt.wantBody), true)
        })
      }
    }
    1. 1Each row is a subtest, so go test -run can pick one.
    2. 2Closure scope: this runs when the subtest ends.

    t.Helper makes the failure point at the caller. Fatal stops a test when the next line needs the value.

    J

    golang-jwt: pin every option

    tested
    Verifygo
    // Verify accepts a token only with the expected algorithm, issuer and
    // audience, and only with an expiry. Each option closes a known forgery.
    func Verify(secret []byte, token string) (*Claims, error) {
      var c Claims
      _, err := jwt.ParseWithClaims(token, &c,
        func(*jwt.Token) (any, error) { return secret, nil },
        jwt.WithValidMethods1([]string{jwt.SigningMethodHS256.Alg()}),
        jwt.WithIssuer("orders-api"),
        jwt.WithAudience("orders-web"),
        jwt.WithExpirationRequired()2,
        jwt.WithLeeway(30*time.Second)3,
      )
      if err != nil {
        return nil, fmt.Errorf("verify: %w", err)
      }
      return &c, nil
    }
    1. 1Without this, the token picks its own algorithm. The drill shows the forgery.
    2. 2The exp claim is optional by default, so a token with none never expires.
    3. 3Allows clock skew between servers.
    tokenVerify says
    alg nonetoken signature is invalid: signing method none is invalid
    HS512, right keytoken signature is invalid: signing method HS512 is invalid
    wrong keytoken signature is invalid: signature is invalid
    expired an hour agotoken has invalid claims: token is expired
    no expirytoken has invalid claims: token is missing required claim: exp claim is required
    wrong issuertoken has invalid claims: token has invalid issuer
    wrong audiencetoken has invalid claims: token has invalid audience

    Each row is a real token. errors.Is with jwt.ErrTokenExpired finds the one case a client can fix with a refresh.

    I pin the method, issuer and audience, and I require an expiry. The token's own header never picks the key.

    K

    x/sync and x/time/rate

    what the standard library lacks
    needusestdlib option
    Wait for goroutinessync.WaitGroup.GoThis one, 1.25
    First error, cancel the resterrgroupNo
    Limit, count 1 eachchan struct{}This one
    Limit with weights and ctxsemaphoreNo
    Share one call among callerssingleflightNo
    Token bucketrate.LimiterNo

    Code for each one is on G12.

    WaitGroup.Go waits. errgroup also returns the first error and cancels the rest, so I use it when a goroutine can fail.

    L

    Migrations and test databases

    what decides
    questionchoose
    You write each migration by handgoose
    You want a plan from a target schemaAtlas
    A mix of bothAtlas writes goose files through its goose format
    CI has Docker, tests need isolationtestcontainers-go
    Tests share a local serverOne database per package
    A mock of the databaseIt hides real behavior

    The tests behind G17 use one database per package on one server, so they need no container.

    I use goose until I need a planner. For tests I use a real Postgres, in a container on CI or a shared server locally.

    M

    OpenTelemetry

    what to wire
    layerhowversion
    RPC server, clientotelconnectv0.12.0
    Plain HTTPotelhttpContrib module
    pgxA pgx.QueryTracer, as in the G17 count testYour code, or a contrib tracer
    Your logslog/slogStandard library

    The current otelconnect and Vanguard releases depend on connect-go v2. Signals are on O3.

    I instrument at the edges: the HTTP or RPC layer and the database driver. A span per function adds cost and hides the signal.

    N

    New in recent Go

    checked against each release's notes
    sincewhat changedwhich library it replaces
    1.21log/slog, slices, maps, cmp.Most logging wrappers, and x/exp slices.
    1.22ServeMux methods and wildcards.Routers, for most APIs.
    1.23Request.Pattern. iter, and slices.Backward.Router-specific route labels for metrics.
    1.24T.Context and B.Context. Server.Protocols.h2c wrappers from x/net.
    1.25sync.WaitGroup.Go. testing/synctest. http.CrossOriginProtection.errgroup with no errors. CSRF token middleware, for many apps.
    1.26errors.AsType. ServeMux slash redirects use 307. slog.NewMultiHandler.Hand-written log fan-out.
    1.27The uuid package, with versions 4 and 7. encoding/json/v2.google/uuid for new code. Third-party JSON for stricter decoding.
    O

    In the round

    45 minutes of build, 45 minutes of talk
    whenthe momentwhat to do or say
    buildYou need a router.ServeMux. Type no go get in the first 45 minutes.
    buildYou need assertions.The 3 helpers fit in a minute. A table test proves more than a library call.
    talk"What would you add for production?"pgx with sqlc and goose, then OpenTelemetry at the edges. Give one reason for each.
    talk"Why not an ORM?"sqlc keeps the SQL visible, and the compiler checks it. An ORM hides the N+1 and the lock.
    talk"How do you judge a dependency?"What it replaces, its maintainers, its transitive modules, and how you leave it.
    talk"How do you handle JWTs?"Pin the algorithm, issuer and audience, require an expiry, and keep the lifetime short.

    In the build I use the standard library only. In the talk I name the library and the reason for each step toward production.

    P

    Drill

    each answer is the output of a real run

    0 of 10 known

    1. Predict the output. GET and PUT routes exist for one path.

      package main
      
      import (
        "fmt"
        "net/http"
        "net/http/httptest"
      )
      
      func ok(http.ResponseWriter, *http.Request) {}
      
      func probe(h http.Handler, method, path string) {
        rec := httptest.NewRecorder()
        h.ServeHTTP(rec, httptest.NewRequest(method, path, nil))
        fmt.Printf("%s %s: %d %s\n", method, path, rec.Code,
          rec.Header().Get("Allow")+rec.Header().Get("Location"))
      }
      
      func main() {
        mux := http.NewServeMux()
        mux.HandleFunc("GET /items/{id}", ok)
        mux.HandleFunc("PUT /items/{id}", ok)
        probe(mux, "DELETE", "/items/7")
        probe(mux, "HEAD", "/items/7")
        probe(mux, "GET", "/items")
      }
    2. Predict the output.

      package main
      
      import (
        "fmt"
        "net/http"
        "net/http/httptest"
      )
      
      func ok(http.ResponseWriter, *http.Request) {}
      
      func probe(h http.Handler, method, path string) {
        rec := httptest.NewRecorder()
        h.ServeHTTP(rec, httptest.NewRequest(method, path, nil))
        fmt.Printf("%s %s: %d %s\n", method, path, rec.Code,
          rec.Header().Get("Allow")+rec.Header().Get("Location"))
      }
      
      func main() {
        mux := http.NewServeMux()
        mux.HandleFunc("GET /docs/", ok)
        mux.HandleFunc("GET /items/{$}", ok)
        probe(mux, "GET", "/docs")
        probe(mux, "GET", "/docs/a/b")
        probe(mux, "GET", "/items/")
        probe(mux, "GET", "/items/7")
      }
    3. Predict the output. The request goes through two routers.

      package main
      
      import (
        "fmt"
        "net/http"
        "net/http/httptest"
      )
      
      func main() {
        inner := http.NewServeMux()
        inner.HandleFunc("GET /users/{id}", func(w http.ResponseWriter,
          r *http.Request) {
          fmt.Println("path:", r.URL.Path, "id:", r.PathValue("id"))
        })
        outer := http.NewServeMux()
        outer.Handle("/v1/", http.StripPrefix("/v1", inner))
      
        r := httptest.NewRequest("GET", "/v1/users/7", nil)
        outer.ServeHTTP(httptest.NewRecorder(), r)
        fmt.Println("after:", r.URL.Path, "id:", r.PathValue("id"))
      }
    4. Predict the output. The path holds an escaped slash.

      package main
      
      import (
        "fmt"
        "net/http"
        "net/http/httptest"
      )
      
      func main() {
        mux := http.NewServeMux()
        mux.HandleFunc("GET /items/{id}", func(w http.ResponseWriter,
          r *http.Request) {
          fmt.Printf("%q %q\n", r.PathValue("id"), r.PathValue("ID"))
        })
        mux.ServeHTTP(httptest.NewRecorder(),
          httptest.NewRequest("GET", "/items/a%2Fb", nil))
      }
    5. Predict the output.

      package main
      
      import (
        "fmt"
        "reflect"
        "slices"
      )
      
      func main() {
        var a []int
        b := []int{}
        fmt.Println(a == nil, b == nil)
        fmt.Println(reflect.DeepEqual(a, b))
        fmt.Println(slices.Equal(a, b))
      }
    6. Predict the output. Both values are the same instant.

      package main
      
      import (
        "fmt"
        "reflect"
        "time"
      )
      
      func main() {
        a := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
        b := a.In(time.FixedZone("IST", 19800))
        fmt.Println(a == b)
        fmt.Println(reflect.DeepEqual(a, b))
        fmt.Println(a.Equal(b))
      }
    7. Predict the output.

      package main
      
      import (
        "errors"
        "fmt"
        "io/fs"
      )
      
      func main() {
        err := fmt.Errorf("load config: %w", fs.ErrNotExist)
        fmt.Println(err == fs.ErrNotExist)
        fmt.Println(errors.Is(err, fs.ErrNotExist))
        fmt.Println(err.Error() == fs.ErrNotExist.Error())
      }
    8. Predict the output. The token has alg none and no signature.

      package main
      
      import (
        "fmt"
      
        "github.com/golang-jwt/jwt/v5"
      )
      
      func main() {
        claims := jwt.MapClaims{"sub": "ada"}
        token := jwt.NewWithClaims(jwt.SigningMethodNone, claims)
        s, err := token.SignedString(jwt.UnsafeAllowNoneSignatureType)
        if err != nil {
          panic(err)
        }
        _, err = jwt.Parse(s, func(*jwt.Token) (any, error) {
          return []byte("secret"), nil
        })
        fmt.Println(err)
      }
    9. Predict the output. The key function trusts the alg header.

      package main
      
      import (
        "crypto/ed25519"
        "crypto/rand"
        "fmt"
      
        "github.com/golang-jwt/jwt/v5"
      )
      
      func main() {
        // The server signs with EdDSA. Its public key is public.
        public, _, err := ed25519.GenerateKey(rand.Reader)
        if err != nil {
          panic(err)
        }
        // The attacker signs with HS256, using the public key as the secret.
        forged := jwt.NewWithClaims(jwt.SigningMethodHS256,
          jwt.MapClaims{"sub": "attacker"})
        s, err := forged.SignedString([]byte(public))
        if err != nil {
          panic(err)
        }
        key := func(t *jwt.Token) (any, error) {
          if t.Method.Alg() == "HS256" {
            return []byte(public), nil
          }
          return public, nil
        }
        _, err = jwt.Parse(s, key)
        fmt.Println("no pinned method:", err)
        _, err = jwt.Parse(s, key, jwt.WithValidMethods([]string{"EdDSA"}))
        fmt.Println("pinned to EdDSA:", err)
      }
    10. Predict the output.

      package main
      
      import (
        "fmt"
        "time"
        "uuid"
      )
      
      func main() {
        a := uuid.NewV7()
        time.Sleep(2 * time.Millisecond)
        b := uuid.NewV7()
        s := a.String()
        fmt.Println(len(s), string(s[14]))
        fmt.Println(a.Compare(b) < 0)
        _, err := uuid.Parse("not-a-uuid")
        fmt.Println(err != nil)
      }
    Q

    Numbers to say

    measured with testing.B
    route lookup
    145 ns with 101 routes.
    2 wildcards
    245 ns.
    2 middleware
    63.3 ns for the chain.
    direct call
    1.4 ns.

    Routing costs under 1 µs, and one query costs about 50 µs (G17). Router speed does not decide this choice. Go 1.27.3, GOMAXPROCS 16, median of 3 interleaved runs, on a busy machine.