System Design

E4

Expense rules engine

The rule types take minutes. The test is the shape: can you add a rule without touching what exists? The second test is a trip limit when many expenses arrive at once.

Not startedSaved in this browser only.
  1. 1A rule is a type with one question: do these facts pass? A composite is a rule that asks its children.
  2. 2A new rule is one new type and one line that registers it. No other code changes.
  3. 3The trip total, the verdict and the save are one atomic step. A total read before that step gives a wrong verdict and a right sum.
  4. 4Production swaps one interface. The rules, the service and the handler do not change.
E4
    A

    The spec

    as the interviewer states it
    Build an expense rules engine as an HTTP service, in memory. A company creates rules: no single expense over a limit, no entertainment, trip totals under a limit. Employees submit expenses. List the violations for an expense and for a trip. Then add composite rules with AND, OR and NOT. We will add new rule types often, so make that easy. Many expenses arrive at once.
    askanswer assumed
    When is an expense judged?At submission. The verdict is saved and does not change.
    Does a new rule apply to old expenses?No. It applies from its creation on.
    Which expense breaks a trip limit?The one that crosses the limit, and every one after it.
    Whose rules?A policy is a named set of rules. A trip belongs to one policy.
    Money?Integer cents in one currency. Amounts from 1 to 10,000,000,000.
    Edit or delete an expense?Not in the build. Mention it in the talk.

    Before I type, I confirm that a verdict is decided at submission, and that a rule does not reach back to old expenses.

    B

    The endpoints

    the contract the grader checks
    requestsuccesserrors
    POST /policies/{policy}/rules201 id, name, rule400
    POST /policies/{policy}/expenses201 id, violations400
    GET /policies/{policy}/expenses/{id}200 id, violations404
    GET /policies/{policy}/trips/{id}200 trip, total, violations404
    rule typefieldspasses when
    max_amountlimitThe amount is at most the limit.
    no_categorycategoryThe category differs.
    trip_totallimitThe trip total, with this expense, is at most the limit.
    and, orrulesAll children pass; any child passes.
    notruleThe child fails.
    • An expense has the fields trip, category and amount.
    • A rule has the fields name and rule. The rule field holds the tree.
    • violations is a list, and it is empty when nothing failed. Each item has expense, rule and name.

    The tree is plain JSON, and each node has a type. The grader posts trees of any depth.

    C

    The checkpoints

    15, 30 and 45 minutes
    bybuildproofif you are late
    15 minThe kit, renamed. The Rule interface, MaxAmount and NoCategory. Create a rule, submit an expense.TestRulesHard-code the two rule types for now. Keep the interface.
    30 minTrips, TripTotal and the Submit that judges inside the lock. The two read routes.TestTripTotalSkip the expense route. The trip route shows the same data.
    45 minTree, the registry, And, Or and Not. Race test.TestComposites, TestParallelSubmitsBuild And and Not, and say: "Or is the same with one word changed."

    I keep a running service at each checkpoint. If I am late at 30 minutes, I skip the composites and describe them, because they are three small types.

    D

    The core idea

    one rule, one expense
    expense: category fun, amount 8000trip total with this expense: 60000orfailno_categoryfunfailandfailmax_amount10000passtrip_total50000failA composite only calls Pass on its children. It never asks what they are.

    Every node answers one question. A composite asks its children and combines the answers. The top answer decides the violation.

    E

    Why it fits

    computed from the files
    partvalue
    Lines, with tests455
    Typed characters9,935
    Typing at 500 a minute19:52
    Typing at 300 a minute33:07
    Left for thinking, at 500 a minute25:08
    Dependencies0
    • Say the shape before you type it: one interface, one registry.
    • 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 rule types and the atomic submit.

    F

    rules.go

    reference build
    rules.gogo
    package build
    
    import (
    	"encoding/json"
    	"errors"
    	"fmt"
    	"slices"
    )
    
    // Facts is everything a rule may read: one expense, and its trip with that expense counted.
    type Facts struct {1
    	Expense   Expense
    	TripTotal int64
    }
    
    // Rule is one type of check. Pass says whether the facts comply. Valid checks the rule's own
    // settings after it is read from JSON.
    type Rule interface {
    	Pass(f Facts) bool2
    	Valid() error
    }
    
    var kinds = map[string]func(json.RawMessage) (Rule, error){}
    
    // Register adds a rule type. A new type calls it from its own init, and no other code changes.
    func Register[R Rule](kind string) {3
    	kinds[kind] = func(raw json.RawMessage) (Rule, error) {
    		var r R
    		if err := json.Unmarshal(raw, &r); err != nil {
    			return nil, err
    		}
    		return r, r.Valid()
    	}
    }
    
    // Tree is a rule read from JSON, leaf or composite. It keeps the JSON, so a store can save it.
    type Tree struct {
    	Rule
    	raw json.RawMessage
    }
    
    func (t *Tree) UnmarshalJSON(raw []byte) error {4
    	var head struct{ Type string }
    	if err := json.Unmarshal(raw, &head); err != nil {
    		return err
    	}
    	parse, ok := kinds[head.Type]
    	if !ok {
    		return fmt.Errorf("unknown rule type %q", head.Type)
    	}
    	rule, err := parse(raw)
    	if err != nil {
    		return err
    	}
    	t.Rule, t.raw = rule, slices.Clone(raw)5
    	return nil
    }
    
    func (t Tree) MarshalJSON() ([]byte, error) {
    	return t.raw, nil
    }
    
    func init() {
    	Register[MaxAmount]("max_amount")
    	Register[NoCategory]("no_category")
    	Register[TripTotal]("trip_total")
    	Register[And]("and")
    	Register[Or]("or")
    	Register[Not]("not")
    }
    
    // need turns a check on a rule's settings into the error Valid returns.
    func need(ok bool, message string) error {
    	if !ok {
    		return errors.New(message)
    	}
    	return nil
    }
    
    // MaxAmount: no single expense over the limit.
    type MaxAmount struct{ Limit int64 }
    
    func (r MaxAmount) Pass(f Facts) bool { return f.Expense.Amount <= r.Limit }
    func (r MaxAmount) Valid() error      { return need(r.Limit > 0, "limit must be positive") }
    
    // NoCategory: no expense in this category.
    type NoCategory struct{ Category string }
    
    func (r NoCategory) Pass(f Facts) bool { return f.Expense.Category != r.Category }
    func (r NoCategory) Valid() error      { return need(r.Category != "", "category is required") }
    
    // TripTotal: the trip stays under the limit, counted up to and including this expense.
    type TripTotal struct{ Limit int64 }
    
    func (r TripTotal) Pass(f Facts) bool { return f.TripTotal <= r.Limit }6
    func (r TripTotal) Valid() error      { return need(r.Limit > 0, "limit must be positive") }
    
    // And passes when every child passes.
    type And struct{ Rules []Tree }
    
    func (r And) Pass(f Facts) bool {
    	return !slices.ContainsFunc(r.Rules, func(c Tree) bool { return !c.Pass(f) })
    }
    func (r And) Valid() error { return need(len(r.Rules) > 0, "rules are required") }
    
    // Or passes when any child passes.
    type Or struct{ Rules []Tree }
    
    func (r Or) Pass(f Facts) bool {
    	return slices.ContainsFunc(r.Rules, func(c Tree) bool { return c.Pass(f) })
    }
    func (r Or) Valid() error { return need(len(r.Rules) > 0, "rules are required") }
    
    // Not passes when its child fails.
    type Not struct{ Rule Tree }
    
    func (r Not) Pass(f Facts) bool { return !r.Rule.Pass(f) }
    func (r Not) Valid() error7      { return need(r.Rule.Rule != nil, "rule is required") }
    
    1. 1The only input a rule gets. A rule cannot read the store, so it stays a pure function and runs inside any lock.
    2. 2One question. A composite and a leaf answer it the same way, so a tree of any shape works.
    3. 3A generic function writes the JSON parser for each type. A new type needs no parser of its own.
    4. 4Reads the type name, then decodes the same bytes into the right struct. Children meet this same method, so trees of any depth decode.
    5. 5Keeps the JSON as sent. The Postgres store saves these bytes, so a type it has never seen needs no schema change. The clone matters: the decoder reuses its buffer.
    6. 6A trip rule has the same shape as an expense rule. The trip total is one more fact.
    7. 7A missing child fails here, at the POST. Without this check, the first expense would panic.

    This file matters most. Everything a rule may read is in Facts. Every rule type is a struct with two methods and one line in the registry.

    G

    A new rule type

    the follow-up, tested
    one new typenew file
    // CategoryCap: no expense in one category over a limit. This one type, in a file of its own, is
    // the whole change. The tree, the service, the store and the handler stay as they are.
    type CategoryCap struct {
      Category string
      Limit    int64
    }
    
    func (r CategoryCap) Pass(f Facts) bool {
      return f.Expense.Category != r.Category || f.Expense.Amount <= r.Limit
    }
    func (r CategoryCap) Valid() error { return need(r.Limit > 0, "limit must be positive") }
    
    func init() { Register[CategoryCap]("category_cap") }
    
    the new rule needsyou changestatus
    Facts that exist alreadyOne new typeApproved
    A new field on the expenseOne new type and one field on ExpenseOne more line
    A count of expenses in the tripOne new type, one field on Facts, one line in each storeSay it first
    Other expenses in the trip, such as duplicatesA new query before judgingChange Facts

    Tested: this rule posts and evaluates inside a not, with no other change. In production, a rule type added the same way needs no migration.

    The interviewer asks for a new rule. I add one type in a new file, and the tree, the service, the store and the handler stay as they are. It works inside not at once.

    H

    store.go

    reference build
    store.gogo
    package build
    
    import (
    	"context"
    	"errors"
    	"sync"
    )
    
    var (
    	ErrInvalid  = errors.New("invalid")
    	ErrNotFound = errors.New("not found")
    )
    
    // Expense is one submitted expense. Amount is in cents.
    type Expense struct {
    	ID         string      `json:"id"`
    	Trip       string      `json:"trip"`
    	Category   string      `json:"category"`
    	Amount     int64       `json:"amount"`
    	Violations []Violation `json:"violations"`
    }
    
    // Violation says that one expense broke one rule.
    type Violation struct {
    	Expense string `json:"expense"`
    	Rule    string `json:"rule"`
    	Name    string `json:"name"`
    }
    
    // PolicyRule is one rule of a policy.
    type PolicyRule struct {
    	ID   string `json:"id"`
    	Name string `json:"name"`
    	Tree Tree   `json:"rule"`
    }
    
    // Trip is the running state of one trip.
    type Trip struct {
    	ID         string      `json:"trip"`
    	Total      int64       `json:"total"`
    	Violations []Violation `json:"violations"`
    }
    
    // Judge turns the facts of one expense into its violations.
    type Judge func(rules []PolicyRule, f Facts) []Violation2
    
    type Store interface {
    	AddRule(ctx context.Context, policy string, rule PolicyRule) error
    	// Submit counts e in its trip, judges the new facts and saves the verdict, as one atomic step.
    	Submit(ctx context.Context, policy string, e Expense, judge Judge) (Expense, error)3
    	Expense(ctx context.Context, policy, id string) (Expense, error)
    	Trip(ctx context.Context, policy, id string) (Trip, error)
    }
    
    type key struct{ policy, id string }4
    
    type MemStore struct {
    	mu       sync.Mutex
    	rules    map[string][]PolicyRule
    	trips    map[key]*Trip
    	expenses map[key]Expense
    }
    
    func NewMemStore() *MemStore {
    	return &MemStore{rules: map[string][]PolicyRule{}, trips: map[key]*Trip{}, expenses: map[key]Expense{}}
    }
    
    func (s *MemStore) AddRule(_ context.Context, policy string, rule PolicyRule) error {
    	s.mu.Lock()
    	defer s.mu.Unlock()
    	s.rules[policy] = append(s.rules[policy], rule)
    	return nil
    }
    
    func (s *MemStore) Submit(_ context.Context, policy string, e Expense, judge Judge) (Expense, error) {
    	s.mu.Lock()
    	defer s.mu.Unlock()
    	k := key{policy, e.Trip}
    	trip, ok := s.trips[k]
    	if !ok {
    		trip = &Trip{ID: e.Trip, Violations: []Violation{}}
    		s.trips[k] = trip
    	}
    	trip.Total += e.Amount5
    	e.Violations = judge(s.rules[policy], Facts{e, trip.Total})6
    	trip.Violations = append(trip.Violations, e.Violations...)
    	s.expenses[key{policy, e.ID}] = e
    	return e, nil
    }
    
    func (s *MemStore) Expense(_ context.Context, policy, id string) (Expense, error) {
    	s.mu.Lock()
    	defer s.mu.Unlock()
    	e, ok := s.expenses[key{policy, id}]
    	if !ok {
    		return Expense{}, ErrNotFound
    	}
    	return e, nil
    }
    
    func (s *MemStore) Trip(_ context.Context, policy, id string) (Trip, error) {
    	s.mu.Lock()
    	defer s.mu.Unlock()
    	trip, ok := s.trips[key{policy, id}]
    	if !ok {
    		return Trip{}, ErrNotFound
    	}
    	return *trip, nil
    }
    
    1. 1Saved on the expense at submission. A read never runs a rule, so a verdict cannot change later.
    2. 2The service passes its logic in, and the store chooses when it runs. This is the seam between the two.
    3. 3The interface states the rule: all of this is one step. The Postgres store implements it with one transaction.
    4. 4A struct key, not a joined string. A slash in a name cannot make two keys collide.
    5. 5The add comes first, so a rule sees the total with this expense counted.
    6. 6Inside the lock. Move this line out and the sum stays right, but the verdicts go wrong under load.

    Submit is the one write path. It adds to the trip, runs the judge and saves, under one lock, so the verdict uses the true total.

    I

    service.go

    reference build
    service.gogo
    package build
    
    import (
    	"context"
    	"crypto/rand"
    	"fmt"
    )
    
    // maxAmount is 100 million dollars in cents. It keeps a trip total far from overflow.
    const maxAmount = 10_000_000_0001
    
    // Service adds the rules of the domain to a Store. Reads pass straight through.
    type Service struct {
    	Store
    }
    
    func NewService(store Store) *Service {
    	return &Service{store}
    }
    
    func (s *Service) NewRule(ctx context.Context, policy string, rule PolicyRule) (PolicyRule, error) {
    	if rule.Name == "" || rule.Tree.Rule == nil {
    		return rule, fmt.Errorf("%w: name and rule are required", ErrInvalid)
    	}
    	rule.ID = rand.Text()3
    	return rule, s.Store.AddRule(ctx, policy, rule)
    }
    
    func (s *Service) NewExpense(ctx context.Context, policy string, e Expense) (Expense, error) {
    	if e.Trip == "" || e.Category == "" {
    		return e, fmt.Errorf("%w: trip and category are required", ErrInvalid)
    	}
    	if e.Amount <= 0 || e.Amount > maxAmount {
    		return e, fmt.Errorf("%w: amount must be from 1 to %d cents", ErrInvalid, maxAmount)
    	}
    	e.ID = rand.Text()
    	return s.Store.Submit(ctx, policy, e, judge)
    }
    
    // judge runs every rule of the policy on one expense. It reads nothing but its arguments, so it
    // can run inside any store's atomic step.
    func judge(rules []PolicyRule, f Facts) []Violation {4
    	found := []Violation{}5
    	for _, rule := range rules {
    		if !rule.Tree.Pass(f) {
    			found = append(found, Violation{f.Expense.ID, rule.ID, rule.Name})
    		}
    	}
    	return found
    }
    
    1. 1A limit on input keeps a trip total far from the end of int64. Without it, a total could wrap to a negative number and pass every limit.
    2. 2Embedding gives the service Expense and Trip with no code. Handlers still call only the service.
    3. 3The server picks every ID, so a client cannot collide with another client.
    4. 4A pure function: rules and facts in, violations out. It cannot deadlock or read stale data.
    5. 5Not nil. A nil slice encodes as null, and the contract says a list.

    The service checks the input and passes judge to the store. Reads go straight through, so the embedded store saves me typing.

    J

    handler.go and main.go

    reference build
    handler.gogo
    package build
    
    import (
    	"encoding/json"
    	"errors"
    	"fmt"
    	"log"
    	"net/http"
    )
    
    func Handler(svc *Service) http.Handler {
    	mux := http.NewServeMux()
    	mux.Handle("POST /policies/{policy}/rules", route(201, func(r *http.Request) (any, error) {
    		var rule PolicyRule1
    		if err := readJSON(r, &rule); err != nil {
    			return nil, err
    		}
    		return svc.NewRule(r.Context(), r.PathValue("policy"), rule)
    	}))
    	mux.Handle("POST /policies/{policy}/expenses", route(201, func(r *http.Request) (any, error) {
    		var e Expense
    		if err := readJSON(r, &e); err != nil {
    			return nil, err
    		}
    		return svc.NewExpense(r.Context(), r.PathValue("policy"), e)
    	}))
    	mux.Handle("GET /policies/{policy}/expenses/{id}", route(200, func(r *http.Request) (any, error) {
    		return svc.Expense(r.Context(), r.PathValue("policy"), r.PathValue("id"))
    	}))
    	mux.Handle("GET /policies/{policy}/trips/{id}", route(200, func(r *http.Request) (any, error) {
    		return svc.Trip(r.Context(), r.PathValue("policy"), r.PathValue("id"))
    	}))
    	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)
    		}
    		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) {2
    	status := 500
    	switch {
    	case errors.Is(err, ErrInvalid):
    		status = 400
    	case errors.Is(err, ErrNotFound):
    		status = 404
    	default:
    		log.Print(err)
    		err = errors.New("internal error")
    	}
    	return status, map[string]string{"error": err.Error()}
    }
    
    1. 1Decoding this runs the whole tree parse and every Valid. A bad tree never reaches the service as a tree.
    2. 2The one place that maps errors to status codes. Anything unknown is a logged 500.
    main.gogo
    // Command main serves the 45-minute expense rules engine.
    package main
    
    import (
    	"log"
    	"net/http"
    
    	"github.com/rudrite/system-design/arena/exercises/expenses/build"
    )
    
    func main() {
    	handler := build.Handler(build.NewService(build.NewMemStore()))
    	log.Fatal(http.ListenAndServe(":8080", handler))
    }
    

    The handler decodes and calls the service. A decode error is 400, and a bad tree fails in the decode.

    K

    build_test.go

    type this part too
    build_test.gogo
    package build
    
    import (
    	"fmt"
    	"net/http"
    	"net/http/httptest"
    	"strings"
    	"sync"
    	"testing"
    )
    
    type step struct {
    	method, path, body string
    	status             int
    	want               string
    }
    
    func do(h http.Handler, method, path, body string) (int, string) {
    	w := httptest.NewRecorder()
    	h.ServeHTTP(w, httptest.NewRequest(method, path, strings.NewReader(body)))
    	return w.Code, w.Body.String()
    }
    
    func run(t *testing.T, h http.Handler, steps []step) {
    	t.Helper()
    	for i, s := range steps {
    		status, body := do(h, s.method, s.path, s.body)
    		if status != s.status || !strings.Contains(body, s.want) {
    			t.Errorf("step %d, %s %s: got %d %s", i, s.method, s.path, status, body)
    		}
    	}
    }
    
    func newHandler() http.Handler {
    	return Handler(NewService(NewMemStore()))
    }
    
    func rule(tree string) string {
    	return `{"name":"r","rule":` + tree + `}`
    }
    
    func expense(trip, category string, amount int) string {
    	return fmt.Sprintf(`{"trip":%q,"category":%q,"amount":%d}`, trip, category, amount)
    }
    
    const (
    	rules, expenses = "/policies/p/rules", "/policies/p/expenses"
    	tripA           = "/policies/p/trips/a"
    	clean           = `"violations":[]`
    )
    
    func TestRules(t *testing.T) {
    	run(t, newHandler(), []step{
    		{"POST", rules, rule(`{"type":"max_amount","limit":500}`), 201, ""},
    		{"POST", rules, rule(`{"type":"no_category","category":"fun"}`), 201, ""},
    		{"POST", expenses, expense("a", "food", 500), 201, clean},
    		{"POST", expenses, expense("a", "fun", 501), 201, `"name":"r"},{`},1
    		{"POST", rules, rule(`{"type":"nope"}`), 400, "unknown rule type"},
    	})
    }
    
    func TestTripTotal(t *testing.T) {
    	run(t, newHandler(), []step{
    		{"POST", rules, rule(`{"type":"trip_total","limit":100}`), 201, ""},
    		{"POST", expenses, expense("a", "food", 100), 201, clean},
    		{"POST", expenses, expense("b", "food", 100), 201, clean},2
    		{"POST", expenses, expense("a", "food", 1), 201, `"name":"r"`},
    		{"GET", tripA, "", 200, `"total":101`},
    	})
    }
    
    func TestComposites(t *testing.T) {
    	tree := `{"type":"or","rules":[{"type":"no_category","category":"fun"},{"type":"and","rules":[
    		{"type":"max_amount","limit":99},{"type":"not","rule":{"type":"trip_total","limit":50}}]}]}`
    	run(t, newHandler(), []step{
    		{"POST", rules, rule(tree), 201, ""},
    		{"POST", expenses, expense("b", "fun", 10), 201, `"name":"r"`},
    		{"POST", expenses, expense("c", "fun", 60), 201, clean},
    	})
    }
    
    func TestParallelSubmits(t *testing.T) {
    	h := newHandler()
    	do(h, "POST", rules, rule(`{"type":"trip_total","limit":6000}`))
    	var wg sync.WaitGroup
    	for range 100 {
    		wg.Go(func() { do(h, "POST", expenses, expense("a", "food", 100)) })
    	}
    	wg.Wait()
    	_, body := do(h, "GET", tripA, "")
    	if !strings.Contains(body, `"total":10000`) || strings.Count(body, `"rule":`) != 403 {
    		t.Fatal(body)
    	}
    }
    
    1. 1The text "},{" appears only between two list items, so this row proves that both rules fired.
    2. 2Trip b does not share a total with trip a.
    3. 3A limit of 6000 allows 60 of 100 expenses of 100. Exactly 40 must fail, whichever order they arrive in.

    Each test is a list of steps, so a new behaviour is one row. The race test states the exact number that must fail.

    L

    The grader agrees

    32 checks, saved from a real run
    reportsaved output
    arena run expenses --base http://localhost:8080
    
    correctness
      PASS  an expense with no rules has no violations
      PASS  max_amount: at the limit passes, one cent over fails
      PASS  no_category fails only its category
      PASS  a violation carries the rule's name and the expense
      PASS  one expense can break two rules
      PASS  trip_total adds up across expenses
      PASS  every expense after the trip limit fails too
      PASS  trips add up apart
      PASS  policies are apart
      PASS  a rule applies from its creation on
      PASS  the expense route lists its violations
      PASS  the trip route lists every violation and the total
      PASS  and fails when either child fails
      PASS  or fails only when both children fail
      PASS  not inverts its child
      PASS  a tree nests to any depth
      PASS  a composite can mix trip and expense rules
    
    status codes
      PASS  a new rule is 201 and returns an id
      PASS  a new expense is 201 and returns an id
      PASS  an unknown expense is 404
      PASS  an unknown trip is 404
      PASS  an expense of another policy is 404
    
    validation
      PASS  malformed JSON is 400
      PASS  a bad rule is 400
      PASS  a rule with no name or no tree is 400
      PASS  a bad expense is 400
      PASS  a refused expense does not count toward the trip
    
    concurrency
      PASS  100 parallel submissions to one trip: the total is exact
      PASS  100 parallel submissions over a trip limit: exactly the excess fails
      PASS  100 parallel submissions to 10 trips stay apart
      PASS  100 parallel new rules all apply
      PASS  reads during parallel submissions: total and violations agree
    
    32 checks: 32 passed, 0 failed

    All checks pass, with 100 parallel submissions in each race.

    M

    The check that matters

    the right sum and the wrong verdict
    checks.gogo
    {Name: "100 parallel submissions over a trip limit: exactly the excess fails", Group: grader.Concurrency, Run: func(t *grader.T) {
      p := t.Key("p")
      id := rule(t, p, "trip cap", tripTotal(6000))
      var flagged atomic.Int64
      t.Parallel(parallel, func(int) {
        e := submit(t, p, "t", "food", 100)
        if slices.ContainsFunc(e.Violations, func(v violation) bool { return v.Rule == id }) {
          flagged.Add(1)
        }
      })
      if flagged.Load() != 40 {1
        t.Failf("the limit allows 60 of 100 expenses, so 40 must fail; %d failed", flagged.Load())
      }
      if got := len(trip(t, p, "t").Violations); got != 40 {
        t.Failf("the trip lists %d violations, want 40", got)
      }
    }},
    1. 1A stale total lets extra expenses pass, so fewer than 40 fail.

    A server that reads the total, unlocks, and judges with the old value. The race detector stays quiet, because each step holds the lock.

    reportsaved output, failures only
      FAIL  100 parallel submissions over a trip limit: exactly the excess fails
            the limit allows 60 of 100 expenses, so 40 must fail; 9 failed
    32 checks: 31 passed, 1 failed

    The total can be exact while the verdicts are wrong. So the check counts verdicts, not the sum.

    N

    Rules for the room

    what to do, what to avoid
    choicestatus
    One type per rule, behind one interfaceApproved
    A switch on the rule typeNot approved
    A rule that reads the store itselfNot approved
    One global mutex for the whole buildSay the cost
    Judge inside the atomic stepApproved
    Read the total, then call the storeNot approved
    Evaluate rules at read timeVerdicts drift
    A rule expression languageNot in 45 minutes
    Money as floatNot approved

    I say what I chose and what it costs, then I move on.

    O

    The talk map

    the second 45 minutes
    the interviewer asksthe answergoes deeper
    The company has 10,000 rules. What happens to submit?Every submission reads and runs all of them, and it holds the trip lock while it does. Index each rule by the fields its tree needs, so one expense runs a few dozen rules. The results must equal a full scan.C25 Expense-policy violations
    A rule changes. What about old expenses?In this build, a rule applies from its creation on, so old verdicts stay. To apply it to the past, run a backfill: chunks on a work queue, each one transaction. Keep a version on each rule, and store the version with each decision.C25 Expense-policy violations
    Which rules must stop a card, and which only report?Two paths share one evaluator. The in-line path decides inside the card deadline, from memory. The reporting path has every field and runs every rule. The Rule interface does not change.C25 Expense-policy violations
    Finance wants totals per department per week.Do not run that on the path that decides. Send each decision to a stream, and build the totals in a batch or stream job. The job can repeat, because each decision has a unique ID.B7 Stream and batch
    How do you store a tree in Postgres?As jsonb in one column. A new rule type then needs no migration. I do not model it as parent and child rows, because nothing queries inside a tree. The cost is that the database cannot check the shape, so the service validates it.D3 Data modeling
    Why a violations table and not a list on the expense?Reporting asks which expenses broke which rule, and that is a query over rows. One row per broken rule takes an index. It also copies the rule name, so an old decision reads the same after a rename.D3 Data modeling
    Run two instances. What breaks?The mutex covers one process, so the trip total race returns. The upsert on the trip row replaces the mutex. It adds the amount and returns the total in one statement, and it holds the row lock to commit.T4 Locks in the database
    Why not SUM the expenses in each submission?Under read committed, two transactions each sum without the other, and both pass. You would need a lock anyway. A stored total with a row lock gives the same answer, and it costs one row and not one row per expense.T2 Isolation levels
    The client times out and retries a submission.A retry would count the amount twice and move the trip over its limit. An Idempotency-Key header fixes this. The key row, the expense and the saved response commit in one database transaction. The same key with a different body gets 422.T9 Exactly-once
    One customer submits a thousand expenses a second on one trip.They wait on one row lock, one at a time. That is correct but slow. A trip has few expenses in real use, so I rate limit by owner and do not shard the row.B3 Rate limiting
    Who may see a trip?Every row carries the owner from the token, and every query filters on it. Another owner gets 404, so an ID reveals nothing. A real system adds roles: an employee, a manager, finance.O5 Security
    A rule tree comes from a client. Is that safe?Only because it is data and not code. The tree can only name registered types. Each level of a tree parses again, so the cost grows with depth times size, and production limits the body to 64 KiB.R3 Requirements to API

    I start from what the build lacks: scale of rules, rule changes, then two instances. I name each limit before the interviewer does.

    P

    The production shape

    what moves out of the process
    loadbalancerinstance 1auth, keys, buildinstance 2auth, keys, buildPostgrestripsone row: total, lockrulestree as jsonbexpenses, violationsone row per broken ruleidempotency_keyssaved responsesOne submission: lock the trip, read the rules, judge, save. Then commit.Two trips never wait for each other.

    Instances hold no state. One trip row lines up the writers of that trip, so two trips never wait for each other.

    Q

    What changes

    from build to production
    toolbuildproduction
    PostgresMemStore: maps and one mutexPGStore: five tables, one row lock per trip
    PostgresTree in memoryTree as jsonb, read back through the same decoder
    PostgresA retry counts twiceIdempotency-Key, saved in the same transaction; a reused key gets 422
    ServiceNo authBearer tokens, the same as E1; each row has an owner
    ServiceNo metricsRequests and time by route and status, the same as E1; health route
    ServiceListenAndServeTimeouts, a 64 KiB body limit, drain on SIGTERM

    Tested: production passes the same 32 grader checks. The real binary passes them over a socket, then exits cleanly on SIGTERM. A trip race across two instances gives exactly 40 failures.

    Not built: pagination of a trip's violations, a sweep of old idempotency keys, and rule versions.

    One interface, one new implementation, and wrappers around the same handler. The rules file does not change.

    R

    The diff

    build to production

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

    main.go+61 -4
    + // Command main serves the production expense rules engine. It reads DATABASE_URL, API_TOKENS
    + // (owner:token,owner:token) and ADDR, which defaults to :8080.
    - // Command main serves the 45-minute expense rules engine.
      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/expenses/prod"
    + 	kv "github.com/rudrite/system-design/arena/exercises/kvstore/prod"
    - 	"github.com/rudrite/system-design/arena/exercises/expenses/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, err := kv.ParseTokens(os.Getenv("API_TOKENS"))
    + 	if err != nil {
    + 		return err
    + 	}
    + 
    + 	srv := &http.Server{
    + 		Addr:              cmp.Or(os.Getenv("ADDR"), ":8080"),
    + 		Handler:           prod.Handler(pool, tokens, kv.NewMetrics()),
    + 		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.NewService(build.NewMemStore()))
    - 	log.Fatal(http.ListenAndServe(":8080", handler))
      }
    schema.sqlnew file
    CREATE TABLE IF NOT EXISTS rules (
        seq    bigserial PRIMARY KEY,
        id     text NOT NULL UNIQUE,
        owner  text NOT NULL,
        policy text NOT NULL,
        name   text NOT NULL,
        tree   jsonb NOT NULL
    );
    
    CREATE INDEX IF NOT EXISTS rules_policy ON rules (owner, policy, seq);
    
    CREATE TABLE IF NOT EXISTS trips (
        owner  text NOT NULL,
        policy text NOT NULL,
        id     text NOT NULL,
        total  bigint NOT NULL,
        PRIMARY KEY (owner, policy, id)
    );
    
    CREATE TABLE IF NOT EXISTS expenses (
        id       text PRIMARY KEY,
        owner    text NOT NULL,
        policy   text NOT NULL,
        trip     text NOT NULL,
        category text NOT NULL,
        amount   bigint NOT NULL CHECK (amount > 0),
        FOREIGN KEY (owner, policy, trip) REFERENCES trips (owner, policy, id)
    );
    
    -- One row per broken rule. The rule's name is copied, so a decision reads the same later.
    CREATE TABLE IF NOT EXISTS violations (
        seq     bigserial PRIMARY KEY,
        owner   text NOT NULL,
        policy  text NOT NULL,
        trip    text NOT NULL,
        expense text NOT NULL REFERENCES expenses (id),
        rule    text NOT NULL REFERENCES rules (id),
        name    text NOT NULL
    );
    
    CREATE INDEX IF NOT EXISTS violations_trip ON violations (owner, policy, trip, seq);
    CREATE INDEX IF NOT EXISTS violations_expense ON violations (expense, seq);
    pgstore: implements Storenew file, +153
    + // Package prod is the expense rules engine made production grade. It imports the 45-minute build
    + // and replaces the in-memory store behind its interface, then adds auth, metrics, health and safe
    + // retries. The rules, 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/expenses/build"
    + 	kv "github.com/rudrite/system-design/arena/exercises/kvstore/prod"
    + 	"github.com/rudrite/system-design/arena/internal/idempotent"
    + )
    + 
    + // PGStore implements build.Store on Postgres. Every row carries the token's owner, so another
    + // owner's IDs read as missing.
    + type PGStore struct {
    + 	pool *pgxpool.Pool
    + }
    + 
    + // NewPGStore returns a store on pool.
    + func NewPGStore(pool *pgxpool.Pool) *PGStore {
    + 	return &PGStore{pool: pool}
    + }
    + 
    + type querier interface {
    + 	Begin(context.Context) (pgx.Tx, error)
    + 	Exec(context.Context, string, ...any) (pgconn.CommandTag, error)
    + 	QueryRow(context.Context, string, ...any) pgx.Row
    + }
    + 
    + // conn joins the request's transaction when it has one, so the expense and the saved response land
    + // together. Otherwise it is the pool.
    + func (s *PGStore) conn(ctx context.Context) querier {
    + 	if tx, ok := idempotent.Tx(ctx); ok {
    + 		return tx
    + 	}
    + 	return s.pool
    + }
    + 
    + // AddRule saves the tree as the JSON the client sent.
    + func (s *PGStore) AddRule(ctx context.Context, policy string, rule build.PolicyRule) error {
    + 	_, err := s.conn(ctx).Exec(ctx, `INSERT INTO rules (id, owner, policy, name, tree) VALUES ($1, $2, $3, $4, $5)`,
    + 		rule.ID, kv.OwnerFrom(ctx), policy, rule.Name, rule.Tree)
    + 	if err != nil {
    + 		return fmt.Errorf("add rule: %w", err)
    + 	}
    + 	return nil
    + }
    + 
    + // addToTrip adds the amount and returns the new total in one statement. It leaves the row locked
    + // until commit, so the next expense on this trip waits and then sees this total.
    + const addToTrip = `
    + INSERT INTO trips (owner, policy, id, total) VALUES ($1, $2, $3, $4)
    + ON CONFLICT (owner, policy, id) DO UPDATE SET total = trips.total + excluded.total
    + RETURNING total`
    + 
    + const saveViolations = `
    + INSERT INTO violations (owner, policy, trip, expense, rule, name)
    + SELECT $1, $2, $3, $4, rule, name
    + FROM unnest($5::text[], $6::text[]) WITH ORDINALITY AS broken (rule, name, position)
    + ORDER BY position`
    + 
    + // Submit is one database transaction: count the expense, read the rules, judge, save.
    + func (s *PGStore) Submit(ctx context.Context, policy string, e build.Expense, judge build.Judge) (build.Expense, error) {
    + 	owner := kv.OwnerFrom(ctx)
    + 	err := pgx.BeginFunc(ctx, s.conn(ctx), func(tx pgx.Tx) error {
    + 		var total int64
    + 		if err := tx.QueryRow(ctx, addToTrip, owner, policy, e.Trip, e.Amount).Scan(&total); err != nil {
    + 			return fmt.Errorf("add to trip: %w", err)
    + 		}
    + 		rules, err := loadRules(ctx, tx, owner, policy)
    + 		if err != nil {
    + 			return err
    + 		}
    + 		e.Violations = judge(rules, build.Facts{Expense: e, TripTotal: total})
    + 
    + 		_, err = tx.Exec(ctx, `INSERT INTO expenses (id, owner, policy, trip, category, amount) VALUES ($1, $2, $3, $4, $5, $6)`,
    + 			e.ID, owner, policy, e.Trip, e.Category, e.Amount)
    + 		if err != nil {
    + 			return fmt.Errorf("save expense: %w", err)
    + 		}
    + 		ruleIDs, names := make([]string, len(e.Violations)), make([]string, len(e.Violations))
    + 		for i, v := range e.Violations {
    + 			ruleIDs[i], names[i] = v.Rule, v.Name
    + 		}
    + 		if _, err = tx.Exec(ctx, saveViolations, owner, policy, e.Trip, e.ID, ruleIDs, names); err != nil {
    + 			return fmt.Errorf("save violations: %w", err)
    + 		}
    + 		return nil
    + 	})
    + 	return e, err
    + }
    + 
    + func loadRules(ctx context.Context, tx pgx.Tx, owner, policy string) ([]build.PolicyRule, error) {
    + 	rows, err := tx.Query(ctx, `SELECT id, name, tree FROM rules WHERE owner = $1 AND policy = $2 ORDER BY seq`, owner, policy)
    + 	if err != nil {
    + 		return nil, fmt.Errorf("read rules: %w", err)
    + 	}
    + 	rules, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (build.PolicyRule, error) {
    + 		var r build.PolicyRule
    + 		err := row.Scan(&r.ID, &r.Name, &r.Tree)
    + 		return r, err
    + 	})
    + 	if err != nil {
    + 		return nil, fmt.Errorf("read rules: %w", err)
    + 	}
    + 	return rules, nil
    + }
    + 
    + // violationList builds the JSON list inside the read, so one statement sees one state.
    + const violationList = `
    + COALESCE(jsonb_agg(jsonb_build_object('expense', v.expense, 'rule', v.rule, 'name', v.name) ORDER BY v.seq), '[]')`
    + 
    + // Expense returns one expense with its violations.
    + func (s *PGStore) Expense(ctx context.Context, policy, id string) (build.Expense, error) {
    + 	e := build.Expense{ID: id}
    + 	err := s.conn(ctx).QueryRow(ctx, `
    + 		SELECT e.trip, e.category, e.amount,
    + 		       (SELECT `+violationList+` FROM violations v WHERE v.expense = e.id)
    + 		FROM expenses e WHERE e.id = $1 AND e.owner = $2 AND e.policy = $3`,
    + 		id, kv.OwnerFrom(ctx), policy).Scan(&e.Trip, &e.Category, &e.Amount, &e.Violations)
    + 	if errors.Is(err, pgx.ErrNoRows) {
    + 		return build.Expense{}, build.ErrNotFound
    + 	}
    + 	if err != nil {
    + 		return build.Expense{}, fmt.Errorf("read expense: %w", err)
    + 	}
    + 	return e, nil
    + }
    + 
    + // Trip returns the total and every violation of a trip.
    + func (s *PGStore) Trip(ctx context.Context, policy, id string) (build.Trip, error) {
    + 	trip := build.Trip{ID: id}
    + 	err := s.conn(ctx).QueryRow(ctx, `
    + 		SELECT t.total,
    + 		       (SELECT `+violationList+` FROM violations v
    + 		        WHERE v.owner = t.owner AND v.policy = t.policy AND v.trip = t.id)
    + 		FROM trips t WHERE t.owner = $1 AND t.policy = $2 AND t.id = $3`,
    + 		kv.OwnerFrom(ctx), policy, id).Scan(&trip.Total, &trip.Violations)
    + 	if errors.Is(err, pgx.ErrNoRows) {
    + 		return build.Trip{}, build.ErrNotFound
    + 	}
    + 	if err != nil {
    + 		return build.Trip{}, fmt.Errorf("read trip: %w", err)
    + 	}
    + 	return trip, nil
    + }
    server: wraps the build's handlernew file, +52
    + package prod
    + 
    + import (
    + 	"context"
    + 	_ "embed"
    + 	"fmt"
    + 	"net/http"
    + 	"time"
    + 
    + 	"github.com/jackc/pgx/v5/pgxpool"
    + 
    + 	"github.com/rudrite/system-design/arena/exercises/expenses/build"
    + 	kv "github.com/rudrite/system-design/arena/exercises/kvstore/prod"
    + 	"github.com/rudrite/system-design/arena/internal/idempotent"
    + )
    + 
    + //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+idempotent.Schema); err != nil {
    + 		return fmt.Errorf("apply schema: %w", err)
    + 	}
    + 	return nil
    + }
    + 
    + // maxBody limits a request body. Reading a tree parses each level again, so the cost of a request
    + // grows with its depth times its size. This limit keeps the worst tree small. A larger body
    + // answers 400.
    + const maxBody = 1 << 16
    + 
    + // Handler serves the API behind auth, plus the two routes an operator needs. The build's handler
    + // runs unchanged inside the wrappers.
    + func Handler(pool *pgxpool.Pool, tokens kv.Tokens, metrics *kv.Metrics) http.Handler {
    + 	api := build.Handler(build.NewService(NewPGStore(pool)))
    + 	retries := idempotent.Wrap(pool, kv.OwnerFrom, api)
    + 
    + 	mux := http.NewServeMux()
    + 	mux.Handle("/", metrics.Wrap(kv.Auth(tokens, http.MaxBytesHandler(retries, 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
    + }
    idempotent: safe retriesnew file, +141
    + // Package idempotent makes a POST safe to retry. A request with an Idempotency-Key header runs in
    + // one database transaction with the row that claims the key, so the work and the saved response
    + // land together or not at all. A retry gets the saved response and does no work.
    + package idempotent
    + 
    + import (
    + 	"bytes"
    + 	"context"
    + 	"crypto/sha256"
    + 	"errors"
    + 	"fmt"
    + 	"io"
    + 	"log"
    + 	"net/http"
    + 
    + 	"github.com/jackc/pgx/v5"
    + 	"github.com/jackc/pgx/v5/pgxpool"
    + )
    + 
    + // Schema is the table Wrap needs.
    + const Schema = `
    + CREATE TABLE IF NOT EXISTS idempotency_keys (
    +     owner      text NOT NULL,
    +     key        text NOT NULL,
    +     request    bytea NOT NULL,
    +     status     int,
    +     body       bytea,
    +     created_at timestamptz NOT NULL DEFAULT now(),
    +     PRIMARY KEY (owner, key)
    + );`
    + 
    + type txKey struct{}
    + 
    + // Tx returns the database transaction a request runs in, if it has one.
    + func Tx(ctx context.Context) (pgx.Tx, bool) {
    + 	tx, ok := ctx.Value(txKey{}).(pgx.Tx)
    + 	return tx, ok
    + }
    + 
    + // errRetry rolls the transaction back, so the key stays free and a retry does the work.
    + var errRetry = errors.New("server error")
    + 
    + // response holds what the handler wrote until the transaction ends.
    + type response struct {
    + 	header http.Header
    + 	status int
    + 	body   bytes.Buffer
    + }
    + 
    + func (r *response) Header() http.Header         { return r.header }
    + func (r *response) WriteHeader(status int)      { r.status = status }
    + func (r *response) Write(b []byte) (int, error) { return r.body.Write(b) }
    + 
    + func (r *response) send(w http.ResponseWriter) {
    + 	w.Header().Set("Content-Type", "application/json")
    + 	w.WriteHeader(r.status)
    + 	if _, err := w.Write(r.body.Bytes()); err != nil {
    + 		log.Print(err)
    + 	}
    + }
    + 
    + func refuse(w http.ResponseWriter, status int, message string) {
    + 	w.Header().Set("Content-Type", "application/json")
    + 	w.WriteHeader(status)
    + 	if _, err := fmt.Fprintf(w, `{"error":%q}`, message); err != nil {
    + 		log.Print(err)
    + 	}
    + }
    + 
    + // Wrap runs each POST that has a key once per owner. A second POST with the key gets the first
    + // response. A POST with the key and a different body gets 422, as the IETF draft for the header
    + // suggests. The draft's 409 for a request still in flight never applies here: that request waits
    + // for the first one, then gets one of these two answers. Other requests pass through.
    + func Wrap(pool *pgxpool.Pool, owner func(context.Context) string, next http.Handler) http.Handler {
    + 	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    + 		key := r.Header.Get("Idempotency-Key")
    + 		if key == "" || r.Method != http.MethodPost {
    + 			next.ServeHTTP(w, r)
    + 			return
    + 		}
    + 		body, err := io.ReadAll(r.Body)
    + 		if err != nil {
    + 			refuse(w, http.StatusBadRequest, "invalid: request body")
    + 			return
    + 		}
    + 		// The path is part of the fingerprint: one key must not cover two different routes.
    + 		request := sha256.Sum256(append([]byte(r.URL.Path+"\n"), body...))
    + 		r.Body = io.NopCloser(bytes.NewReader(body))
    + 
    + 		ctx := r.Context()
    + 		who := owner(ctx)
    + 		out := &response{header: http.Header{}, status: http.StatusOK}
    + 		err = pgx.BeginFunc(ctx, pool, func(tx pgx.Tx) error {
    + 			// A parallel request with this key waits here until the first one commits.
    + 			tag, err := tx.Exec(ctx, `
    + 				INSERT INTO idempotency_keys (owner, key, request) VALUES ($1, $2, $3)
    + 				ON CONFLICT DO NOTHING`, who, key, request[:])
    + 			if err != nil {
    + 				return fmt.Errorf("claim key: %w", err)
    + 			}
    + 			if tag.RowsAffected() == 0 {
    + 				return replay(ctx, tx, who, key, request[:], out)
    + 			}
    + 			next.ServeHTTP(out, r.WithContext(context.WithValue(ctx, txKey{}, tx)))
    + 			if out.status >= http.StatusInternalServerError {
    + 				return errRetry
    + 			}
    + 			_, err = tx.Exec(ctx, `UPDATE idempotency_keys SET status = $3, body = $4 WHERE owner = $1 AND key = $2`,
    + 				who, key, out.status, out.body.Bytes())
    + 			if err != nil {
    + 				return fmt.Errorf("save response: %w", err)
    + 			}
    + 			return nil
    + 		})
    + 		if err != nil && !errors.Is(err, errRetry) {
    + 			log.Print(err)
    + 			refuse(w, http.StatusInternalServerError, "internal error")
    + 			return
    + 		}
    + 		out.send(w)
    + 	})
    + }
    + 
    + func replay(ctx context.Context, tx pgx.Tx, who, key string, request []byte, out *response) error {
    + 	var (
    + 		saved []byte
    + 		body  []byte
    + 	)
    + 	err := tx.QueryRow(ctx, `SELECT request, status, body FROM idempotency_keys WHERE owner = $1 AND key = $2`,
    + 		who, key).Scan(&saved, &out.status, &body)
    + 	if err != nil {
    + 		return fmt.Errorf("read saved response: %w", err)
    + 	}
    + 	if !bytes.Equal(saved, request) {
    + 		out.status = http.StatusUnprocessableEntity
    + 		out.body.WriteString(`{"error":"conflict: this key was used with a different request"}` + "\n")
    + 		return nil
    + 	}
    + 	out.body.Write(body)
    + 	return nil
    + }

    The diff is one changed file and a few new ones. That is what the store interface in the build was for.

    S

    Drill

    predict, then reveal

    0 of 11 known

    1. You add a rule type by adding a case to a switch in the evaluator. What is the cost?

    2. And has a Rules field of type []Tree. How does Tree know which struct to decode?

    3. What happens to {"type":"not"} with no child?

    4. A limit is 100. Two expenses of 60 arrive at once. The handler reads the total, then calls Submit. What goes wrong?

    5. That race leaves the total correct. Why does the race detector stay quiet?

    6. Why is judge passed into Submit as a function?

    7. A trip is at 100, the limit is 100, and an expense of 1 arrives, then another. Which ones fail?

    8. What does NOT mean on a trip rule, if a violation is a rule that fails?

    9. In production, why is the rule read after the trip row lock?

    10. A 500 happens after the key row was inserted. What does a retry see?

    11. In production, one key arrives with a different body. What is the answer?

    T

    Numbers to say

    from the files and tests
    build
    455 lines with tests, 19:52 of typing at 100 words a minute.
    checks
    32 grader checks, in 4 groups.
    race
    100 expenses of 100 against a limit of 6000: exactly 40 fail.
    new rule
    One type, two methods, one line to register.
    amount
    At most 10,000,000,000 cents; 922 million of those fit in a trip total (derived).
    body limit
    64 KiB in production.

    Design values from the tested code, not load measurements.