System Design

K1

The 45-minute build kit

The build half asks for a small correct service. This kit is the routing, JSON, errors and storage around it, small enough to type from memory. Every line below is a tested file.

Not startedSaved in this browser only.
  1. 1Type the same skeleton every time, so the clock covers the domain and not the setup.
  2. 2Handler calls service calls store. The store interface is what makes the talk half concrete.
  3. 3Update takes a function, so a read, a rule and a write run as one atomic step.
  4. 4The server is 2,559 typed characters. Rehearse until it runs at the 5-minute mark.
K1
    A

    The layers

    one direction only
    POST /items/k/addhandlerhandler.goHTTP only: route, JSON,error to statusserviceservice.goRules only: validation,limits, what may happenStorestore.goAn interface. Update runsone function atomicallyMemStoremap + mutex: the buildPGStoresame interface: the talk
    • A layer calls only the layer below it.
    • The handler never touches a map. The store never sees a request.

    The handler knows HTTP, the service knows the rules, and the store knows the data. To move to Postgres I change one file.

    B

    Timed walkthrough

    computed from the files below
    filetypeddone at 500/minat 300/min
    store.go7961:362:39
    service.go3572:183:51
    handler.go1,2734:518:05
    main.go1335:078:32
    kit_test.go1,1887:3012:29
    1. store.go: The errors, Item, the Store interface, MemStore.
    2. service.go: One rule in the service; Get comes from the embedded Store.
    3. handler.go: Two routes, JSON in and out, the error map.
    4. main.go: go run . answers a curl.
    5. kit_test.go: go test -race passes, with 100 parallel adds.

    Typed means characters on screen, without imports, closing brackets, indentation or comments, because the editor adds those. 500 a minute is 100 words a minute at 5 characters a word; 300 is 60 words a minute. These are arithmetic, not a measurement of a person. Time yourself.

    I type the kit in the same order each time: store, service, handler, main, test.

    C

    store.go

    0:00 to 1:36
    store.gogo
    package main
    
    import (
    	"context"
    	"errors"
    	"sync"
    )
    
    var (
    	ErrInvalid  = errors.New("invalid")1
    	ErrNotFound = errors.New("not found")
    	ErrConflict = errors.New("conflict")
    )
    
    type Item struct {
    	Count int `json:"count"`
    }
    
    type Store interface {
    	Get(ctx context.Context, key string) (Item, error)2
    	Update(ctx context.Context, key string, fn func(*Item) error3) (Item, error)
    }
    
    type MemStore struct {
    	mu    sync.Mutex
    	items map[string]Item
    }
    
    func (s *MemStore) Get(_ context.Context, key string) (Item, error) {
    	s.mu.Lock()
    	defer s.mu.Unlock()
    	item, ok := s.items[key]
    	if !ok {
    		return item, ErrNotFound
    	}
    	return item, nil
    }
    
    func (s *MemStore) Update(_ context.Context, key string, fn func(*Item) error) (Item, error) {
    	s.mu.Lock()
    	defer s.mu.Unlock()
    	item := s.items[key]
    	if err := fn(&item); err != nil {4
    		return item, err
    	}
    	s.items[key] = item
    	return item, nil
    }
    
    1. 1Sentinel errors are the only language the layers share. The handler maps them to status codes.
    2. 2The memory store ignores ctx. A Postgres store needs it, so the interface has it from the first minute.
    3. 3The caller passes its rule. The rule runs inside the lock, so nothing changes between the read and the write.
    4. 4A rule that refuses leaves the map unchanged: the write comes after the check.

    The store has one write method, and it takes a function. That keeps every read-then-write inside the lock.

    D

    service.go

    to 2:18
    service.gogo
    package main
    
    import (
    	"context"
    	"fmt"
    )
    
    type Service struct{ Store }1
    
    func (s *Service) Add(ctx context.Context, key string, by int) (Item, error) {
    	if by < 1 {2
    		return Item{}, fmt.Errorf("%w: by must be 1 or more", ErrInvalid)
    	}
    	return s.Update(ctx, key, func(item *Item) error {
    		if item.Count+by > 1000 {3
    			return fmt.Errorf("%w: over the limit", ErrConflict)
    		}
    		item.Count += by
    		return nil
    	})
    }
    
    1. 1Embedding gives the service a Get that passes through. Add a method only when a rule appears.
    2. 2This check needs no state, so it runs outside the lock.
    3. 3This check reads state, so it must run inside the function.

    Validation before the lock is cheap. A rule that depends on current state goes inside Update.

    E

    The error map

    one function decides
    errorstatuswhen
    ErrInvalid400Bad JSON, or a value the rules refuse.
    ErrNotFound404The key does not exist.
    ErrConflict409Valid input, but the current state refuses it.
    anything else500Logged. The client gets a fixed message.
    • Wrap with %w to add detail. errors.Is still finds the sentinel.
    • A new domain error needs one new case and no handler change.

    Layers below the handler return sentinel errors. One function turns them into status codes, so the codes stay consistent.

    F

    handler.go

    to 4:51
    handler.gogo
    package main
    
    import (
    	"encoding/json"
    	"errors"
    	"fmt"
    	"log"
    	"net/http"
    )
    
    func routes(svc *Service) http.Handler {
    	mux := http.NewServeMux()
    	mux.Handle("GET /items/{key}", route(200, func(r *http.Request) (any, error) {
    		return svc.Get(r.Context(), r.PathValue("key")2)
    	}))
    	mux.Handle("POST /items/{key}/add"1, route(200, func(r *http.Request) (any, error) {
    		var body struct{ By int }
    		if err := readJSON(r, &body); err != nil {
    			return nil, err
    		}
    		return svc.Add(r.Context(), r.PathValue("key"), body.By)
    	}))
    	return mux
    }
    
    func route(status int, fn func(*http.Request) (any, error)) http.Handler {
    	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    		code := status3
    		v, err := fn(r)
    		if err != nil {
    			code, v = failure(err)
    		}
    		w.Header().Set("Content-Type", "application/json")
    		w.WriteHeader(code)
    		if err := json.NewEncoder(w).Encode(v); err != nil {
    			log.Print(err)
    		}
    	})
    }
    
    func readJSON(4r *http.Request, v any) error {
    	if err := json.NewDecoder(r.Body).Decode(v); err != nil {
    		return fmt.Errorf("%w: %v", ErrInvalid, err)
    	}
    	return nil
    }
    
    func failure(err error) (int, any) {
    	status := 500
    	switch {
    	case errors.Is(err, ErrInvalid):
    		status = 400
    	case errors.Is(err, ErrNotFound):
    		status = 404
    	case errors.Is(err, ErrConflict):
    		status = 409
    	default:
    		log.Print(err)
    		err = errors.New("internal error")5
    	}
    	return status, map[string]string{"error": err.Error()}
    }
    
    1. 1Routing patterns since Go 1.22 hold the method and path variables. A wrong method gets 405 with no code from you.
    2. 2The value of {key} in the pattern.
    3. 3A copy for this request. Writing to status would change the route for every later request, and it would be a data race.
    4. 4Bad JSON becomes ErrInvalid, so it takes the same path to 400 as any other validation error.
    5. 5Log the real error, and send a fixed message. An error text can leak a connection string.

    Every route is one function that returns a value and an error. One wrapper turns those into JSON and a status code.

    G

    main.go and the first run

    to 5:07
    main.gogo
    package main
    
    import (
    	"log"
    	"net/http"
    )
    
    func main() {
    	svc := &Service{&MemStore{items: map[string]Item{}}}
    	log.Fatal(http.ListenAndServe(":8080", routes(svc)))
    }
    
    the first runterminal
    go mod init kit
    go run .
    curl -d '{"by":2}' localhost:8080/items/a/add
    {"count":2}
    curl localhost:8080/items/a
    {"count":2}
    curl -i localhost:8080/items/b
    HTTP/1.1 404 Not Found

    At this point the server runs. I check it with curl once before I write a test.

    H

    Have this ready

    the machine, the day before
    itemcheck
    Go toolchaingo version
    Race detector worksgo test -race ./...
    Format and imports on saveSave a file with a missing import.
    AI completion is offCheck every editor plugin. The round allows no AI tools.
    An empty foldergo mod init works there
    Two terminals: server and curlA curl line is in the shell history.
    Screen share is readableLarge font, one window.
    The kit, rehearsedType it from memory, three days in a row.

    Ask at the start if a prepared starter is allowed. Rehearse as if it is not.

    My machine is set up before the clock starts, so I spend no minutes on it.

    I

    kit_test.go

    to 7:30
    kit_test.gogo
    package main
    
    import (
    	"net/http"
    	"net/http/httptest"
    	"strings"
    	"sync"
    	"testing"
    )
    
    func do(h http.Handler, method, path, body string) (int, string) {
    	w := httptest.NewRecorder()
    	h.ServeHTTP(w, httptest.NewRequest(method, path, strings.NewReader(body)))1
    	return w.Code, strings.TrimSpace(w.Body.String())
    }
    
    func TestAPI(t *testing.T) {
    	h := routes(&Service{&MemStore{items: map[string]Item{}}})
    	for _, c := range []struct {
    		method, path, body string
    		status             int
    		want               string
    	}{
    		{"GET", "/items/a", "", 404, `{"error":"not found"}`},
    		{"POST", "/items/a/add", `{"by":2}`, 200, `{"count":2}`},
    		{"POST", "/items/a/add", `{"by":0}`, 400,2 `{"error":"invalid: by must be 1 or more"}`},
    		{"POST", "/items/a/add", `{"by":999}`, 409, `{"error":"conflict: over the limit"}`},
    		{"GET", "/items/a", "", 200, `{"count":2}`},
    	} {
    		status, body := do(h, c.method, c.path, c.body)
    		if status != c.status || body != c.want {
    			t.Errorf("%s %s: got %d %s", c.method, c.path, status, body)
    		}
    	}
    }
    
    func TestParallelAdds(t *testing.T) {
    	h := routes(&Service{&MemStore{items: map[string]Item{}}})
    	var wg sync.WaitGroup
    	for range 100 {3
    		wg.Go(func() { do(h, "POST", "/items/k/add", `{"by":1}`) })
    	}
    	wg.Wait()
    	if _, body := do(h, "GET", "/items/k", ""); body != `{"count":100}`4 {
    		t.Errorf("got %s", body)
    	}
    }
    
    1. 1No socket and no port. The request still goes through the router, the service and the store.
    2. 2A new behaviour is a new row. Add one row for each error in the prompt.
    3. 3Run with -race. We removed the lock from Update, and this test failed with a data race report.
    4. 4The race detector finds unsafe memory access. This assert finds lost updates, which can be race-free.
    the gateterminal
    go test -race ./...
    ok  	kit

    One table test goes through the router to the store. One race test fires 100 parallel requests at one key and checks the count.

    J

    Mistakes this kit prevents

    what to do, what to avoid
    patternstatus
    Read, rule and write in one UpdateApproved
    Get, then a rule, then Put in the serviceNot approved
    A map with no lockNot approved
    The lock held during a slow callMemory only
    Status codes chosen in each handlerNot approved
    Errors mapped in one functionApproved
    A framework you have not rehearsedNot approved
    RWMutex before a read-heavy case existsReads dominate

    I look for each read followed by a write. If they are two store calls, I have a race.

    K

    From kit to exercise

    what changes in the room
    partchange
    ItemRename it to the domain noun. Add fields.
    AddWrite one service method per operation.
    UpdateKeep it. Each rule that reads state goes in the function.
    routesOne line per endpoint. Use 201 and 204 as the spec says.
    failureAdd a case only for a new error.
    TestAPIAdd one row per behaviour.

    A 204 has no body, so route must skip the encoder. E1 shows that line.

    The skeleton stays. I rename the noun, change the rule, and add routes.

    L

    Each of the 45 minutes

    one cell a minute
    A1A2A3B4B5B6B7B8B9B10C11C12C13C14C15D16D17D18D19D20D21D22D23D24D25D26D27D28D29D30E31E32E33E34E35E36E37E38F39F40F41F42F43G44G45
    minutesdoproof
    A0 to 3Read the prompt. Ask 3 or 4 questions. Write the routes as a comment.The interviewer agrees with the routes.
    B3 to 10Type the kit. Rename Item to the domain noun.go test -race passes.
    C10 to 15Turn the kit into the first real endpoints.Checkpoint 15: the simplest flow runs from curl.
    D15 to 30Build the core rules in the service, one test at a time.Checkpoint 30: every rule in the prompt has a test.
    E30 to 38Make the rules safe under load. Find each read followed by a write.A 100-goroutine test passes under -race.
    F38 to 43Walk the status codes and bad input, one table row each.Each error has a row in a table test.
    G43 to 45Stop adding. Run everything. Say what you would do next.Checkpoint 45: green tests, and a clean list for the talk.

    At 15, 30 and 45 minutes I stop and check that what I have runs. A smaller working service beats a larger broken one.

    M

    Drill

    predict, then reveal

    0 of 6 known

    1. A service method calls store.Get, adds 1, then calls store.Put. Each store call holds the mutex. Is this safe?

    2. Why does the Store interface take a function instead of offering Get and Put alone?

    3. In route, the error branch writes to a new variable code. What goes wrong if it writes to status instead?

    4. Why does failure replace an unknown error with "internal error"?

    5. go test passes without -race and fails with it. What does that mean?

    6. A request uses DELETE on a route that only has GET. Who answers, and with what?

    N

    Numbers to say

    computed from the files
    server
    2,559 typed characters: 5:07 at 100 words a minute.
    with tests
    3,747 typed characters: 7:30.
    race test
    100 parallel requests at one key.
    checkpoints
    15, 30 and 45 minutes.
    dependencies
    0: only the standard library.

    Derived from the files on this sheet. See panel B for what counts as typed.