System Design

K2

Proto-first kit: buf, Connect, Vanguard

The same service as K1, defined proto first. A bare Connect API only exposes POST paths, and the round grades REST status codes, so this kit adds Vanguard. The store and the service do not change.

Not startedSaved in this browser only.
  1. 1One proto file holds the service, the validation rules and the REST paths.
  2. 2Vanguard turns google.api.http annotations into plain JSON REST, so the round can grade status codes.
  3. 3The room cut is 3,919 typed characters, against 2,559 for K1. Use it only if you rehearse it under 10 minutes.
  4. 4If you do not build with it, it is still a strong answer in the talk: how you would formalise the contract.
K2
    A

    One handler, two doors

    only the transport changes
    GET /items/aPOST /items.v1.ItemService/…VanguardJSON REST from the protoconnecthttpConnect, gRPC, gRPC-Webconnect.Server: one chain for both doorsrecovery → request ID → logging→ auth → validateAuth runs before the body is decoded.handlerhandler.goGenerated interface, plusthe error mapserviceservice.goThe same file as K1Storestore.goThe same file as K1
    • store.go and service.go are byte for byte the K1 files. The build checks this.
    • Vanguard needs no generated gateway. It reads the descriptors at run time.

    The proto file is the contract. REST and RPC clients reach one handler through one interceptor chain.

    B

    What setup costs

    computed from the files below
    filetypeddone at 500/minat 300/min
    buf.yaml1320:160:26
    buf.gen.yaml1950:391:05
    items.proto7452:093:34
    the commands762:183:50
    store.go7963:536:29
    service.go3574:367:40
    handler.go1,0446:4111:09
    main.go5747:5013:04
    Room cut, running3,9198:0113:14
    interceptors.go1,92311:4119:28
    protokit_test.go1,55214:4724:39
    K1, running2,5595:078:32

    The same typing rule as K1. Proto and YAML files count their import lines, because no editor adds those. The room cut leaves out interceptors.go and includes the 10.5 seconds the commands take on a warm machine. Arithmetic, not a measurement of a person.

    I rehearse this to under 10 minutes, or I build with K1 and bring this up in the talk.

    C

    When to use it in the room

    decide before the day
    your positionuse it to build?
    Timed from an empty folder, under 10 minutes, three days in a rowApproved
    Timed once, at 12 minutesNot approved
    Never timedNot approved
    Under 10 minutes, and the spec asks for authAdd the chain last
    You built with K1Use it in the talk

    At 300 characters a minute the room cut takes 13:04 of typing, so it misses the target. At 500, K1 leaves 2:43 more of the 45 minutes for the domain. That time is the price of the contract.

    I use the kit I have timed. An untimed kit costs more in the room than it gives back.

    D

    K1 and K2 side by side

    from the files and a timed run
    K1K2
    Server, typed2,5593,919
    Everything, typed3,7477,394
    Target from empty5 min10 min
    Modules015
    Generated lines0415
    Commands, empty build cache19.7 s52.1 s
    Commands, warm3.4 s10.5 s
    Routes live inhandler.goitems.proto
    Validation lives inGo, by handProto rules
    Error body{"error":…}{"code","message"}
    Status codesSameSame
    Typed clientsNoneGenerated
    gRPC callersNoYes

    K1 is what I type in the build. K2 is where the design goes when the service has many clients.

    E

    items.proto

    the contract
    items.protoproto
    syntax = "proto3";
    
    package items.v1;
    
    import "buf/validate/validate.proto";
    import "google/api/annotations.proto";
    
    option go_package = "github.com/rudrite/system-design/arena/protokit/gen/items/v1;itemsv1";
    
    service ItemService {
      rpc GetItem(GetItemRequest) returns (GetItemResponse) {
        option (google.api.http) = {get: "/items/{key}"};1
      }
      rpc AddItem(AddItemRequest) returns (AddItemResponse) {
        option (google.api.http) = {
          post: "/items/{key}/add"
          body: "*"2
        };
      }
    }
    
    message GetItemRequest {
      string key = 1 [(buf.validate.field).string = {
        min_len: 14
        max_bytes: 256
      }];
    }
    
    message GetItemResponse {
      int32 count = 1;3
    }
    
    message AddItemRequest {
      string key = 1 [(buf.validate.field).string = {
        min_len: 1
        max_bytes: 256
      }];
      int32 by = 2 [(buf.validate.field).int32.gte = 15];
    }
    
    message AddItemResponse {
      int32 count = 1;
    }
    
    1. 1The path variable fills the key field of the request. Vanguard reads this at run time.
    2. 2The whole JSON body maps to the remaining fields, so the client sends {"by":2}.
    3. 3int32, because proto3 JSON writes int64 as a string. K1 answers {"count":2}, and this must match.
    4. 4A protovalidate rule. The interceptor refuses the request with InvalidArgument, which is 400.
    5. 5The same rule as the by check in service.go, now visible in the contract.

    I write the proto first. It names the methods, the rules and the paths, so the interviewer can read the API before any Go exists.

    F

    buf and the commands

    five commands from empty
    buf.yamlyaml
    version: v2
    modules:
      - path: proto
    deps:
      - buf.build/bufbuild/protovalidate
      - buf.build/googleapis/googleapis
    lint:
      use:
        - STANDARD
    
    buf.gen.yamlyaml
    version: v2
    plugins:
      - local: protoc-gen-go
        out: gen
        opt: paths=source_relative
      - local: [go, run, connectrpc.com/connect/v2/cmd/[email protected]1]
        out: gen
        opt: paths=source_relative
    
    1. 1A pinned version. An older plugin on the PATH generates code that the v2 server cannot register.
    the commandsshell
    go mod init kit
    buf dep update
    buf generate
    go mod tidy
    go test -race ./...
    

    buf.gen.yaml pins the Connect plugin, because Vanguard needs Connect v2.

    G

    What the commands take

    a timed run, not typing
    from an empty foldersaved output
    go1.27.3 darwin/amd64, 16 CPUs, 15 modules
    command                      cold       warm
    go mod init kit              0.0s       0.0s
    buf dep update               0.9s       0.9s
    buf generate                19.9s       3.0s
    go mod tidy                  3.0s       2.0s
    go test -race ./...         28.3s       4.7s
    total                       52.1s      10.5s
    K1 go test -race            19.7s       3.4s
    • Cold means an empty Go build cache. Warm means the same day as a rehearsal.
    • Both runs had the module cache and the buf cache filled. An empty module cache adds downloads.
    • The test line compiles and links with -race, so most of the wait is there.

    Yesterday's run fills the caches, so the commands take seconds in the room.

    H

    handler.go

    the error map lives here
    handler.gogo
    package main
    
    import (
    	"context"
    	"errors"
    	"log/slog"
    
    	"connectrpc.com/connect/v2"
    
    	itemsv1 "github.com/rudrite/system-design/arena/protokit/gen/items/v1"
    	"github.com/rudrite/system-design/arena/protokit/gen/items/v1/itemsv1connect"
    )
    
    type handler struct {
    	itemsv1connect.UnimplementedItemServiceHandler1
    	svc *Service
    }
    
    func (h *handler) GetItem(ctx context.Context, req *itemsv1.GetItemRequest) (*itemsv1.GetItemResponse, error) {
    	item, err := h.svc.Get(ctx, req.Key)2
    	if err != nil {
    		return nil, toConnect(err)
    	}
    	return &itemsv1.GetItemResponse{Count: int32(item.Count)}, nil
    }
    
    func (h *handler) AddItem(ctx context.Context, req *itemsv1.AddItemRequest) (*itemsv1.AddItemResponse, error) {
    	item, err := h.svc.Add(ctx, req.Key, int(req.By))
    	if err != nil {
    		return nil, toConnect(err)
    	}
    	return &itemsv1.AddItemResponse{Count: int32(item.Count)}, nil
    }
    
    func toConnect(err error) error {
    	switch {
    	case errors.Is(err, ErrInvalid):
    		return connect.NewError(connect.CodeInvalidArgument, err.Error())
    	case errors.Is(err, ErrNotFound):
    		return connect.NewError(connect.CodeNotFound, err.Error())
    	case errors.Is(err, ErrConflict):
    		return connect.NewError(connect.CodeAborted3, err.Error())
    	}
    	slog.Error("internal", "err", err)4
    	return connect.NewError(connect.CodeInternal, "internal error")
    }
    
    1. 1A new method in the proto compiles at once and answers Unimplemented, which is 501.
    2. 2The same call as in K1. The key comes from the path, already validated.
    3. 3Aborted gives 409. FailedPrecondition sounds right, but it gives 400.
    4. 4Log the real error, and send a fixed message, as K1 does.

    The handler translates. It takes a typed request, calls the service, and maps each domain error to one Connect code.

    I

    Domain error to HTTP status

    every row is a test
    domainConnectstatus
    ErrInvalidInvalidArgument400
    ErrNotFoundNotFound404
    ErrConflictAborted409
    anything elseInternal500

    A proto rule that fails also gives InvalidArgument, so both paths reach 400.

    Each layer has one job: the domain names the problem, Connect names the code, and the REST layer picks the status.

    J

    Every Connect code

    through Vanguard, tested
    statusConnect codes
    400InvalidArgument, FailedPrecondition, OutOfRange
    401Unauthenticated
    403PermissionDenied
    404NotFound
    409AlreadyExists, Aborted
    429ResourceExhausted
    499Canceled
    500Internal, Unknown, DataLoss
    501Unimplemented
    503Unavailable
    504DeadlineExceeded

    I pick the code by the status I want the client to see.

    K

    interceptors.go

    one chain for both doors
    interceptors.gogo
    package main
    
    import (
    	"context"
    	"crypto/rand"
    	"log/slog"
    	"strings"
    	"time"
    
    	"connectrpc.com/connect/v2"
    	"connectrpc.com/validate"
    
    	"github.com/rudrite/system-design/arena/protokit/gen/items/v1/itemsv1connect"
    )
    
    func chain(tokens map[string]string) []connect.ServerInterceptor {
    	return []connect.ServerInterceptor{recovery, requestID, logging, auth(tokens), validate.NewServerInterceptor()}1
    }
    
    func recovery(next connect.ServerFunc) connect.ServerFunc {
    	return func(ctx context.Context, spec connect.Spec, stream connect.ServerStream) (err error) {
    		defer func() {
    			if r := recover(); r != nil {2
    				slog.Error("panic", "procedure", spec.Procedure, "value", r)
    				err = connect.NewError(connect.CodeInternal, "internal error")
    			}
    		}()
    		return next(ctx, spec, stream)
    	}
    }
    
    type idKey struct{}
    
    func requestID(next connect.ServerFunc) connect.ServerFunc {
    	return func(ctx context.Context, spec connect.Spec, stream connect.ServerStream) error {
    		info, _ := connect.CallInfoForServerContext(ctx)
    		id := info.RequestHeader().Get("X-Request-Id")
    		if id == "" {
    			id = rand.Text()
    		}
    		info.ResponseHeader().Set("X-Request-Id", id)3
    		return next(context.WithValue(ctx, idKey{}, id), spec, stream)
    	}
    }
    
    func logging(next connect.ServerFunc) connect.ServerFunc {
    	return func(ctx context.Context, spec connect.Spec, stream connect.ServerStream) error {
    		start := time.Now()
    		err := next(ctx, spec, stream)
    		slog.Info("rpc", "id", ctx.Value(idKey{}), "procedure", spec.Procedure,
    			"code", connect.CodeOf(err).String()4, "took", time.Since(start))
    		return err
    	}
    }
    
    func auth(tokens map[string]string) connect.ServerInterceptor {
    	return func(next connect.ServerFunc) connect.ServerFunc {
    		return func(ctx context.Context, spec connect.Spec, stream connect.ServerStream) error {
    			info, _ := connect.CallInfoForServerContext(ctx)
    			role, ok := tokens[strings.TrimPrefix(info.RequestHeader().Get("Authorization"), "Bearer ")]
    			if !ok {
    				return connect.NewError(connect.CodeUnauthenticated, "unknown token")5
    			}
    			if spec.Procedure == itemsv1connect.ItemServiceAddItemProcedure && role != "writer" {
    				return connect.NewError(connect.CodePermissionDenied, "writers only")6
    			}
    			return next(ctx, spec, stream)
    		}
    	}
    }
    
    1. 1The first entry is the outermost. Recovery wraps everything. Validate runs last, when the handler reads the message.
    2. 2Connect v2 has no recovery option. An interceptor surrounds the call, so a few lines do it. The client gets a fixed 500.
    3. 3Headers travel on CallInfo in v2. Vanguard copies this one to the REST response, on errors too.
    4. 4One log line per call, with the code and the ID. The tracing work in the talk starts here.
    5. 5Unknown caller: 401. The body has not been decoded yet.
    6. 6Known caller, wrong role: 403. Read the two lines together in the talk.

    Interceptors wrap the whole call, so auth can refuse a request before the server reads its body. This code uses Connect v2.

    L

    main.go and the first run

    both doors on one mux
    main.gogo
    package main
    
    import (
    	"log"
    	"net/http"
    
    	"connectrpc.com/connect/v2"
    	"connectrpc.com/connect/v2/connecthttp"
    	"connectrpc.com/vanguard"
    
    	"github.com/rudrite/system-design/arena/protokit/gen/items/v1/itemsv1connect"
    )
    
    func serve(h itemsv1connect.ItemServiceHandler, chain ...connect.ServerInterceptor3) (http.Handler, error) {
    	server := connect.NewServer(chain...)
    	itemsv1connect.RegisterItemServiceHandler(server, h)
    	mux := http.NewServeMux()
    	connecthttp.Mount(mux, server)1
    	return mux, vanguard.Mount(mux, server)2
    }
    
    func main() {
    	svc := &Service{&MemStore{items: map[string]Item{}}}
    	tokens := map[string]string{"dev-w": "writer", "dev-r": "reader"}
    	mux, err := serve(&handler{svc: svc}, chain(tokens)...)
    	if err != nil {
    		log.Fatal(err)
    	}
    	log.Fatal(http.ListenAndServe(":8080", mux))
    }
    
    1. 1Connect, gRPC and gRPC-Web, one route per procedure.
    2. 2REST from the annotations. It installs one catch-all route on "/", and the more specific routes still win.
    3. 3The chain is a parameter. For the room cut, pass only validate.NewServerInterceptor() and delete interceptors.go.
    the first runterminal
    go run .
    curl -H 'Authorization: Bearer dev-w' -d '{"by":2}' localhost:8080/items/a/add
    {"count":2}
    curl -H 'Authorization: Bearer dev-r' localhost:8080/items/a
    {"count":2}
    curl -i -H 'Authorization: Bearer dev-r' localhost:8080/items/b
    HTTP/1.1 404 Not Found
    {"code":5,"message":"not found","details":[]}

    Two Mount calls give me RPC and REST. The curl below uses a plain path and gets plain JSON.

    M

    protokit_test.go

    the REST paths and status codes
    protokit_test.gogo
    package main
    
    import (
    	"net/http"
    	"net/http/httptest"
    	"strings"
    	"sync"
    	"testing"
    )
    
    func newAPI(t testing.TB) http.Handler {
    	svc := &Service{&MemStore{items: map[string]Item{}}}
    	h, err := serve(&handler{svc: svc}, chain(map[string]string{"w": "writer", "r": "reader"})...)
    	if err != nil {
    		t.Fatal(err)
    	}
    	return h
    }
    
    func do(h http.Handler, method, path, token, body string) (int, string) {
    	r := httptest.NewRequest(method, path, strings.NewReader(body))
    	r.Header.Set("Authorization", "Bearer "+token)
    	r.Header.Set("Content-Type", "application/json")1
    	w := httptest.NewRecorder()
    	h.ServeHTTP(w, r)
    	return w.Code, strings.TrimSpace(w.Body.String())
    }
    
    func TestREST(t *testing.T) {
    	h := newAPI(t)
    	for _, c := range []struct {
    		method, path, token, body string
    		status                    int
    		want                      string
    	}{
    		{"GET", "/items/a", "nope", "", 401, "unknown token"},
    		{"POST", "/items/a/add", "r", `{"by":2}`, 403, "writers only"},2
    		{"GET", "/items/a", "r", "", 404, "not found"},
    		{"POST", "/items/a/add", "w", `{"by":2}`, 200, `{"count":2}`},
    		{"POST", "/items/a/add", "w", `{"by":0}`, 400, "by"},
    		{"POST", "/items/a/add", "w", `{"by":999}`, 409, "over the limit"},3
    		{"GET", "/items/a", "r", "", 200, `{"count":2}`},
    	} {
    		status, body := do(h, c.method, c.path, c.token, c.body)
    		if status != c.status || !strings.Contains(body, c.want) {
    			t.Errorf("%s %s: got %d %s", c.method, c.path, status, body)
    		}
    	}
    }
    
    func TestParallelAdds(t *testing.T) {
    	h := newAPI(t)
    	var wg sync.WaitGroup
    	for range 100 {4
    		wg.Go(func() { do(h, "POST", "/items/k/add", "w", `{"by":1}`) })
    	}
    	wg.Wait()
    	if _, body := do(h, "GET", "/items/k", "r", ""); body != `{"count":100}` {
    		t.Errorf("got %s", body)
    	}
    }
    
    1. 1Vanguard also reads the JSON body with the form content type that curl -d sends. A test proves this.
    2. 2A known token without the role. The next row has no such key yet, and it answers 404.
    3. 3The state rule in the service, through Aborted, to 409 on a REST path.
    4. 4Run with -race. The mutex is still the K1 mutex, so the count must be exactly 100.

    Deeper tests prove the rest. They cover each Connect code, both doors, the generated client, and 405 and 404 on unknown routes. They also cover a panic to 500, the request ID on a 401, and the room cut.

    The table test goes through the REST path for each status code. The race test fires 100 parallel adds, as in K1.

    N

    Have this ready

    the machine, the day before
    itemcheck
    bufbuf --version
    protoc-gen-go on the PATHprotoc-gen-go --version
    Network to the schema registrybuf dep update
    Module and build caches fullRun all five commands once.
    A fallbackBe ready to switch to K1 at the 10-minute mark.

    Ask at the start if generated code is allowed. Rehearse as if it is not, which means K1.

    I run the kit the night before, so the caches are full.

    O

    In the talk half

    if you built with K1
    • Say which files stay: the store and the service do not change.
    • Say what the handler becomes: a generated interface and one error map.
    • Say what you gain: a contract, typed clients and breaking-change checks.
    • Say what it costs: a generator, more modules and a slower build.
    • Name the status detail: FailedPrecondition gives 400, so a conflict uses Aborted.

    I built with the standard library for speed. To formalise the contract, I would move the same service to a proto file.

    P

    The talk map

    questions this kit invites
    the interviewer asksthe answergoes deeper
    How would you formalise the API contract?One proto file becomes the contract. buf lint checks its style, and buf breaking fails CI on an incompatible change. Clients in each language come from that one file.R3 Requirements to API
    REST clients and RPC clients. Do you write it twice?No. google.api.http annotations map each method to a path, and Vanguard serves them at run time from the descriptors. Both reach one handler and one interceptor chain.R3 Requirements to API
    How do you version it?The package name holds the version, so items.v2 can sit beside items.v1 on one server. Inside a version, I only add fields and never reuse a field number.O4 Change and migrations
    Where does validation live?Rules on one field go in the proto, so every language enforces them. Rules that need current state stay in the service, inside Update.O5 Security
    What does this cost you?A generator in the build, 15 modules to keep up to date, and a slower first build. For two endpoints that is too much. For many services and many clients, the contract pays for it.K1 The 45-minute build kit

    I answer the question, then I name the cost of my answer.

    Q

    Drill

    predict, then reveal

    0 of 8 known

    1. A bare Connect API exposes POST /items.v1.ItemService/GetItem. What does the round grade that this does not give?

    2. ErrConflict could map to CodeFailedPrecondition. What status does the client get then?

    3. You change count to int64. A client that worked with {"count":2} now fails. Why?

    4. The proto says by >= 1, and service.go still checks it. Is that dead code?

    5. Why does recovery come first in the chain and validate last?

    6. A handler returns ErrNotFound without toConnect. What does the client see?

    7. Your PATH has an older protoc-gen-connect-go. buf generate succeeds, then the build fails. Why?

    8. Vanguard installs one catch-all route. What happens to your other routes on that mux?

    R

    Numbers to say

    from the files and a timed run
    room cut
    3,919 typed characters: 7:50 at 100 words a minute.
    full kit
    7,394 typed characters: 14:47.
    K1
    2,559 typed characters: 5:07.
    commands
    52.1 s cold, 10.5 s warm.
    modules
    15, against 0 in K1.
    generated
    415 lines from one proto file.

    Timed on an 8-core Intel i9 laptop with Go 1.27.3. Your machine will differ, so time it yourself.