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.
- 1Type the same skeleton every time, so the clock covers the domain and not the setup.
- 2Handler calls service calls store. The store interface is what makes the talk half concrete.
- 3Update takes a function, so a read, a rule and a write run as one atomic step.
- 4The server is 2,559 typed characters. Rehearse until it runs at the 5-minute mark.
- 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.
| file | typed | done at 500/min | at 300/min |
|---|---|---|---|
| store.go | 796 | 1:36 | 2:39 |
| service.go | 357 | 2:18 | 3:51 |
| handler.go | 1,273 | 4:51 | 8:05 |
| main.go | 133 | 5:07 | 8:32 |
| kit_test.go | 1,188 | 7:30 | 12:29 |
- store.go: The errors, Item, the Store interface, MemStore.
- service.go: One rule in the service; Get comes from the embedded Store.
- handler.go: Two routes, JSON in and out, the error map.
- main.go: go run . answers a curl.
- 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.
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
}
- 1Sentinel errors are the only language the layers share. The handler maps them to status codes.
- 2The memory store ignores ctx. A Postgres store needs it, so the interface has it from the first minute.
- 3The caller passes its rule. The rule runs inside the lock, so nothing changes between the read and the write.
- 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.
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
})
}
- 1Embedding gives the service a Get that passes through. Add a method only when a rule appears.
- 2This check needs no state, so it runs outside the lock.
- 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.
| error | status | when |
|---|---|---|
| ErrInvalid | 400 | Bad JSON, or a value the rules refuse. |
| ErrNotFound | 404 | The key does not exist. |
| ErrConflict | 409 | Valid input, but the current state refuses it. |
| anything else | 500 | Logged. 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.
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()}
}
- 1Routing patterns since Go 1.22 hold the method and path variables. A wrong method gets 405 with no code from you.
- 2The value of {key} in the pattern.
- 3A copy for this request. Writing to status would change the route for every later request, and it would be a data race.
- 4Bad JSON becomes ErrInvalid, so it takes the same path to 400 as any other validation error.
- 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.
package main
import (
"log"
"net/http"
)
func main() {
svc := &Service{&MemStore{items: map[string]Item{}}}
log.Fatal(http.ListenAndServe(":8080", routes(svc)))
}
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 FoundAt this point the server runs. I check it with curl once before I write a test.
| item | check |
|---|---|
| Go toolchain | go version |
| Race detector works | go test -race ./... |
| Format and imports on save | Save a file with a missing import. |
| AI completion is off | Check every editor plugin. The round allows no AI tools. |
| An empty folder | go mod init works there |
| Two terminals: server and curl | A curl line is in the shell history. |
| Screen share is readable | Large font, one window. |
| The kit, rehearsed | Type 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.
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)
}
}
- 1No socket and no port. The request still goes through the router, the service and the store.
- 2A new behaviour is a new row. Add one row for each error in the prompt.
- 3Run with -race. We removed the lock from Update, and this test failed with a data race report.
- 4The race detector finds unsafe memory access. This assert finds lost updates, which can be race-free.
go test -race ./...
ok kitOne table test goes through the router to the store. One race test fires 100 parallel requests at one key and checks the count.
| pattern | status |
|---|---|
| Read, rule and write in one Update | Approved |
| Get, then a rule, then Put in the service | Not approved |
| A map with no lock | Not approved |
| The lock held during a slow call | Memory only |
| Status codes chosen in each handler | Not approved |
| Errors mapped in one function | Approved |
| A framework you have not rehearsed | Not approved |
| RWMutex before a read-heavy case exists | Reads dominate |
I look for each read followed by a write. If they are two store calls, I have a race.
| part | change |
|---|---|
| Item | Rename it to the domain noun. Add fields. |
| Add | Write one service method per operation. |
| Update | Keep it. Each rule that reads state goes in the function. |
| routes | One line per endpoint. Use 201 and 204 as the spec says. |
| failure | Add a case only for a new error. |
| TestAPI | Add 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.
| minutes | do | proof | |
|---|---|---|---|
| A | 0 to 3 | Read the prompt. Ask 3 or 4 questions. Write the routes as a comment. | The interviewer agrees with the routes. |
| B | 3 to 10 | Type the kit. Rename Item to the domain noun. | go test -race passes. |
| C | 10 to 15 | Turn the kit into the first real endpoints. | Checkpoint 15: the simplest flow runs from curl. |
| D | 15 to 30 | Build the core rules in the service, one test at a time. | Checkpoint 30: every rule in the prompt has a test. |
| E | 30 to 38 | Make the rules safe under load. Find each read followed by a write. | A 100-goroutine test passes under -race. |
| F | 38 to 43 | Walk the status codes and bad input, one table row each. | Each error has a row in a table test. |
| G | 43 to 45 | Stop 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.
0 of 6 known
A service method calls store.Get, adds 1, then calls store.Put. Each store call holds the mutex. Is this safe?
Why does the Store interface take a function instead of offering Get and Put alone?
In route, the error branch writes to a new variable code. What goes wrong if it writes to status instead?
Why does failure replace an unknown error with "internal error"?
go test passes without -race and fails with it. What does that mean?
A request uses DELETE on a route that only has GET. Who answers, and with what?
- 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.