System Design

E9

Directory and audit log

This exercise looks like plain CRUD. The test is three details: pages that hold still while rows arrive, the right refusal for each caller, and exactly one audit row per change.

Not startedSaved in this browser only.
  1. 1A cursor names a place in the sort order. An offset counts rows, and an insert moves them.
  2. 2401 says who are you. 403 says you may not. Check both before you read the request.
  3. 3A change and its audit row share one lock, so parallel updates make an unbroken chain.
  4. 4Production puts the tenant rule and the append-only rule in the database.
E9
    A

    The spec

    as the interviewer states it
    Build an employee directory as an HTTP service, in memory. Clients create, update and list employees. The list has filters and pagination, and it must stay correct while others add rows. Three roles exist: viewers read, editors write, and admins also read the audit log. Every change writes one audit row that says who changed what. Make it safe under parallel requests.
    askanswer assumed
    How do callers log in?Three fixed bearer tokens. Login is out of scope.
    What order?By name, then id, in byte order.
    Can employees be deleted?No. Status goes to inactive, and audit rows keep their meaning.
    What can an update change?Name, team and status. The email stays fixed.
    Is an email unique?Yes. A duplicate is 409.
    What does an audit row hold?Actor, time, and the record before and after.

    Before I type, I confirm the sort order, because the cursor depends on it, and that a change with no effect writes no audit row.

    B

    The endpoints

    the contract the grader checks
    requestrolesuccesserrors
    POST /employeeseditor201 employee400, 409
    GET /employees/{id}viewer200 employee404
    PATCH /employees/{id}editor200 employee400, 404
    GET /employeesviewer200 page400
    GET /auditadmin200 rows400
    • Every route answers 401 with no known token, and 403 with too low a role.
    • The tokens are viewer-token, editor-token and admin-token.
    • The list takes team, status, limit (20 by default, 100 at most) and cursor.
    • A page is {"items":[...],"nextCursor":"..."}. An empty cursor ends the walk.
    • The log takes employee and after (a seq), with 100 rows a page. An empty page ends the walk.

    Every route starts with the same two gates. A viewer gets 403 on a write, whatever the body says.

    C

    The checkpoints

    15, 30 and 45 minutes
    bybuildproofif you are late
    15 minThe kit, renamed. Create, get and update over MemStore. The allow wrapper with 401 and 403.TestRolesHard-code the tokens. They stay hard-coded in the build.
    30 minThe audit row inside Create and Update. The audit route.TestParallelUpdatesEachLogOneRowSkip paging the log. Say that it pages by seq.
    45 minList with filters and the cursor. Limit + 1. The race test.TestCursorIgnoresInsertsBuild the team filter only. A second filter is one more condition.

    I keep a running service at each checkpoint. If I am late at 30 minutes, I finish the audit row first, because it is an invariant.

    D

    Two kinds of pagination

    one insert, two results
    page 1, limit 2bobcatThen a client inserts abe at the front.OFFSET 2skip two rows, by countafter (cat, id)start after one row, by valueabebobcatdaneveabebobcatdaneveskipped: 2 rowsrepeatpage 2never shown yetthe cursor points herepage 2page 2Page 2 by offset: cat, dan. cat comes twice.Page 2 by cursor: dan, eve.A delete has the opposite effect: rows move up, and the offset skips one.A cursor names a place in the sort order, and no insert or delete moves that place.

    An offset counts rows, and an insert moves them. A cursor names the last row I saw, and no insert moves that.

    E

    Which one, when

    the choice in the room
    needoffsetcursor
    Rows arrive during a walkNot approvedApproved
    Rows leave during a walkNot approvedApproved
    Page 5000 stays fastNot approvedApproved
    Jump to page 40ApprovedNot approved
    Show a page countExtra queryExtra query
    A row changes its sort keyCan repeatCan repeat

    Tested on 50,000 rows: the keyset query starts inside the index with no sort, and OFFSET 49,000 reads 49,021 rows to return 21.

    I use a cursor for anything that changes. I keep offset for small, stable lists with page numbers.

    F

    The order of the gates

    401, then 403, then the rest
    requestwho are you?401no token, or unknownmay you?403token known, role too lowis it valid?400, 404, 409body, id, duplicateone lockchangeaudit rowA viewer who sends a bad body, or a missing id, gets 403.The answer reveals nothing about the data to a caller who may not act on it.

    Each gate answers one question. I read the body only after the caller has passed the first two.

    G

    Why it fits

    computed from the files
    partvalue
    Lines, with tests451
    Typed characters9,995
    Typing at 500 a minute19:59
    Typing at 300 a minute33:19
    Left for thinking, at 500 a minute25:01
    Dependencies0
    • This build is at the edge of the budget. Type the audit row before the filters.
    • In the room, keep every file in package main. Here main.go sits in its own folder, so the production version can import the build.

    Typed characters leave out imports, closing brackets, indentation and comments. Arithmetic, not a measurement of a person.

    I have rehearsed the kit part of this build. The new work is the allow wrapper, the audit row and the cursor.

    H

    store.go

    reference build
    store.gogo
    package build
    
    import (
    	"cmp"
    	"context"
    	"errors"
    	"slices"
    	"sync"
    	"time"
    )
    
    var (
    	ErrInvalid      = errors.New("invalid")
    	ErrUnauthorized = errors.New("unauthorized")
    	ErrForbidden    = errors.New("forbidden")
    	ErrNotFound     = errors.New("not found")
    	ErrConflict     = errors.New("conflict")
    )
    
    type Employee struct {
    	ID     string `json:"id"`
    	Name   string `json:"name"`
    	Email  string `json:"email"`
    	Team   string `json:"team"`
    	Status string `json:"status"`
    }
    
    // Audit is one change: who, when, and the record before and after. Before is nil on a create.
    type Audit struct {
    	Seq      int64     `json:"seq"`
    	At       time.Time `json:"at"`
    	Actor    string    `json:"actor"`
    	Employee string    `json:"employee"`
    	Before   *Employee `json:"before"`1
    	After    Employee  `json:"after"`
    }
    
    // Query selects a page: rows that match, sorted by name then id, from just after After.
    type Query struct {
    	Team, Status string
    	After        Employee
    	Limit        int
    }
    
    type Store interface {
    	// Create adds the employee and one audit row together, or returns ErrConflict.
    	Create(ctx context.Context, e Employee, actor string) error2
    	Get(ctx context.Context, id string) (Employee, error)
    	// Update runs fn, then writes the change and one audit row together. No change, no row.
    	Update(ctx context.Context, id, actor string, fn func(*Employee) error) (Employee, error)
    	List(ctx context.Context, q Query) ([]Employee, error)
    	Log(ctx context.Context, employee string, after int64, limit int) ([]Audit, error)
    }
    
    func compare(a, b Employee) int {
    	return cmp.Or(cmp.Compare(a.Name, b.Name), cmp.Compare(a.ID, b.ID))3
    }
    
    type MemStore struct {
    	mu        sync.RWMutex
    	employees map[string]Employee
    	emails    map[string]bool
    	log       []Audit
    }
    
    func NewMemStore() *MemStore {
    	return &MemStore{employees: map[string]Employee{}, emails: map[string]bool{}}
    }
    
    func (s *MemStore) record(actor string, before *Employee, after Employee) {
    	s.log = append(s.log, Audit{int64(len(s.log) + 1), time.Now(), actor, after.ID, before, after})
    }
    
    func (s *MemStore) Create(_ context.Context, e Employee, actor string) error {
    	s.mu.Lock()
    	defer s.mu.Unlock()
    	if s.emails[e.Email] {
    		return ErrConflict
    	}
    	s.emails[e.Email] = true
    	s.employees[e.ID] = e
    	s.record(actor, nil, e)
    	return nil
    }
    
    func (s *MemStore) Get(_ context.Context, id string) (Employee, error) {
    	s.mu.RLock()
    	defer s.mu.RUnlock()
    	e, ok := s.employees[id]
    	if !ok {
    		return e, ErrNotFound
    	}
    	return e, nil
    }
    
    func (s *MemStore) Update(_ context.Context, id, actor string, fn func(*Employee) error) (Employee, error) {
    	s.mu.Lock()
    	defer s.mu.Unlock()
    	before, ok := s.employees[id]
    	if !ok {
    		return before, ErrNotFound
    	}
    	after := before
    	if err := fn(&after); err != nil {
    		return after, err
    	}
    	if after != before {4
    		s.employees[id] = after
    		s.record(actor, &before, after)5
    	}
    	return after, nil
    }
    
    func (s *MemStore) List(_ context.Context, q Query) ([]Employee, error) {
    	s.mu.RLock()
    	defer s.mu.RUnlock()
    	out := []Employee{}
    	for _, e := range s.employees {
    		if (q.Team == "" || e.Team == q.Team) && (q.Status == "" || e.Status == q.Status) && compare(e, q.After) > 06 {
    			out = append(out, e)
    		}
    	}
    	slices.SortFunc(out, compare)
    	return out[:min(q.Limit, len(out))], nil
    }
    
    // Log uses the fact that seq n sits at index n-1.
    func (s *MemStore) Log(_ context.Context, employee string, after int64, limit int) ([]Audit, error) {
    	s.mu.RLock()
    	defer s.mu.RUnlock()
    	out := []Audit{}
    	for _, a := range s.log[min(int(after), len(s.log)):]7 {
    		if len(out) < limit && (employee == "" || a.Employee == employee) {
    			out = append(out, a)
    		}
    	}
    	return out, nil
    }
    
    1. 1Two full records, not a list of changed fields. Comparing them gives the difference, with no code to compute it.
    2. 2The actor is a parameter of the write, so a change with no author cannot compile.
    3. 3The id breaks ties. Every row now has one exact place, which a cursor needs.
    4. 4A struct comparison. No change, no write, no audit row.
    5. 5Still under the write lock. Two updates cannot log out of order, so each row follows the row before it.
    6. 6The cursor test: only rows after the last row of the last page. This scans all rows. Production starts inside an index.
    7. 7The min guards a cursor past the end. The service has already refused a negative one.

    Create and Update write the audit row inside the store, under the lock. No caller can make a change without one.

    I

    service.go

    reference build
    service.gogo
    package build
    
    import (
    	"cmp"
    	"context"
    	"crypto/rand"
    	"encoding/base64"
    	"fmt"
    	"strconv"
    	"strings"
    )
    
    type Service struct {
    	Store
    }
    
    // Page is one page of employees. An empty NextCursor means this is the last page.
    type Page struct {
    	Items      []Employee `json:"items"`
    	NextCursor string     `json:"nextCursor"`
    }
    
    // A cursor names the last row of a page, not a count of rows, so inserts cannot move it.
    func decode(cursor string) (Employee, error) {
    	raw, err := base64.RawURLEncoding.DecodeString(cursor)
    	name, id, ok := strings.Cut(string(raw), "\x00")
    	if cursor != "" && (err != nil || !ok) {2
    		return Employee{}, fmt.Errorf("%w: bad cursor", ErrInvalid)
    	}
    	return Employee{Name: name, ID: id}, nil
    }
    
    func validate(e Employee) error {
    	if e.Name == "" || e.Team == "" || e.Email == "" || (e.Status != "active" && e.Status != "inactive") {
    		return fmt.Errorf("%w: bad name, team, email or status", ErrInvalid)
    	}
    	return nil
    }
    
    func (s *Service) Create(ctx context.Context, actor string, e Employee) (Employee, error) {
    	e.ID, e.Status = rand.Text(), "active"
    	if err := validate(e); err != nil {
    		return e, err
    	}
    	return e, s.Store.Create(ctx, e, actor)
    }
    
    // Patch holds the fields a client may change. A nil field stays as it is.
    type Patch struct {
    	Name, Team, Status *string
    }
    
    func (s *Service) Update(ctx context.Context, actor, id string, p Patch) (Employee, error) {
    	return s.Store.Update(ctx, id, actor, func(e *Employee) error {
    		for field, value := range map[*string]*string{&e.Name: p.Name, &e.Team: p.Team, &e.Status: p.Status} {3
    			if value != nil {
    				*field = *value
    			}
    		}
    		return validate(*e)4
    	})
    }
    
    // List asks the store for one row over the limit. That row proves another page exists.
    func (s *Service) List(ctx context.Context, team, status, cursor, limit string) (Page, error) {
    	n, err := strconv.Atoi(cmp.Or(limit, "20"))
    	if err != nil || n < 1 || n > 100 {
    		return Page{}, fmt.Errorf("%w: limit must be from 1 to 100", ErrInvalid)
    	}
    	after, err := decode(cursor)
    	if err != nil {
    		return Page{}, err
    	}
    	rows, err := s.Store.List(ctx, Query{team, status, after, n + 1}5)
    	if len(rows) <= n {
    		return Page{rows, ""}, err
    	}
    	last := rows[n-1]6
    	return Page{rows[:n], base64.RawURLEncoding.EncodeToString([]byte(last.Name + "\x00" + last.ID))}, err
    }
    
    // Log returns one page of the audit log from just after seq. An empty page is the end.
    func (s *Service) Log(ctx context.Context, employee, after string) ([]Audit, error) {
    	seq, err := strconv.ParseInt(cmp.Or(after, "0"), 10, 64)
    	if err != nil || seq < 0 {
    		return nil, fmt.Errorf("%w: bad after", ErrInvalid)
    	}
    	return s.Store.Log(ctx, employee, seq, 100)
    }
    
    1. 1Embedded, as in the kit. Get needs no rule, so it reaches the store directly.
    2. 2A broken cursor is 400. An empty one starts the list, because the zero row sorts before every name.
    3. 3Each field is a pointer, so an absent field stays as it is and an empty string can be refused.
    4. 4Inside the lock, on the merged record. A refused patch returns an error, and the store writes nothing.
    5. 5One row over the limit. If it comes back, another page exists, with no count query.
    6. 6The last row the client will see, not the extra row. The next page starts just after it.

    The cursor holds the name and id of the last row, in Base64. Asking for one extra row tells me if another page exists.

    J

    handler.go and main.go

    reference build
    handler.gogo
    package build
    
    import (
    	"encoding/json"
    	"errors"
    	"fmt"
    	"log"
    	"net/http"
    	"strings"
    )
    
    // The roles, lowest first. A higher role can do all that a lower one can.
    const (
    	Viewer = iota + 11
    	Editor
    	Admin
    )
    
    type Caller struct {
    	Name string
    	Rank int
    }
    
    type Tokens map[string]Caller
    
    // SpecTokens are the fixed tokens of the spec.
    var SpecTokens = Tokens{
    	"viewer-token": {"viewer", Viewer},
    	"editor-token": {"editor", Editor},
    	"admin-token":  {"admin", Admin},
    }
    
    func Handler(svc *Service, tokens Tokens) http.Handler {
    	// allow answers who you are (401), then what you may do (403), and only then reads the request.
    	allow := func(need, status int, fn func(*http.Request, Caller) (any, error)) http.Handler {2
    		return route(status, func(r *http.Request) (any, error) {
    			token, bearer := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
    			caller, known := tokens[token]
    			if !bearer || !known {
    				return nil, ErrUnauthorized
    			}
    			if caller.Rank < need {
    				return nil, ErrForbidden
    			}
    			return fn(r, caller)
    		})
    	}
    
    	mux := http.NewServeMux()
    	mux.Handle("POST /employees", allow(Editor, 201, func(r *http.Request, c Caller) (any, error) {
    		var e Employee
    		if err := readJSON(r, &e); err != nil {
    			return nil, err
    		}
    		return svc.Create(r.Context(), c.Name, e)
    	}))
    	mux.Handle("GET /employees/{id}", allow(Viewer, 200, func(r *http.Request, _ Caller) (any, error) {
    		return svc.Get(r.Context(), r.PathValue("id"))
    	}))
    	mux.Handle("PATCH /employees/{id}", allow(Editor, 200, func(r *http.Request, c Caller) (any, error) {
    		var p Patch
    		if err := readJSON(r, &p); err != nil {
    			return nil, err
    		}
    		return svc.Update(r.Context(), c.Name, r.PathValue("id"), p)
    	}))
    	mux.Handle("GET /employees", allow(Viewer, 200, func(r *http.Request, _ Caller) (any, error) {
    		q := r.URL.Query()
    		return svc.List(r.Context(), q.Get("team"), q.Get("status"), q.Get("cursor"), q.Get("limit"))
    	}))
    	mux.Handle("GET /audit", allow(Admin, 200, func(r *http.Request, _ Caller) (any, error) {
    		q := r.URL.Query()
    		rows, err := svc.Log(r.Context(), q.Get("employee"), q.Get("after"))
    		return map[string][]Audit{"items": rows}, err
    	}))
    	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 := status
    		v, err := fn(r)
    		if err != nil {
    			code, v = failure(err)
    		}
    		if code == 401 {5
    			w.Header().Set("WWW-Authenticate", "Bearer")
    		}
    		w.Header().Set("Content-Type", "application/json")
    		w.WriteHeader(code)
    		if err := json.NewEncoder(w).Encode(v); err != nil {
    			log.Print(err)
    		}
    	})
    }
    
    func readJSON(r *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, ErrUnauthorized):
    		status = 401
    	case errors.Is(err, ErrForbidden):
    		status = 403
    	case errors.Is(err, ErrNotFound):
    		status = 404
    	case errors.Is(err, ErrConflict):
    		status = 409
    	default:
    		log.Print(err)
    		err = errors.New("internal error")
    	}
    	return status, map[string]string{"error": err.Error()}
    }
    
    1. 1From 1, so an unknown caller at rank 0 can never pass. Higher means more.
    2. 2Every route goes through this, and each one names its role.
    3. 3First gate: 401. It runs before anything reads the body or the path.
    4. 4Second gate: 403. The token is known, and the role is too low.
    5. 5HTTP requires this header on a 401. It names the scheme to use.
    main.gogo
    // Command main serves the 45-minute directory.
    package main
    
    import (
    	"log"
    	"net/http"
    
    	"github.com/rudrite/system-design/arena/exercises/directory/build"
    )
    
    func main() {
    	handler := build.Handler(&build.Service{Store: build.NewMemStore()}, build.SpecTokens)
    	log.Fatal(http.ListenAndServe(":8080", handler))
    }
    

    The allow wrapper puts the two gates in one place. A route cannot forget them, because it cannot register without a role.

    K

    build_test.go

    type this part too
    build_test.gogo
    package build
    
    import (
    	"encoding/json"
    	"fmt"
    	"net/http"
    	"net/http/httptest"
    	"strings"
    	"sync"
    	"testing"
    )
    
    func do(h http.Handler, token, method, path, body string, out any) int {
    	w := httptest.NewRecorder()
    	r := httptest.NewRequest(method, path, strings.NewReader(body))
    	r.Header.Set("Authorization", "Bearer "+token)
    	h.ServeHTTP(w, r)
    	_ = json.Unmarshal(w.Body.Bytes(), out) // out is nil when a test wants only the status
    	return w.Code
    }
    
    func newHandler() http.Handler {
    	return Handler(&Service{NewMemStore()}, SpecTokens)
    }
    
    func add(t *testing.T, h http.Handler, name string) string {
    	t.Helper()
    	var e Employee
    	body := fmt.Sprintf(`{"name":%q,"email":"%[email protected]","team":"eng"}`, name, name)
    	if status := do(h, "editor-token", "POST", "/employees", body, &e); status != 201 {
    		t.Fatal(status)
    	}
    	return e.ID
    }
    
    func TestRoles(t *testing.T) {
    	h := newHandler()
    	id := add(t, h, "ann")
    	for _, c := range []struct {
    		token, method, path string
    		status              int
    	}{
    		{"nope", "GET", "/employees", 401},1
    		{"viewer-token", "PATCH", "/employees/" + id, 403},
    		{"editor-token", "GET", "/audit", 403},
    	} {
    		if status := do(h, c.token, c.method, c.path, `{}`, nil); status != c.status {
    			t.Errorf("%s %s as %s: got %d", c.method, c.path, c.token, status)
    		}
    	}
    }
    
    // An insert at the front between pages: an offset would repeat "cat".
    func TestCursorIgnoresInserts(t *testing.T) {
    	h := newHandler()
    	for _, name := range []string{"bob", "cat", "dan"} {
    		add(t, h, name)
    	}
    	var first, second Page
    	do(h, "viewer-token", "GET", "/employees?limit=2", "", &first)
    	add(t, h, "abe")2
    	do(h, "viewer-token", "GET", "/employees?limit=2&cursor="+first.NextCursor, "", &second)
    	if len(second.Items) != 1 || second.Items[0].Name != "dan" {
    		t.Fatalf("second page: %+v", second)
    	}
    }
    
    func TestParallelUpdatesEachLogOneRow(t *testing.T) {
    	h := newHandler()
    	id := add(t, h, "ann")
    	var wg sync.WaitGroup
    	for i := range 99 {
    		wg.Go(func() {
    			do(h, "editor-token", "PATCH", "/employees/"+id, fmt.Sprintf(`{"team":"t%d"}`, i), nil)
    		})
    	}
    	wg.Wait()
    	var log struct{ Items []Audit }
    	do(h, "admin-token", "GET", "/audit?employee="+id, "", &log)
    	if len(log.Items) != 100 {
    		t.Fatalf("%d rows, want 100", len(log.Items))
    	}
    	for i := 1; i < len(log.Items); i++ {
    		if log.Items[i].Before.Team != log.Items[i-1].After.Team {3
    			t.Errorf("row %d does not follow the row before it", i)
    		}
    	}
    }
    
    1. 1A table of who may do what: one line per rule.
    2. 2The insert between pages. It sorts first, which is the worst case for an offset.
    3. 3The chain. The count alone would pass with the audit row outside the lock.

    The last test is the one that matters. 99 parallel updates must leave 100 rows, with each row starting where the last one ended.

    L

    The grader agrees

    33 checks, saved from a real run
    reportsaved output
    arena run directory --base http://localhost:8080
    
    correctness
      PASS  get returns what create stored
      PASS  patch changes only the fields it sends
      PASS  the list is sorted by name
      PASS  the team filter returns only that team
      PASS  the status filter combines with the team filter
      PASS  limit and cursor walk every row once
      PASS  a page that ends the list has an empty nextCursor
      PASS  an empty list is an empty array
      PASS  create writes one audit row
      PASS  update writes one audit row with before and after
      PASS  a patch that changes nothing writes no audit row
      PASS  a refused patch writes no audit row
      PASS  the audit log pages past 100 rows
    
    status codes
      PASS  create is 201 and returns an id
      PASS  a missing employee is 404
      PASS  a duplicate email is 409
      PASS  no token, or an unknown one, is 401 on every route
      PASS  a known token without the right role is 403
      PASS  the role check comes before the request is read
      PASS  each role can do its work
      PASS  the audit log has no write route
    
    validation
      PASS  malformed JSON is 400
      PASS  a value of the wrong type is 400
      PASS  a missing name, email or team is 400
      PASS  an unknown status is 400
      PASS  a limit outside 1 to 100 is 400
      PASS  a bad cursor is 400
    
    concurrency
      PASS  an insert between pages repeats no row
      PASS  parallel inserts during a walk: no row repeats or goes missing
      PASS  100 parallel creates all land, each with one audit row
      PASS  100 parallel creates of one email: exactly one wins, one audit row
      PASS  100 parallel updates: one audit row each, in an unbroken chain
      PASS  100 parallel patches of two fields lose neither
    
    33 checks: 33 passed, 0 failed

    All checks pass, with inserts during a walk and 100 parallel updates of one record.

    M

    Two bugs it catches

    both pass every other check

    A test server uses the row count as its cursor, as OFFSET does.

    offset cursorssaved output, failures only
      FAIL  an insert between pages repeats no row
            row m002 came back on a later page
      FAIL  parallel inserts during a walk: no row repeats or goes missing
            row a03-00 came back on a later page
    
    33 checks: 31 passed, 2 failed

    A test server reads the record, makes the change, then logs. The count of rows is right, and the chain breaks.

    audit row outside the locksaved output, failures only
      FAIL  100 parallel updates: one audit row each, in an unbroken chain
            row 2 says the name was "Ann", but the row before set "n8"
    
    33 checks: 32 passed, 1 failed
    choicestatus
    Role check before the bodyApproved
    403 for a missing tokenNot approved
    Audit row under the same lockApproved
    Audit row in a goroutineNot approved
    Sort by name aloneNot approved
    Sort a full copy per pageSay the cost

    Neither bug shows up in a simple test. The first needs an insert between pages. The second needs overlapping updates.

    N

    The talk map

    the second 45 minutes
    the interviewer asksthe answergoes deeper
    Why a cursor and not page numbers?An insert moves every later row, so an offset repeats a row. A delete makes it skip one. OFFSET also reads every row it skips, so deep pages get slow. A cursor has neither problem.R3 Requirements to API
    What does a cursor cost?No jump to page 40, and no page count. A rename moves a row, so a walk can see it twice or miss it. For an admin screen with few rows, offset is fine, and I say that.R3 Requirements to API
    What index does this list need?One that matches the sort: tenant, then name, then id. The query starts inside the index and reads one page. A second index on tenant, team, name and id serves the filter in the same order.D2 Indexes
    Run two instances. What breaks?Each mutex and map covers one process. The row lock on update replaces the mutex. The unique index replaces the email map, and it holds under any number of parallel creates.T4 Locks in the database
    401 or 403?401 says that I do not know who you are, so log in again. 403 says that I know you, and you may not do this. Check the role before the body, so a refused caller learns nothing.O5 Security
    JWT or sessions?A session row can be revoked at once, and each request costs a lookup. A JWT needs no lookup, but it stays valid until it expires. Roles change here, so I use short JWTs or sessions.O5 Security
    How do you keep one customer out of another's data?A tenant column on every table, and row-level security on top. A missing WHERE in one query then returns nothing extra. A test runs a query with no filter and sees one tenant.O6 Multi-tenant SaaS
    Why not filter by tenant in the store and stop there?Then every query must remember, and a bug in one leaks data across customers. With policies, the app role cannot see the other rows at all. The store filter would be a second copy of the rule.O6 Multi-tenant SaaS
    Why write the audit row in the same transaction?They land together or not at all. A message sent after the commit can be lost, and one sent before can describe a change that rolled back. A trigger also works, but the actor must then reach the database.T9 Exactly-once
    Who can change the audit log?Nobody through the app. The app role has SELECT and INSERT on it, so UPDATE, DELETE and TRUNCATE fail with a permission error. A test tries each one. Ship rows to separate storage to defend against a stolen admin.O5 Security
    A reader follows the log by seq. Can it miss a row?Yes. Two transactions take seq 8 and 9, and 9 commits first. A reader at 9 then never sees 8. Per employee the row lock orders them. For a global tail, read behind by a safe margin.T4 Locks in the database
    The audit rows hold personal data. An employee asks to be erased.The before and after rows copy every field. Keep the fields you must keep, and store the rest by reference to a record you can delete. Set a retention period with the legal team.C27 Employee directory

    I start from what the build lacks: durability and two instances. Then I move to tenants and to who can touch the log.

    O

    The production shape

    the rules move into the database
    tokentenant, roleany instanceBEGINrole = apptenant = aquery, COMMITPostgresemployeesa: annb: hiddenaudit_loga: create annb: hiddenpolicy: tenant = app.tenantaudit_log grants: SELECT, INSERTThe tenant check lives in the database, so a query that forgets it still sees one tenant.The change and its audit row commit together, or neither does.

    Each transaction drops to the app role and names a tenant. From there the database refuses what the app must not do.

    P

    What changes

    from build to production
    toolbuildproduction
    PostgresMap and mutexemployees table, FOR UPDATE on update
    PostgresSort a copy per pageKeyset query on a matching index
    PostgresA slice for the logaudit_log, in the same transaction; no UPDATE or DELETE grant
    PostgresOne set of dataRow-level security per tenant
    PostgresExact email matchUnique index on tenant and lower(email)
    ServiceFixed tokensTokens from config, each with a tenant and a role
    ServiceListenAndServeTimeouts, a body limit, metrics, drain on SIGTERM

    Tested: production passes the same 33 grader checks. The real binary passes them over a socket, then exits cleanly on SIGTERM. Metrics are the ones from E1.

    One interface, one new implementation, and a wrapper around the same handler. The service file does not change.

    Q

    The diff

    build to production

    store.go, service.go and handler.go of the build are imported as they are. The production package adds the files below.

    main.go+63 -4
    + // Command main serves the production directory. It reads DATABASE_URL, API_TOKENS
    + // (tenant:role:token,tenant:role:token) and ADDR, which defaults to :8080. The database user must
    + // be able to SET ROLE directory_app, and must not have BYPASSRLS.
    - // Command main serves the 45-minute directory.
      package main
      
      import (
    + 	"cmp"
    + 	"context"
    + 	"errors"
      	"log"
      	"net/http"
    + 	"os"
    + 	"os/signal"
    + 	"syscall"
    + 	"time"
      
    + 	"github.com/jackc/pgx/v5/pgxpool"
    + 
    + 	"github.com/rudrite/system-design/arena/exercises/directory/prod"
    + 	kv "github.com/rudrite/system-design/arena/exercises/kvstore/prod"
    - 	"github.com/rudrite/system-design/arena/exercises/directory/build"
      )
      
      func main() {
    + 	if err := run(); err != nil {
    + 		log.Fatal(err)
    + 	}
    + }
    + 
    + func run() error {
    + 	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
    + 	defer stop()
    + 
    + 	pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
    + 	if err != nil {
    + 		return err
    + 	}
    + 	defer pool.Close()
    + 	if err := prod.Migrate(ctx, pool); err != nil {
    + 		return err
    + 	}
    + 	tokens, tenants, err := prod.ParseTokens(os.Getenv("API_TOKENS"))
    + 	if err != nil {
    + 		return err
    + 	}
    + 	handler := prod.Handler(pool, tokens, tenants, kv.NewMetrics())
    + 
    + 	srv := &http.Server{
    + 		Addr:              cmp.Or(os.Getenv("ADDR"), ":8080"),
    + 		Handler:           handler,
    + 		ReadHeaderTimeout: 5 * time.Second,
    + 		ReadTimeout:       10 * time.Second,
    + 		WriteTimeout:      10 * time.Second,
    + 		IdleTimeout:       60 * time.Second,
    + 	}
    + 	failed := make(chan error, 1)
    + 	go func() { failed <- srv.ListenAndServe() }()
    + 
    + 	select {
    + 	case err := <-failed:
    + 		return err
    + 	case <-ctx.Done():
    + 	}
    + 	// SIGTERM: stop accepting, finish what is running, then exit.
    + 	drain, cancel := context.WithTimeout(context.Background(), 20*time.Second)
    + 	defer cancel()
    + 	if err := srv.Shutdown(drain); err != nil {
    + 		return err
    + 	}
    + 	if err := <-failed; !errors.Is(err, http.ErrServerClosed) {
    + 		return err
    + 	}
    + 	return nil
    - 	handler := build.Handler(&build.Service{Store: build.NewMemStore()}, build.SpecTokens)
    - 	log.Fatal(http.ListenAndServe(":8080", handler))
      }
    schema.sqlnew file
    DO $$ BEGIN
        CREATE ROLE directory_app NOLOGIN;
    EXCEPTION WHEN duplicate_object THEN NULL;
    END $$;
    
    CREATE TABLE IF NOT EXISTS employees (
        tenant text NOT NULL DEFAULT current_setting('app.tenant'),
        id     text COLLATE "C" PRIMARY KEY,
        name   text COLLATE "C" NOT NULL,
        email  text NOT NULL,
        team   text NOT NULL,
        status text NOT NULL CHECK (status IN ('active', 'inactive'))
    );
    
    CREATE UNIQUE INDEX IF NOT EXISTS employees_email ON employees (tenant, lower(email));
    CREATE INDEX IF NOT EXISTS employees_by_name ON employees (tenant, name, id);
    CREATE INDEX IF NOT EXISTS employees_by_team ON employees (tenant, team, name, id);
    
    CREATE TABLE IF NOT EXISTS audit_log (
        seq        bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
        tenant     text NOT NULL DEFAULT current_setting('app.tenant'),
        at         timestamptz NOT NULL DEFAULT now(),
        actor      text NOT NULL,
        employee   text NOT NULL,
        before_row jsonb,
        after_row  jsonb NOT NULL
    );
    
    CREATE INDEX IF NOT EXISTS audit_by_employee ON audit_log (tenant, employee, seq);
    schema.sql, policies and grantsnew file
    -- Row-level security: every query the app role runs sees one tenant, with or without a WHERE. With
    -- no tenant set, current_setting returns NULL and no row matches.
    ALTER TABLE employees ENABLE ROW LEVEL SECURITY;
    ALTER TABLE audit_log ENABLE ROW LEVEL SECURITY;
    
    DROP POLICY IF EXISTS one_tenant ON employees;
    CREATE POLICY one_tenant ON employees
        USING (tenant = current_setting('app.tenant', true))
        WITH CHECK (tenant = current_setting('app.tenant', true));
    
    DROP POLICY IF EXISTS one_tenant ON audit_log;
    CREATE POLICY one_tenant ON audit_log
        USING (tenant = current_setting('app.tenant', true))
        WITH CHECK (tenant = current_setting('app.tenant', true));
    
    -- The grants make the log append-only and fix each employee's id, tenant and email.
    GRANT SELECT, INSERT ON employees TO directory_app;
    GRANT UPDATE (name, team, status) ON employees TO directory_app;
    GRANT SELECT, INSERT ON audit_log TO directory_app;
    pgstore: implements Storenew file, +165
    + // Package prod is the directory made production grade. It imports the 45-minute build and replaces
    + // the in-memory store behind its interface, then adds tenants, row-level security, metrics and
    + // health. The service and the handler do not change.
    + package prod
    + 
    + import (
    + 	"context"
    + 	"errors"
    + 	"fmt"
    + 
    + 	"github.com/jackc/pgx/v5"
    + 	"github.com/jackc/pgx/v5/pgconn"
    + 	"github.com/jackc/pgx/v5/pgxpool"
    + 
    + 	"github.com/rudrite/system-design/arena/exercises/directory/build"
    + )
    + 
    + // PGStore implements build.Store on Postgres.
    + type PGStore struct {
    + 	pool *pgxpool.Pool
    + }
    + 
    + // NewPGStore returns a store on pool.
    + func NewPGStore(pool *pgxpool.Pool) *PGStore {
    + 	return &PGStore{pool: pool}
    + }
    + 
    + // asTenant drops to the app role for one transaction and names the tenant. The role has no way
    + // around the policies, so a query that forgets a tenant filter still sees one tenant.
    + const asTenant = `SELECT set_config('role', 'directory_app', true), set_config('app.tenant', $1, true)`
    + 
    + func (s *PGStore) tx(ctx context.Context, fn func(pgx.Tx) error) error {
    + 	err := pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error {
    + 		if _, err := tx.Exec(ctx, asTenant, TenantFrom(ctx)); err != nil {
    + 			return fmt.Errorf("set tenant: %w", err)
    + 		}
    + 		return fn(tx)
    + 	})
    + 	var pgErr *pgconn.PgError
    + 	if errors.As(err, &pgErr) {
    + 		switch pgErr.Code {
    + 		case "23505": // unique_violation: the email is taken
    + 			return build.ErrConflict
    + 		case "22021": // bad encoding: a NUL byte or invalid UTF-8 from the client
    + 			return build.ErrInvalid
    + 		}
    + 	}
    + 	return err
    + }
    + 
    + const record = `INSERT INTO audit_log (actor, employee, before_row, after_row) VALUES ($1, $2, $3, $4)`
    + 
    + // Create writes the employee and its audit row in one transaction.
    + func (s *PGStore) Create(ctx context.Context, e build.Employee, actor string) error {
    + 	return s.tx(ctx, func(tx pgx.Tx) error {
    + 		_, err := tx.Exec(ctx, `INSERT INTO employees (id, name, email, team, status) VALUES ($1, $2, $3, $4, $5)`,
    + 			e.ID, e.Name, e.Email, e.Team, e.Status)
    + 		if err != nil {
    + 			return fmt.Errorf("insert employee: %w", err)
    + 		}
    + 		if _, err := tx.Exec(ctx, record, actor, e.ID, nil, e); err != nil {
    + 			return fmt.Errorf("insert audit row: %w", err)
    + 		}
    + 		return nil
    + 	})
    + }
    + 
    + const columns = `id, name, email, team, status`
    + 
    + func scan(row pgx.CollectableRow) (build.Employee, error) {
    + 	var e build.Employee
    + 	err := row.Scan(&e.ID, &e.Name, &e.Email, &e.Team, &e.Status)
    + 	return e, err
    + }
    + 
    + // Get returns one employee of the tenant. Another tenant's id reads as missing.
    + func (s *PGStore) Get(ctx context.Context, id string) (build.Employee, error) {
    + 	var e build.Employee
    + 	err := s.tx(ctx, func(tx pgx.Tx) error {
    + 		rows, err := tx.Query(ctx, `SELECT `+columns+` FROM employees WHERE id = $1`, id)
    + 		if err != nil {
    + 			return fmt.Errorf("get employee: %w", err)
    + 		}
    + 		e, err = pgx.CollectExactlyOneRow(rows, scan)
    + 		return err
    + 	})
    + 	if errors.Is(err, pgx.ErrNoRows) {
    + 		return e, build.ErrNotFound
    + 	}
    + 	return e, err
    + }
    + 
    + // Update locks the row, so parallel updates run one at a time, and writes the change and its audit
    + // row in one transaction.
    + func (s *PGStore) Update(ctx context.Context, id, actor string, fn func(*build.Employee) error) (build.Employee, error) {
    + 	var after build.Employee
    + 	err := s.tx(ctx, func(tx pgx.Tx) error {
    + 		rows, err := tx.Query(ctx, `SELECT `+columns+` FROM employees WHERE id = $1 FOR UPDATE`, id)
    + 		if err != nil {
    + 			return fmt.Errorf("lock employee: %w", err)
    + 		}
    + 		before, err := pgx.CollectExactlyOneRow(rows, scan)
    + 		if err != nil {
    + 			return err
    + 		}
    + 		after = before
    + 		if err := fn(&after); err != nil || after == before {
    + 			return err
    + 		}
    + 		_, err = tx.Exec(ctx, `UPDATE employees SET name = $2, team = $3, status = $4 WHERE id = $1`,
    + 			id, after.Name, after.Team, after.Status)
    + 		if err != nil {
    + 			return fmt.Errorf("update employee: %w", err)
    + 		}
    + 		if _, err := tx.Exec(ctx, record, actor, id, before, after); err != nil {
    + 			return fmt.Errorf("insert audit row: %w", err)
    + 		}
    + 		return nil
    + 	})
    + 	if errors.Is(err, pgx.ErrNoRows) {
    + 		return after, build.ErrNotFound
    + 	}
    + 	return after, err
    + }
    + 
    + // List is a keyset query: the row comparison starts just after the last row of the last page, and
    + // the index walks from there. It reads the page and nothing before it.
    + func (s *PGStore) List(ctx context.Context, q build.Query) ([]build.Employee, error) {
    + 	var out []build.Employee
    + 	err := s.tx(ctx, func(tx pgx.Tx) error {
    + 		rows, err := tx.Query(ctx, `
    + SELECT `+columns+` FROM employees
    + WHERE ($1 = '' OR team = $1) AND ($2 = '' OR status = $2) AND (name, id) > ($3, $4)
    + ORDER BY name, id
    + LIMIT $5`, q.Team, q.Status, q.After.Name, q.After.ID, q.Limit)
    + 		if err != nil {
    + 			return fmt.Errorf("list employees: %w", err)
    + 		}
    + 		out, err = pgx.CollectRows(rows, scan)
    + 		return err
    + 	})
    + 	return out, err
    + }
    + 
    + // Log returns audit rows after seq, oldest first.
    + func (s *PGStore) Log(ctx context.Context, employee string, after int64, limit int) ([]build.Audit, error) {
    + 	var out []build.Audit
    + 	err := s.tx(ctx, func(tx pgx.Tx) error {
    + 		rows, err := tx.Query(ctx, `
    + SELECT seq, at, actor, employee, before_row, after_row FROM audit_log
    + WHERE ($1 = '' OR employee = $1) AND seq > $2
    + ORDER BY seq
    + LIMIT $3`, employee, after, limit)
    + 		if err != nil {
    + 			return fmt.Errorf("read audit log: %w", err)
    + 		}
    + 		out, err = pgx.CollectRows(rows, func(row pgx.CollectableRow) (build.Audit, error) {
    + 			var a build.Audit
    + 			err := row.Scan(&a.Seq, &a.At, &a.Actor, &a.Employee, &a.Before, &a.After)
    + 			return a, err
    + 		})
    + 		return err
    + 	})
    + 	return out, err
    + }
    server: wraps the build's handlernew file, +89
    + package prod
    + 
    + import (
    + 	"context"
    + 	_ "embed"
    + 	"fmt"
    + 	"net/http"
    + 	"strings"
    + 	"time"
    + 
    + 	"github.com/jackc/pgx/v5/pgxpool"
    + 
    + 	"github.com/rudrite/system-design/arena/exercises/directory/build"
    + 	kv "github.com/rudrite/system-design/arena/exercises/kvstore/prod"
    + )
    + 
    + //go:embed schema.sql
    + var schema string
    + 
    + // Migrate applies the schema. It is safe to run twice.
    + func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
    + 	if _, err := pool.Exec(ctx, schema); err != nil {
    + 		return fmt.Errorf("apply schema: %w", err)
    + 	}
    + 	return nil
    + }
    + 
    + type tenantKey struct{}
    + 
    + // TenantFrom returns the caller's tenant.
    + func TenantFrom(ctx context.Context) string {
    + 	tenant, _ := ctx.Value(tenantKey{}).(string)
    + 	return tenant
    + }
    + 
    + // WithTenant returns ctx for one tenant, for code that reaches the store without a request.
    + func WithTenant(ctx context.Context, tenant string) context.Context {
    + 	return context.WithValue(ctx, tenantKey{}, tenant)
    + }
    + 
    + // Tenants maps a token to its tenant.
    + type Tenants map[string]string
    + 
    + // ParseTokens reads "tenant:role:token,tenant:role:token". The role name is also the actor in the
    + // audit log. A real deployment gives each person a token of their own.
    + func ParseTokens(s string) (build.Tokens, Tenants, error) {
    + 	ranks := map[string]int{"viewer": build.Viewer, "editor": build.Editor, "admin": build.Admin}
    + 	tokens, tenants := build.Tokens{}, Tenants{}
    + 	for part := range strings.SplitSeq(s, ",") {
    + 		fields := strings.SplitN(part, ":", 3)
    + 		if len(fields) != 3 || fields[0] == "" || fields[2] == "" || ranks[fields[1]] == 0 {
    + 			return nil, nil, fmt.Errorf("token list: want tenant:role:token, got %q", part)
    + 		}
    + 		tokens[fields[2]] = build.Caller{Name: fields[1], Rank: ranks[fields[1]]}
    + 		tenants[fields[2]] = fields[0]
    + 	}
    + 	return tokens, tenants, nil
    + }
    + 
    + // scoped puts the token's tenant on the context. The build's handler still answers 401 and 403.
    + func scoped(tenants Tenants, next http.Handler) http.Handler {
    + 	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    + 		token := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
    + 		next.ServeHTTP(w, r.WithContext(WithTenant(r.Context(), tenants[token])))
    + 	})
    + }
    + 
    + // maxBody limits a request body. A larger one fails to decode and answers 400.
    + const maxBody = 1 << 20
    + 
    + // Handler serves the API, plus the two routes an operator needs. Neither of those takes a token:
    + // the load balancer and the metrics scraper have none.
    + func Handler(pool *pgxpool.Pool, tokens build.Tokens, tenants Tenants, metrics *kv.Metrics) http.Handler {
    + 	api := build.Handler(&build.Service{Store: NewPGStore(pool)}, tokens)
    + 
    + 	mux := http.NewServeMux()
    + 	mux.Handle("/", metrics.Wrap(scoped(tenants, http.MaxBytesHandler(api, maxBody))))
    + 	mux.Handle("GET /metrics", metrics)
    + 	mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
    + 		ctx, cancel := context.WithTimeout(r.Context(), time.Second)
    + 		defer cancel()
    + 		if err := pool.Ping(ctx); err != nil {
    + 			http.Error(w, "database unreachable", http.StatusServiceUnavailable)
    + 			return
    + 		}
    + 		w.WriteHeader(http.StatusNoContent)
    + 	})
    + 	return mux
    + }

    The schema is where this diff does its work. The policies and the grants are short, and they cover every query.

    R

    Drill

    predict, then reveal

    0 of 10 known

    1. The list sorts by name only. A page ends between two people called Ann. What goes wrong?

    2. Page 1 is bob and cat. A client adds abe, then asks for OFFSET 2. What is on page 2?

    3. Same walk with a cursor. A client adds dan after page 1. Does the reader see dan?

    4. Why ask the store for limit + 1 rows?

    5. Why must a cursor be opaque?

    6. A viewer sends PATCH with a malformed body to an id that does not exist. Which status?

    7. An update reads the employee, applies the change under the lock, then appends the audit row after the unlock. What breaks?

    8. Why is a PATCH that changes nothing not an audit row?

    9. Why does the email stay fixed after create in this build?

    10. A transaction sets the role and the tenant with set_config and true as the third argument. Why true?

    S

    Numbers to say

    from the files and tests
    build
    451 lines with tests, 19:59 of typing at 100 words a minute.
    checks
    33 grader checks, in 4 groups.
    walk
    A list of 30 rows, walked while 99 clients insert. Every row appears once.
    chain
    100 parallel updates add 100 audit rows, in a chain with no break.
    page
    20 rows by default, 100 at most.
    deep page
    OFFSET 49,000 reads 49,021 rows. The keyset query starts in the index.
    body limit
    1 MiB in production.

    Design values from the tested code, not load measurements.