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.
- 1One proto file holds the service, the validation rules and the REST paths.
- 2Vanguard turns google.api.http annotations into plain JSON REST, so the round can grade status codes.
- 3The room cut is 3,919 typed characters, against 2,559 for K1. Use it only if you rehearse it under 10 minutes.
- 4If you do not build with it, it is still a strong answer in the talk: how you would formalise the contract.
- 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.
| file | typed | done at 500/min | at 300/min |
|---|---|---|---|
| buf.yaml | 132 | 0:16 | 0:26 |
| buf.gen.yaml | 195 | 0:39 | 1:05 |
| items.proto | 745 | 2:09 | 3:34 |
| the commands | 76 | 2:18 | 3:50 |
| store.go | 796 | 3:53 | 6:29 |
| service.go | 357 | 4:36 | 7:40 |
| handler.go | 1,044 | 6:41 | 11:09 |
| main.go | 574 | 7:50 | 13:04 |
| Room cut, running | 3,919 | 8:01 | 13:14 |
| interceptors.go | 1,923 | 11:41 | 19:28 |
| protokit_test.go | 1,552 | 14:47 | 24:39 |
| K1, running | 2,559 | 5:07 | 8: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.
| your position | use it to build? |
|---|---|
| Timed from an empty folder, under 10 minutes, three days in a row | Approved |
| Timed once, at 12 minutes | Not approved |
| Never timed | Not approved |
| Under 10 minutes, and the spec asks for auth | Add the chain last |
| You built with K1 | Use 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.
| K1 | K2 | |
|---|---|---|
| Server, typed | 2,559 | 3,919 |
| Everything, typed | 3,747 | 7,394 |
| Target from empty | 5 min | 10 min |
| Modules | 0 | 15 |
| Generated lines | 0 | 415 |
| Commands, empty build cache | 19.7 s | 52.1 s |
| Commands, warm | 3.4 s | 10.5 s |
| Routes live in | handler.go | items.proto |
| Validation lives in | Go, by hand | Proto rules |
| Error body | {"error":…} | {"code","message"} |
| Status codes | Same | Same |
| Typed clients | None | Generated |
| gRPC callers | No | Yes |
K1 is what I type in the build. K2 is where the design goes when the service has many clients.
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;
}
- 1The path variable fills the key field of the request. Vanguard reads this at run time.
- 2The whole JSON body maps to the remaining fields, so the client sends {"by":2}.
- 3int32, because proto3 JSON writes int64 as a string. K1 answers {"count":2}, and this must match.
- 4A protovalidate rule. The interceptor refuses the request with InvalidArgument, which is 400.
- 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.
version: v2
modules:
- path: proto
deps:
- buf.build/bufbuild/protovalidate
- buf.build/googleapis/googleapis
lint:
use:
- STANDARD
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
- 1A pinned version. An older plugin on the PATH generates code that the v2 server cannot register.
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.
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.
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")
}
- 1A new method in the proto compiles at once and answers Unimplemented, which is 501.
- 2The same call as in K1. The key comes from the path, already validated.
- 3Aborted gives 409. FailedPrecondition sounds right, but it gives 400.
- 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.
| domain | Connect | status |
|---|---|---|
| ErrInvalid | InvalidArgument | 400 |
| ErrNotFound | NotFound | 404 |
| ErrConflict | Aborted | 409 |
| anything else | Internal | 500 |
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.
| status | Connect codes |
|---|---|
| 400 | InvalidArgument, FailedPrecondition, OutOfRange |
| 401 | Unauthenticated |
| 403 | PermissionDenied |
| 404 | NotFound |
| 409 | AlreadyExists, Aborted |
| 429 | ResourceExhausted |
| 499 | Canceled |
| 500 | Internal, Unknown, DataLoss |
| 501 | Unimplemented |
| 503 | Unavailable |
| 504 | DeadlineExceeded |
I pick the code by the status I want the client to see.
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)
}
}
}
- 1The first entry is the outermost. Recovery wraps everything. Validate runs last, when the handler reads the message.
- 2Connect v2 has no recovery option. An interceptor surrounds the call, so a few lines do it. The client gets a fixed 500.
- 3Headers travel on CallInfo in v2. Vanguard copies this one to the REST response, on errors too.
- 4One log line per call, with the code and the ID. The tracing work in the talk starts here.
- 5Unknown caller: 401. The body has not been decoded yet.
- 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.
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))
}
- 1Connect, gRPC and gRPC-Web, one route per procedure.
- 2REST from the annotations. It installs one catch-all route on "/", and the more specific routes still win.
- 3The chain is a parameter. For the room cut, pass only validate.NewServerInterceptor() and delete interceptors.go.
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.
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)
}
}
- 1Vanguard also reads the JSON body with the form content type that curl -d sends. A test proves this.
- 2A known token without the role. The next row has no such key yet, and it answers 404.
- 3The state rule in the service, through Aborted, to 409 on a REST path.
- 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.
| item | check |
|---|---|
| buf | buf --version |
| protoc-gen-go on the PATH | protoc-gen-go --version |
| Network to the schema registry | buf dep update |
| Module and build caches full | Run all five commands once. |
| A fallback | Be 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.
- 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.
| the interviewer asks | the answer | goes 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.
0 of 8 known
A bare Connect API exposes POST /items.v1.ItemService/GetItem. What does the round grade that this does not give?
ErrConflict could map to CodeFailedPrecondition. What status does the client get then?
You change count to int64. A client that worked with {"count":2} now fails. Why?
The proto says by >= 1, and service.go still checks it. Is that dead code?
Why does recovery come first in the chain and validate last?
A handler returns ErrNotFound without toConnect. What does the client see?
Your PATH has an older protoc-gen-connect-go. buf generate succeeds, then the build fails. Why?
Vanguard installs one catch-all route. What happens to your other routes on that mux?
- 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.