System Design

C25

Expense-policy violations

A rules engine for corporate cards. The hard parts: a company's rules inside a card's deadline, a trip added up across expenses, and a rule that changes later.

Not startedSaved in this browser only.
  1. 1A rule is a versioned tree of predicates stored as JSON. A version never changes, and each decision stores the version and the facts it read.
  2. 2Two paths share one evaluator. The in-line path decides while the card waits, from memory. The reporting path has every field and runs every rule.
  3. 3An index derived from each tree means one expense reads a few dozen rules out of 10,000, with results equal to a full scan.
  4. 4A rule change is a backfill: chunks on a work queue, each one transaction, so a crash loses nothing and repeats nothing.
C25
    A

    The prompt

    as the interviewer says it
    "Design a corporate-card rules engine for per-expense and per-trip policies. It supports composite AND/OR/NOT rules, and it scales to millions of expenses and tens of thousands of rules."
    questionanswer assumed
    How many companies and expenses?10,000 companies, 20 million expenses a month.
    How many rules?50,000 in total. The largest company has up to 10,000.
    Who writes rules?Each company's finance team, in a builder.
    Must a rule stop a card?Some block at the swipe. Most flag for review.
    What is a trip?A booking names it. If not, a gap in spending ends it.
    What happens when a rule changes?History from its effective date is checked again.
    Must a decision be explained?Yes: which predicate failed, for years, for auditors.

    I clarify which rules must stop a card and which only report, because that splits the design into two paths.

    B

    Requirements

    as numbers
    functional
    Create and version rules with AND, OR and NOT.
    Decide a card swipe in-line.
    Evaluate each settled expense and each trip.
    Re-evaluate history when a rule changes.
    Explain each violation; keep an audit trail.
    non-functionaltarget
    In-line decisionp99 < 50 ms inside a 2 s deadline
    Rules read per expenseunder 1% at 10,000 rules
    Peak rate≈ 76 expenses/s
    Backfill of one large companyminutes, no effect on the card path
    Decisions lost or doubled by a crash0
    Explanation keptThe retention period of the audit

    The 2 s comes from one card-issuing API's published webhook limit; check your processor. It sets the order of magnitude.

    A card decision takes milliseconds from memory. A flag can take seconds, and it must say which predicate failed, for ever.

    C

    Estimates

    the arithmetic, on the board
    quantityarithmeticresult
    Average rate20 million ÷ 2,628,000 s≈ 7.6/s
    Peak rate10 × average, in working hours≈ 76/s
    Rules per company50,000 ÷ 10,0005 on average; 10,000 at most
    Expenses a year240 million × 181 B≈ 43 GB with indexes
    Violations a year5% × 240 million × 539 B≈ 6 GB with indexes
    Backfill, a large company1 million ÷ 350,000/s≈ 3 s at lab rates
    Backfill, every expense in a year240 million ÷ 350,000/s≈ 12 minutes at lab rates

    Inputs are the assumed answers in panel A; the 5% share of violations is a choice. Bytes per row, evaluation and backfill rates were measured in the lab, where the table fits in memory. A table of 240 million rows reads from disk, so plan for far less. Method: R2.

    About 76 expenses a second at peak. A server evaluates 580,000 a second at 10,000 rules, so rate is not the limit. The deadline, the backfill and the audit are.

    D

    API

    methods, bodies, status codes
    callsuccesserrorsretry safe?
    POST /authorizations {card, amount, category, merchant, country}200 approved, or declined with the rule429; on a timeout the processor's default appliesYes: a decision writes nothing
    PUT /expenses/{id} {revision, ...}200 verdicts409 older revisionYes: id and revision
    POST /rules/{id}/versions {tree, effective_from, backfill}201 version, backfill id422 with the reasonIdempotency-Key header
    GET /rules/{id}/versions200 every version, who, when404Yes: a read
    GET /expenses/{id}/violations200 rule version, failing predicates, facts404Yes: a read
    GET /backfills/{id}200 chunks done of total404Yes: a read

    A rule change returns a version and a backfill id. Every expense call is idempotent by id and revision, and every violation names a rule version.

    E

    Data model

    entities, then SQL
    rulescompany_idPKrule_idPKversionPKbodyjsonb treeeffective_froma version never changesactive_rulescompany_idPKrule_idPKversionFKone pointer a ruleviolationssubject_kindPKsubject_idPKrule_idPKversionPKfailures, factsjsonbopenflagone row a version a subjectbackfillsidPKchunks, donestatechunks commit onceexpensesidPKcompany_idtrip_idamount_centscategory, countryrevisionrisesan older revision is ignoredaudit_logidPKactor, eventdetailjsonbappended only
    tenancy
    company_id leads every key. Row-level security scopes each request.
    growth
    Partition expenses and violations by month. Old months move to cheap storage.
    money
    bigint cents. Foreign amounts convert at the settlement rate, once.
    backfillssql
    CREATE TABLE backfills (
      id         bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
      company_id bigint NOT NULL,
      rule_id    text   NOT NULL,
      version    int    NOT NULL,
      chunks     int    NOT NULL,
      done       int    NOT NULL DEFAULT 0,
      state      text   NOT NULL DEFAULT 'running' CHECK (state IN ('running', 'done')),
      CHECK (done <= chunks)1
    );
    
    -- A chunk's row commits with its violations, so a chunk
    -- runs once even if its job runs twice.
    CREATE TABLE backfill_chunks (
      backfill_id bigint NOT NULL REFERENCES backfills,
      low         bigint NOT NULL,
      scanned     int    NOT NULL,
      broken      int    NOT NULL,
      PRIMARY KEY (backfill_id, low)2
    );
    1. 1Progress can never pass the plan.
    2. 2The chunk row commits with its work, so a chunk runs once.
    rules and violationssql
    -- A version never changes. An edit inserts the next one.
    CREATE TABLE rules (
      company_id     bigint      NOT NULL,
      rule_id        text        NOT NULL,
      version        int         NOT NULL,
      name           text        NOT NULL,
      scope          text        NOT NULL CHECK (scope IN ('expense', 'trip')),
      action         text        NOT NULL CHECK (action IN ('block', 'flag')),
      inline_ok      boolean     NOT NULL3,
      body           jsonb       NOT NULL2,
      effective_from date        NOT NULL,
      created_by     text        NOT NULL,
      created_at     timestamptz NOT NULL DEFAULT now(),
      PRIMARY KEY (company_id, rule_id, version)1
    );
    
    CREATE TABLE active_rules (
      company_id bigint NOT NULL,
      rule_id    text   NOT NULL,
      version    int    NOT NULL,
      PRIMARY KEY (company_id, rule_id),
      FOREIGN KEY (company_id, rule_id, version) REFERENCES rules
    );
    
    CREATE TABLE audit_log (
      id         bigint      GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
      company_id bigint      NOT NULL,
      at         timestamptz NOT NULL DEFAULT now(),
      actor      text        NOT NULL,
      event      text        NOT NULL,
      detail     jsonb       NOT NULL
    );
    
    -- One row per rule version per expense or trip. facts keeps
    -- what the rule read, so the explanation survives later edits.
    CREATE TABLE violations (
      company_id    bigint      NOT NULL,
      subject_kind  text        NOT NULL CHECK (subject_kind IN ('expense', 'trip')),
      subject_id    bigint      NOT NULL,
      rule_id       text        NOT NULL,
      version       int         NOT NULL,
      action        text        NOT NULL,
      failures      jsonb       NOT NULL,
      facts         jsonb       NOT NULL4,
      source        text        NOT NULL CHECK (source IN ('live', 'backfill')),
      open          boolean     NOT NULL DEFAULT true,
      superseded_by int,
      decided_at    timestamptz NOT NULL DEFAULT now(),
      PRIMARY KEY (company_id, subject_kind, subject_id, rule_id, version)5,
      FOREIGN KEY (company_id, rule_id, version) REFERENCES rules
    );
    CREATE INDEX violations_open ON violations (company_id, rule_id) WHERE open6;
    1. 1A change inserts a row. Nothing updates a version.
    2. 2The trees, as stored. The service parses and checks them before insert.
    3. 3Derived at save time: every field in the rule is known at the swipe.
    4. 4The values the rule read. The explanation does not depend on later edits.
    5. 5One row per version per subject, so a retry inserts nothing.
    6. 6A partial index: the review queue reads only open violations.

    Rule versions never change. A violation names a version and stores the facts it read, so an old decision stays explainable.

    F

    The architecture

    click a step; its path lights up
    Card networkauthorizationFinance adminrule editorSettlement feedexpenses, editsDecision servicerule index in memoryPolicy servicerules, reportsEvaluatorevery rule, trip statePostgresrules, expenses, violationsBackfill workersN, resumableRead replicareports

    Step 1: Publish a rule

    • Parse the JSON tree and refuse a bad rule.
    • Insert the next version, move the active pointer, and write an audit row.
    • Decision servers load the new snapshot.

    If it fails

    A rule fails validation: nothing is stored, and the caller gets 422 with the reason.

    The card path reads memory and writes nothing. The settlement path writes everything in one transaction. Backfills run beside both, on their own workers.

    G

    Capabilities used

    what each tool gives you
    toolcapabilitywhat it gives this designalso used for
    PostgresjsonbStores trees and facts as written, with no column per field.Settings, event payloads
    PostgresComposite primary keysOne rule version per number; one violation per version and subject.Idempotent writes
    PostgresINSERT ... ON CONFLICTA retried event or chunk writes nothing new.T9
    PostgresFOR UPDATE SKIP LOCKEDWorkers share the chunks of a backfill.B6
    PostgresTransactionsAn expense and its violations commit together; so does a chunk.Every multi-row change
    PostgresPartial indexes, partitionsFast review queue; old months move away.D2
    PostgresRow-level securityOne company never reads another's rules or expenses.O6
    ServiceCompiled rule snapshot per companyA decision reads memory only, with no database call.Feature flags, routing tables
    ServiceGuard derivationThe index comes from the tree. Nobody tags a rule by hand.Query planners, search percolation
    ServiceState keyed by tripOne running total per trip, safe under repeats.B7

    Postgres gives me versioned JSON, unique keys for idempotency, and SKIP LOCKED for the backfill. The service keeps a compiled rule index in memory.

    H

    Deep dive: the rule model

    a tree of predicates, stored as JSON
    rule meals-receipt · version 3 · flagapplies whencategory = meals✓ heldmust holdOR✕ falseamount ≤ 7500receipt = truepath 0: got 9200path 1: got falseAn OR is false only if every child is false, so the explanation names both.
    rule modelstatuswhy
    Rules in codeNot approvedEach change is a deploy, and companies cannot edit them.
    A SQL WHERE clause per ruleNot approvedInjection risk, and a false WHERE explains nothing.
    A free text expression languagePower usersNeeds a parser and limits; the builder must render it back.
    JSON tree of typed predicatesApprovedChecked at save time, easy to version, and each node can explain itself.
    A forward-chaining rule networkRules that feed rulesBuilt for rules that fire other rules. This prompt has none.
    evaluate and explainpseudo code
    eval(node, facts):
      and:  every child is true
      or:   some child is true
      not:  the child is false
      pred: compare facts[field] with value1
    
    rule is broken WHEN eval(when) AND NOT eval(require)2
    
    blame(node, want):                  // node is not want
      pred: report it
      not:  blame(child, NOT want)3
      and, want true:  blame each false child4
      or,  want true:  blame every child5
      and, want false: blame every child
      or,  want false: blame each true child
    1. 1Fields and operators are a closed list, each with a type. An unknown field fails at save time.
    2. 2The two trees let the builder ask two plain questions: does this apply, and what must hold.
    3. 3Each NOT flips what the walk wants, so a nested NOT needs no special case.
    4. 4An AND fails on its false children; the true ones did no harm.
    5. 5An OR that should be true failed on every child, so all of them count.
    Tested source Go: fields · Go: evaluate · Go: explain
    Go: fieldsgo
    var fields = []fieldDef{
      {name: "amount", kind: Num, auth: true},
      {name: "category", kind: Str, auth: true},
      {name: "merchant", kind: Str, auth: true},
      {name: "country", kind: Str, auth: true},
      {name: "weekend", kind: Flag, auth: true},
      {name: "receipt", kind: Flag},  // arrives after the swipe
      {name: "attendees", kind: Num}, // arrives after the swipe
      {name: "trip_total", kind: Num, trip: true, auth: true},
      {name: "trip_days", kind: Num, trip: true, auth: true},
      {name: "trip_count", kind: Num, trip: true, auth: true},
      {name: "trip_meals", kind: Num, trip: true, auth: true},
      {name: "trip_lodging", kind: Num, trip: true, auth: true},
      {name: "trip_meals_per_day", kind: Num, trip: true, auth: true},
    }
    
    Go: evaluatego
    
    // Eval returns the node's truth value on the facts.
    func (n *Node) Eval(f *Facts) bool {
      switch n.form {
      case formAnd:
        for _, k := range n.And {
          if !k.Eval(f) {
            return false
          }
        }
        return true
      case formOr:
        for _, k := range n.Or {
          if k.Eval(f) {
            return true
          }
        }
        return false
      case formNot:
        return !n.Not.Eval(f)
      }
      return n.test(f)
    }
    
    func (n *Node) test(f *Facts) bool {
      switch n.cmp {
      case "lt":
        return f.num[n.id] < n.n
      case "le":
        return f.num[n.id] <= n.n
      case "gt":
        return f.num[n.id] > n.n
      case "ge":
        return f.num[n.id] >= n.n
      case "in":
        for _, v := range n.set {
          if f.str[n.id] == v {
            return true
          }
        }
        return false
      }
      var same bool
      if fields[n.id].kind == Str {
        same = f.str[n.id] == n.s
      } else {
        same = f.num[n.id] == n.n
      }
      return same == (n.cmp == "eq")
    }
    
    Go: explaingo
    
    // Failures explains why n is false: the predicates that, together, forced that result.
    func (n *Node) Failures(f *Facts) []Failure {
      if n.Eval(f) {
        return nil
      }
      return n.blame(f, "", true, nil)
    }
    
    // blame walks the tree. want is the value the parent needed from n, and n has the opposite value.
    // An AND that should be true blames its false children; an OR that should be true blames them all.
    // A NOT flips want, so an AND under a NOT blames all its children, and an OR blames its true ones.
    func (n *Node) blame(f *Facts, path string, want bool, out []Failure) []Failure {
      child := func(i int) string {
        if path == "" {
          return strconv.Itoa(i)
        }
        return path + "." + strconv.Itoa(i)
      }
      switch n.form {
      case formPred:
        return append(out, Failure{path, n.text(), f.Value(n.id), !want})
      case formNot:
        return n.Not.blame(f, child(0), !want, out)
      }
      kids := n.And
      all := !want // an AND that should be false, so every child was true
      if n.form == formOr {
        kids = n.Or
        all = want // an OR that should be true, so every child was false
      }
      for i, k := range kids {
        if all || k.Eval(f) != want {
          out = k.blame(f, child(i), want, out)
        }
      }
      return out
    }
    

    Tested on 20,000 random trees: flip exactly the reported predicates and the rule passes, so the explanation is sufficient. A saved rule has at most 8 levels and 64 nodes. One explanation took 1,205 ns.

    A rule is two trees: when it applies, and what must hold. It is broken when the first is true and the second is false.

    I

    Deep dive: in-line and async

    one evaluator, two paths
    in-linereporting
    WhenThe card waitsAfter settlement, and on each edit
    DeadlineUnder 2 s, end to endSeconds to minutes
    FieldsAmount, merchant, category, countryThose, plus receipt and attendees
    RulesBlock rules that can run in-lineEvery rule
    ReadsMemoryMemory, then one transaction
    ResultApprove or declineA violation with its explanation
    methodstatuswhy
    Load rules from the database per swipeNot approvedThe card path then depends on the database.
    Snapshot in memory, refreshed on publishApprovedA decision reads one version of the rule set, throughout.
    Two rule engines, one per pathNot approvedThe paths drift, and a swipe and its report disagree.
    One evaluator; each field says when it is knownApprovedInline eligibility is derived from the tree.
    authorize and recordpseudo code
    authorize(expense):                  // the card waits
      snapshot = this company's compiled rules, in memory1
      rules = index.candidates(expense)
      decline IF a block rule that can run in-line2 is broken
      IF the expense has a trip:
        facts = trip aggregate with this expense added3
        decline IF a block trip rule is broken
      RETURN approved
    
    record(expense):                     // after settlement, and on each edit
      BEGIN
        upsert the expense, a newer revision only4
        run every candidate rule, with every field
        add violations; close the ones an edit cured5
        update the trip; run its rules
      COMMIT
    1. 1One snapshot per decision. A publish swaps in a new one, and the old one finishes its work.
    2. 2A rule that reads a receipt can never block: the field does not exist yet.
    3. 3A preview, kept nowhere. If the swipe is declined, the trip never saw it.
    4. 4A repeat or a stale event does nothing.
    5. 5Adding a receipt fixes the violation, and the row stays as history.
    Tested source Go: authorize and record
    Go: authorize and recordgo
    
    // Authorize is the in-line path: it runs while the card waits. It reads memory only, runs block
    // rules whose fields are known at the swipe, and previews the trip with this expense in it.
    func (d *Decider) Authorize(e Expense) (approved bool, why []Verdict) {
      f := e.Facts()
      for _, r := range d.ix.Candidates(&f, nil) {
        if v, broken := r.Check(&f); broken && r.Inline() && r.Action == "block" {
          why = append(why, v)
        }
      }
      if e.Trip != 0 {
        tf := d.Trips.Preview(e)
        for _, r := range d.ix.TripCandidates(e.Category) {
          if v, broken := r.Check(&tf); broken && r.Inline() && r.Action == "block" {
            why = append(why, v)
          }
        }
      }
      return len(why) == 0, why
    }
    
    // Record is the reporting path: it runs after settlement with every field, and it runs again on
    // each edit. The expense, its violations and any cures commit in one transaction.
    func (d *Decider) Record(ctx context.Context, e Expense) ([]Verdict, error) {
      f := e.Facts()
      found := Evaluate(d.ix.Candidates(&f, nil), &f)
      var tf Facts
      var tripRules []*Rule
      var tripFound []Verdict
      if e.Trip != 0 {
        tf = d.Trips.Add(e).Facts()
        tripRules = d.ix.TripCandidates(e.Category)
        tripFound = Evaluate(tripRules, &tf)
      }
      err := pgx.BeginFunc(ctx, d.store.DB, func(tx pgx.Tx) error {
        tag, err := tx.Exec(ctx, q["upsert_expense"], e.ID, e.Company, e.Employee, e.Trip, e.Amount, e.Category, e.Merchant, e.Country,
          e.Day, e.Weekend, e.Receipt, e.Attendees, e.Revision)
        if err != nil {
          return fmt.Errorf("upsert expense %d: %w", e.ID, err)
        }
        if tag.RowsAffected() == 0 {
          return nil // a repeat or a stale revision
        }
        sub := Subject{"expense", e.ID}
        broken, err := settle(ctx, tx, d.company, sub, found, &f)
        if err != nil {
          return err
        }
        if _, err := tx.Exec(ctx, q["close_cured"], d.company, sub.Kind, sub.ID, broken); err != nil {
          return fmt.Errorf("close cured on expense %d: %w", e.ID, err)
        }
        if e.Trip == 0 {
          return nil
        }
        trip := Subject{"trip", e.Trip}
        stillBroken, err := settle(ctx, tx, d.company, trip, tripFound, &tf)
        if err != nil {
          return err
        }
        var cured []string
        for _, r := range tripRules {
          if !slices.Contains(stillBroken, r.ID) {
            cured = append(cured, r.ID)
          }
        }
        if _, err := tx.Exec(ctx, q["close_rules"], d.company, trip.Kind, trip.ID, cured); err != nil {
          return fmt.Errorf("close cured on trip %d: %w", e.Trip, err)
        }
        return nil
      })
      return append(found, tripFound...), err
    }
    
    // settle writes the verdicts and reopens any that an earlier edit had closed. It returns the names
    // of the broken rules.
    func settle(ctx context.Context, tx pgx.Tx, company int64, sub Subject, found []Verdict, f *Facts) ([]string, error) {
      broken := make([]string, 0, len(found))
      for _, v := range found {
        broken = append(broken, v.Rule)
        if err := insertViolation(ctx, tx, company, sub, v, f, "live"); err != nil {
          return nil, err
        }
        if _, err := tx.Exec(ctx, q["reopen"], company, sub.Kind, sub.ID, v.Rule, v.Version); err != nil {
          return nil, fmt.Errorf("reopen %s on %s %d: %w", v.Rule, sub.Kind, sub.ID, err)
        }
      }
      return broken, nil
    }
    

    The card path runs block rules on swipe fields, from memory. Everything else waits for settlement, when the receipt and the attendees exist.

    J

    Deep dive: indexing the rules

    one expense need not read them all
    expense: meals, US, bistro, 92.00category = mealsmin 30.00min 60.00min 90.00min 120.00min 150.00country = USmin 30.00min 60.00min 90.00min 120.00min 150.00merchant = bistromin 30.00min 60.00min 90.00min 120.00min 150.00no guardmin 30.00min 60.00min 90.00min 120.00min 150.00Mean rules read per expense: 35 of 10,000Solid rows can fire at 92.00, so they run. Dashed rows need more. A rule sits in one field, so none runs twice.
    rulesscan/sindex/srules readp99
    1,00046,9765,008,7693.81.0 µs
    10,0004,410582,81135.112 µs
    50,00037975,240173.2105 µs
    narrowing methodstatuswhy
    Scan every ruleUnder 100 rulesSimple, and linear in rules.
    A category column that an admin setsNot approvedA wrong tag silently skips a rule.
    Guards derived from the treeApprovedSound by construction, and proved against a scan.
    Trip rules by the category they readApprovedA taxi cannot change a meal cap, so that rule does not run.
    guards and bucketspseudo code
    guard(tree):                         // needed for the rule to fire1
      category = x        -> category in {x}
      amount > n          -> amount >= n + 1
      a AND b             -> both guards hold
      a OR b              -> only what holds on both sides2
      NOT x               -> push NOT down with De Morgan3
    
    build:
      FOR EACH rule:
        g = guard(when) AND guard(NOT require)
        put it in one bucket, per value of its best field4
        sort each bucket by smallest firing amount
    
    candidates(expense):
      FOR EACH guard field, and the bucket with no guard:
        read while bucket.min <= expense.amount5
    1. 1A guard is necessary, not sufficient. The index may return a rule that passes, never miss one that fires.
    2. 2An OR with an unguarded branch gives no guard, so that rule goes to the open bucket.
    3. 3The rule fires when require is false, so its guard comes from the negated tree: amount <= 75 gives amount >= 76.
    4. 4A rule sits under one field only: merchant, then country, then category. No expense reaches it twice.
    5. 5A sorted bucket stops at the first rule this amount cannot fire.
    Tested source Go: guards · Go: index
    Go: guardsgo
    
    // guardOf derives the guard of a tree, or of its negation when neg is set. Negation moves down
    // the tree by De Morgan's laws: NOT (a AND b) is (NOT a) OR (NOT b).
    func guardOf(n *Node, neg bool) guard {
      switch n.form {
      case formNot:
        return guardOf(n.Not, !neg)
      case formAnd, formOr:
        kids, combine := n.And, both
        if n.form == formOr {
          kids = n.Or
        }
        if (n.form == formOr) != neg {
          combine = either
        }
        g := guardOf(kids[0], neg)
        for _, k := range kids[1:] {
          g = combine(g, guardOf(k, neg))
        }
        return g
      }
      g := anyGuard()
      if fields[n.id].kind == Str {
        switch {
        case n.cmp == "eq" && !neg, n.cmp == "ne" && neg:
          g.eq = map[fieldID][]string{n.id: {n.s}}
        case n.cmp == "in" && !neg:
          g.eq = map[fieldID][]string{n.id: n.set}
        }
        return g
      }
      if n.id != fAmount {
        return g
      }
      switch {
      case n.cmp == "gt" && !neg, n.cmp == "le" && neg:
        g.minAmount = n.n + 1
      case n.cmp == "ge" && !neg, n.cmp == "lt" && neg, n.cmp == "eq" && !neg:
        g.minAmount = n.n
      }
      return g
    }
    
    // ruleGuard is the guard of "When holds and Require does not".
    func ruleGuard(r *Rule) guard {
      g := guardOf(r.Require, true)
      if r.When != nil {
        g = both(guardOf(r.When, false), g)
      }
      return g
    }
    
    Go: indexgo
    
    // NewIndex builds an index over the rules.
    func NewIndex(rules []*Rule) *Index {
      ix := &Index{tripBy: map[string][]*Rule{}, total: len(rules)}
      for _, r := range rules {
        if r.Scope == "trip" {
          ix.addTrip(r)
          continue
        }
        e := guarded{r.guard.minAmount, r}
        placed := false
        for _, f := range indexOrder {
          values, ok := r.guard.eq[f]
          if !ok {
            continue
          }
          if ix.buckets[f] == nil {
            ix.buckets[f] = map[string][]guarded{}
          }
          for _, v := range slices.Compact(slices.Sorted(slices.Values(values))) {
            ix.buckets[f][v] = append(ix.buckets[f][v], e)
          }
          placed = true
          break
        }
        if !placed {
          ix.open = append(ix.open, e)
        }
      }
      byMin := func(a, b guarded) int { return cmp.Compare(a.min, b.min) }
      for _, f := range indexOrder {
        for _, b := range ix.buckets[f] {
          slices.SortStableFunc(b, byMin)
        }
      }
      slices.SortStableFunc(ix.open, byMin)
      return ix
    }
    
    // Candidates appends the rules this expense could break: one bucket per guard field, and in each
    // bucket only the prefix whose smallest firing amount the expense reaches.
    func (ix *Index) Candidates(f *Facts, out []*Rule) []*Rule {
      take := func(b []guarded) {
        for _, e := range b {
          if e.min > f.num[fAmount] {
            return
          }
          out = append(out, e.rule)
        }
      }
      for _, id := range indexOrder {
        if ix.buckets[id] != nil {
          take(ix.buckets[id][f.str[id]])
        }
      }
      take(ix.open)
      return out
    }
    

    One tenant with all the rules, the worst case; 200,000 expenses, median of 3 runs, one thread. Generated rules: 90% name a category, country or merchant, and 10% name nothing the index can use. A policy book with more open rules gains less. Building the index for 10,000 rules took 3.3 ms.

    At 10,000 rules the index read about 35 per expense and ran 132 times faster than a full scan, with the same verdicts.

    K

    Deep dive: per-trip rules

    window state keyed by trip
    trip aggregatepseudo code
    add(expense):
      state = trips[company, trip]1
      old = state.expenses[expense.id]
      IF old exists AND old.revision >= expense.revision:
        RETURN state                      // a repeat changes nothing2
      subtract old from the totals3
      add the expense to the totals
      remember (id, revision, amount, category, day)
    
    facts(state):
      trip_total, trip_meals, trip_lodging
      trip_days = last day - first day + 14
      trip_meals_per_day = trip_meals ÷ trip_days
    1. 1The key is the trip, not a calendar window. A trip has no fixed length.
    2. 2The aggregate keeps a row per expense, so idempotence costs one lookup.
    3. 3An edit is a subtraction and an addition, so totals never drift.
    4. 4Days between expenses count. A day with no spend is still a day away.
    Tested source Go: trip aggregate
    Go: trip aggregatego
    
    // TripState is the running aggregate of one trip. The expenses map makes an update idempotent: a
    // repeat changes nothing, and a new revision replaces the old values.
    type TripState struct {
      Total    int64
      Meals    int64
      Lodging  int64
      days     map[int]int
      expenses map[int64]counted
    }
    
    // Windows holds one aggregate per trip.
    type Windows struct {
      trips map[tripKey]*TripState
    }
    
    // NewWindows returns an empty set of trips.
    func NewWindows() *Windows { return &Windows{trips: map[tripKey]*TripState{}} }
    
    // Add folds an expense into its trip and returns the aggregate. Arrival order does not matter.
    func (w *Windows) Add(e Expense) *TripState {
      k := tripKey{e.Company, e.Trip}
      s, ok := w.trips[k]
      if !ok {
        s = &TripState{days: map[int]int{}, expenses: map[int64]counted{}}
        w.trips[k] = s
      }
      old, seen := s.expenses[e.ID]
      if seen && old.revision >= e.Revision {
        return s
      }
      if seen {
        s.apply(old, -1)
      }
      c := counted{e.Amount, e.Category, e.Day, e.Revision}
      s.expenses[e.ID] = c
      s.apply(c, 1)
      return s
    }
    
    func (s *TripState) apply(c counted, sign int64) {
      s.Total += sign * c.amount
      switch c.category {
      case "meals":
        s.Meals += sign * c.amount
      case "lodging":
        s.Lodging += sign * c.amount
      }
      if s.days[c.day] += int(sign); s.days[c.day] == 0 {
        delete(s.days, c.day)
      }
    }
    
    // Facts returns the trip fields a trip rule reads.
    func (s *TripState) Facts() Facts {
      var f Facts
      f.num[fTripTotal] = s.Total
      f.num[fTripCount] = int64(len(s.expenses))
      f.num[fTripMeals] = s.Meals
      f.num[fTripLodging] = s.Lodging
      if len(s.days) > 0 {
        lo, hi := minMax(s.days)
        days := int64(hi - lo + 1)
        f.num[fTripDays] = days
        f.num[fTripMealsPerDay] = s.Meals / days
      }
      return f
    }
    
    methodstatuswhy
    Sum the rows on every expenseReporting onlyCorrect, and too slow for the card path.
    Calendar windows, by week or monthNot approvedA trip crosses windows, so the sum is wrong.
    A counter with no expense idsNot approvedA repeat counts twice, and an edit cannot subtract.
    State keyed by trip, with ids and revisionsApprovedOrder does not matter, and a repeat changes nothing.
    casebehaviour
    Each expense passes, the trip failsA trip violation appears on the expense that crosses the cap.
    A swipe would cross a block capThe preview declines it before the trip changes.
    An expense arrives weeks lateThe trip reopens and its rules run again.
    An edit lowers the totalThe trip violation closes.
    No booking names the tripA session window groups the expenses: a gap of N days ends it.

    Tested with repeats and stale revisions in random order, 500 times: the same totals each time. Session windows reuse the window code from B7.

    A trip rule reads an aggregate keyed by trip. It adds each expense once by id and revision, so repeats and late arrivals give the same totals.

    L

    Deep dive: changing a rule

    a backfill, and the audit trail
    publish and workpseudo code
    publish(rule):
      BEGIN
        insert the next version; move the active pointer
        write an audit row
        enqueue one job per chunk of ids1
      COMMIT
    
    work(chunk):
      claim a job; it hides from others for a lease2
      BEGIN
        IF the chunk row exists: skip3     // it ran already
        insert the chunk row
        read the subjects in the chunk
        close older versions for those subjects4
        insert a violation for each broken subject
        count the chunk on the backfill5
      COMMIT
      acknowledge the job
    1. 1In the same transaction, so a new version never lacks its backfill.
    2. 2A dead worker's chunk reappears when the lease ends.
    3. 3A crash between the commit and the acknowledgement runs the job again, and this line stops it.
    4. 4Only the subjects this chunk read. Expenses before the effective date keep their old result.
    5. 5In the chunk's transaction, so progress is never ahead of the data.
    Tested source Go: publish · Go: backfill · Go: replay a decision · SQL: claim, supersede
    Go: publishgo
    
    // Publish stores a new version and moves the active pointer in one transaction. If a backfill is
    // wanted, its chunks enter the work queue in that same transaction.
    func (s *Store) Publish(ctx context.Context, now time.Time, r *Rule, actor string, effectiveDay int, chunkSize int64) (backfill int64, err error) {
      body, err := toJSON(map[string]any{"when": r.When, "require": r.Require, "scope": r.Scope, "action": r.Action})
      if err != nil {
        return 0, err
      }
      err = pgx.BeginFunc(ctx, s.DB, func(tx pgx.Tx) error {
        if err := tx.QueryRow(ctx, q["next_version"], r.Company, r.ID).Scan(&r.Version); err != nil {
          return fmt.Errorf("next version of %s: %w", r.ID, err)
        }
        if _, err := tx.Exec(ctx, q["insert_rule"], r.Company, r.ID, r.Version, r.Name, r.Scope, r.Action, r.auth, body, effectiveDay, actor); err != nil {
          return fmt.Errorf("insert %s v%d: %w", r.ID, r.Version, err)
        }
        if _, err := tx.Exec(ctx, q["activate"], r.Company, r.ID, r.Version); err != nil {
          return fmt.Errorf("activate %s: %w", r.ID, err)
        }
        detail, err := toJSON(map[string]any{"rule": r.ID, "version": r.Version, "effective_from": effectiveDay})
        if err != nil {
          return err
        }
        if _, err := tx.Exec(ctx, q["audit"], r.Company, actor, "rule_published", detail); err != nil {
          return fmt.Errorf("audit %s: %w", r.ID, err)
        }
        if chunkSize <= 0 {
          return nil
        }
        backfill, err = plan(ctx, tx, now, r, effectiveDay, chunkSize)
        return err
      })
      return backfill, err
    }
    
    type chunk struct {
      Backfill  int64  `json:"backfill"`
      Rule      string `json:"rule"`
      Version   int    `json:"version"`
      Company   int64  `json:"company"`
      Low       int64  `json:"low"`
      High      int64  `json:"high"`
      Effective int    `json:"effective"`
    }
    
    func plan(ctx context.Context, tx pgx.Tx, now time.Time, r *Rule, effectiveDay int, size int64) (int64, error) {
      var lo, hi int64
      key := "expense_range"
      if r.Scope == "trip" {
        key = "trip_range"
      }
      if err := tx.QueryRow(ctx, q[key], r.Company).Scan(&lo, &hi); err != nil {
        return 0, fmt.Errorf("range of %s: %w", r.ID, err)
      }
      var chunks []chunk
      for low := lo; low <= hi; low += size {
        chunks = append(chunks, chunk{Rule: r.ID, Version: r.Version, Company: r.Company, Low: low, High: low + size, Effective: effectiveDay})
      }
      var id int64
      if err := tx.QueryRow(ctx, q["plan_backfill"], r.Company, r.ID, r.Version, len(chunks)).Scan(&id); err != nil {
        return 0, fmt.Errorf("plan backfill of %s: %w", r.ID, err)
      }
      payloads := make([]string, len(chunks))
      for i := range chunks {
        chunks[i].Backfill = id
        p, err := toJSON(chunks[i])
        if err != nil {
          return 0, err
        }
        payloads[i] = p
      }
      if _, err := tx.Exec(ctx, q["plan_jobs"], payloads, now); err != nil {
        return 0, fmt.Errorf("enqueue chunks of %s: %w", r.ID, err)
      }
      return id, nil
    }
    
    Go: backfillgo
    
    // Work claims one chunk and re-evaluates it. The chunk's row, its violations and the older
    // versions it supersedes commit together, so a crash leaves all of it or none of it. It reports
    // false when no chunk is visible.
    func (s *Store) Work(ctx context.Context, now time.Time, worker string, fault Fault) (bool, error) {
      jobs, _, err := s.Queue.Claim(ctx, now, worker, 1)
      if err != nil || len(jobs) == 0 {
        return false, err
      }
      job := jobs[0]
      var c chunk
      if err := json.Unmarshal([]byte(job.Payload), &c); err != nil {
        return false, fmt.Errorf("decode chunk %d: %w", job.ID, err)
      }
      err = pgx.BeginFunc(ctx, s.DB, func(tx pgx.Tx) error {
        tag, err := tx.Exec(ctx, q["claim_chunk"], c.Backfill, c.Low)
        if err != nil {
          return fmt.Errorf("claim chunk %d: %w", c.Low, err)
        }
        if tag.RowsAffected() == 0 {
          return nil // committed before; this job ran again after a crash
        }
        if err := s.runChunk(ctx, tx, c); err != nil {
          return err
        }
        if fault.BeforeCommit {
          return ErrCrash
        }
        return nil
      })
      if err != nil {
        return true, err
      }
      if fault.BeforeAck {
        return true, ErrCrash
      }
      _, err = s.Queue.Ack(ctx, worker, job.ID)
      return true, err
    }
    
    func (s *Store) runChunk(ctx context.Context, tx pgx.Tx, c chunk) error {
      r, err := s.ruleVersion(ctx, tx, c.Company, c.Rule, c.Version)
      if err != nil {
        return err
      }
      type evaluated struct {
        sub   Subject
        facts Facts
      }
      var subjects []evaluated
      if r.Scope == "expense" {
        es, err := loadExpenses(ctx, tx, q["chunk_expenses"], c.Company, c.Low, c.High, c.Effective)
        if err != nil {
          return err
        }
        for _, e := range es {
          subjects = append(subjects, evaluated{Subject{"expense", e.ID}, e.Facts()})
        }
      } else {
        es, err := loadExpenses(ctx, tx, q["chunk_trips"], c.Company, c.Low, c.High)
        if err != nil {
          return err
        }
        w := NewWindows()
        for _, e := range es {
          w.Add(e)
        }
        for k, st := range w.trips {
          subjects = append(subjects, evaluated{Subject{"trip", k.trip}, st.Facts()})
        }
      }
      ids := make([]int64, len(subjects))
      for i := range subjects {
        ids[i] = subjects[i].sub.ID
      }
      if _, err := tx.Exec(ctx, q["supersede"], c.Company, r.Scope, ids, c.Rule, c.Version); err != nil {
        return fmt.Errorf("supersede %s: %w", c.Rule, err)
      }
      broken := 0
      for i := range subjects {
        v, bad := r.Check(&subjects[i].facts)
        if !bad {
          continue
        }
        broken++
        if err := insertViolation(ctx, tx, c.Company, subjects[i].sub, v, &subjects[i].facts, "backfill"); err != nil {
          return err
        }
      }
      if _, err := tx.Exec(ctx, q["finish_chunk"], c.Backfill, c.Low, len(subjects), broken); err != nil {
        return fmt.Errorf("finish chunk %d: %w", c.Low, err)
      }
      if _, err := tx.Exec(ctx, q["count_chunk"], c.Backfill); err != nil {
        return fmt.Errorf("count chunk %d: %w", c.Low, err)
      }
      return nil
    }
    
    Go: replay a decisiongo
    
    // Replay re-runs a stored violation: the rule version it used, on the facts it stored. The result
    // does not depend on today's expense or today's rule.
    func (s *Store) Replay(ctx context.Context, company int64, sub Subject, rule string, version int) (stored, again []Failure, err error) {
      err = pgx.BeginFunc(ctx, s.DB, func(tx pgx.Tx) error {
        var fails, facts []byte
        if err := tx.QueryRow(ctx, q["violation"], company, sub.Kind, sub.ID, rule, version).Scan(&fails, &facts); err != nil {
          return fmt.Errorf("load violation: %w", err)
        }
        if err := json.Unmarshal(fails, &stored); err != nil {
          return fmt.Errorf("decode failures: %w", err)
        }
        var m map[string]any
        if err := json.Unmarshal(facts, &m); err != nil {
          return fmt.Errorf("decode facts: %w", err)
        }
        f, err := factsFromMap(m)
        if err != nil {
          return err
        }
        r, err := s.ruleVersion(ctx, tx, company, rule, version)
        if err != nil {
          return err
        }
        again = r.Require.Failures(&f)
        return nil
      })
      return stored, again, err
    }
    
    SQL: claim, supersedesql
    -- 0 rows: this chunk already committed, and its job ran a second time.
    INSERT INTO backfill_chunks (backfill_id, low, scanned, broken) VALUES ($1, $2, 0, 0)
    ON CONFLICT DO NOTHING;
    
    -- Older versions of this rule, for the subjects this chunk read, stop being open.
    UPDATE violations SET open = false, superseded_by = $5
    WHERE company_id = $1 AND subject_kind = $2 AND subject_id = ANY($3)
      AND rule_id = $4 AND version < $5 AND open;
    methodstatuswhy
    One transaction over all historyNot approvedLong locks; one bad row rolls back everything.
    A script with an offset in memoryNot approvedA crash restarts from 0, or skips rows.
    Evaluate lazily when a report readsSmall tenantsNo backfill cost, and slow reports.
    Chunks on a queue, one transaction eachApprovedResumable and safe to run in parallel.
    backfill of 100,000 expensesexpenses/s
    1 worker, chunks of 1,000119,048
    4 workers, chunks of 1,000347,766
    audit questionanswer comes from
    Who changed this rule, and when?The audit log and the rule version row.
    What did the rule say then?The version's stored tree.
    Why was this expense flagged?The violation's failures and facts.
    Is that explanation still true?Replay: the old version on the stored facts.

    The rule read every expense and flagged 4.8% of them; the table fit in memory. Tested: a crash on each of 10 chunks, before the commit and again between the commit and the acknowledgement. Each run ended equal to an in-memory evaluation. Replay gave the same predicates after the rule and the expense both changed.

    A rule change enqueues chunks in the transaction that publishes it. Four workers re-evaluated about 350,000 expenses a second, and a crash on any chunk gave the same result as a clean run.

    M

    See it: build a rule

    the lab's fields and expenses; the same evaluator

    Applies when

    Must hold

    Stored as JSON
    {
     "when": {
      "field": "category",
      "op": "eq",
      "value": "meals"
     },
     "require": {
      "or": [
       {
        "field": "amount",
        "op": "le",
        "value": 7500
       },
       {
        "field": "receipt",
        "op": "eq",
        "value": true
       }
      ]
     }
    }

    Expense

    amount
    9200
    attendees
    1
    category
    meals
    country
    US
    merchant
    noodle bar
    receipt
    false
    weekend
    false

    ✕ Violation

    1. 0 failed: amount le 7500; the expense has 9200
    2. 1 failed: receipt eq true; the expense has false

    This rule reads a field that arrives after the swipe, so it runs on the reporting path.

    Amounts are in cents. This evaluator runs in your browser. The page checks it against 180 results from the lab engine when it is built, and any disagreement stops the build.

    I read the failing path off the tree. An AND names its false children, an OR names them all, and a NOT names what held.

    N

    Failure cases

    what breaks, and what stays correct
    eventresultwhy it is safesaved by
    The decision service misses the deadlineThe processor applies its default.Reporting still runs every rule, so a wrong approval becomes a flag.Two paths
    Postgres is down during a swipeDecisions continue from memory.The card path reads no database. Settlement events wait in the feed.Snapshot
    A settlement event arrives twiceThe second changes nothing.The revision check, then the unique violation key.Unique key
    Two edits arrive out of orderThe older one is ignored.Only a newer revision updates the row.Revision
    A backfill worker dies mid-chunkThe chunk rolls back.The lease ends and another worker takes it.Transaction, lease
    A worker dies after the commitThe job runs again.The chunk row exists, so the job only acknowledges.Chunk row
    A chunk keeps failingIt moves to the dead jobs.The backfill stays running, and a person sees why.Dead jobs
    An admin saves a broken rule422 with the reason.Types, depth and size are checked before insert.Validation
    A new rule flags far too muchPublish version 3, the old tree.The backfill clears the wrong flags, and history keeps them.Versions
    A server holds an old snapshotIt decides on the last version for a moment.Each decision records its version, and reporting uses the new one.Version in row
    O

    Scale ladder

    start simple; climb only on a signal
    Each step adds one component1One Postgres2+ rule snapshots3+ rule index4+ workers5+ read replica6+ company shardsmore load →
    Expenses per second against this prompt's demand101001k10k100k1M10MDemand: peak: 76 expenses per secondDemand: peak76Record, 1 connection: 2,544 expenses per secondRecord, 1 connection2,544Backfill, 4 workers: 347,766 expenses per secondBackfill, 4 workers347,766Scan, 10,000 rules: 4,410 expenses per secondScan, 10,000 rules4,410Index, 10,000 rules: 582,811 expenses per secondIndex, 10,000 rules582,811Index, 50,000 rules: 75,240 expenses per secondIndex, 50,000 rules75,240expenses per second, log scale
    stepaddit handlesmove up when you see
    1One Postgres, a scan per expense.About 46,976 expenses a second at 1,000 rules.The card path waits on the database.
    2Rule snapshots in memory, refreshed on publish.Decisions survive a database outage.A large company's rules take most of the CPU.
    3The rule index.About 580,000 evaluations a second at 10,000 rules.A backfill slows settlement writes.
    4Backfill workers with a rate limit per company.A large company in seconds to minutes, in the background.Reports slow down the primary.
    5A read replica for reports, and monthly partitions.Long queries leave the primary.One primary nears its write limit.
    6Shards by company; a rule and its expenses never cross.Each shard adds its own rate.Top of the ladder.

    Demand from panel C. Evaluation is one thread in memory, with 90% of rules guarded. Record and backfill are the lab Postgres on a shared 8-core laptop, so read them as orders of magnitude.

    A scan is fine for most companies, which have tens of rules. I add the index for the large ones, and split the backfill from the card path before I shard.

    P

    Follow-ups

    what the interviewer asks next
    questionanswerdeeper
    How do you keep one company from seeing another's data?company_id leads every key, and row-level security scopes each request. A very large company can get its own cell.O6
    How do new rules reach every decision server?Publish writes a version, and an event tells servers to reload. A poll on the version backs that up, so a missed event only delays the change.O4
    How do you stop a backfill hurting live traffic?Limit chunks per second per company, and use a separate worker pool. Slow it when replica lag or write latency grows.O2
    How do you let a company test a rule first?Run a backfill that writes to a draft table, with no effect on live violations. Show the count before publishing.O4
    Why not a stream processor for trip totals?Volume is low enough for one table, and the totals must be read in the card path. Move to a stream job if trip logic grows.B7
    How do you keep the outbox of notifications exact?Write the event in the transaction that inserts the violation. A dispatcher sends it once per key.C7
    Does a refund affect the trip?A refund is an edit or a negative expense. The aggregate subtracts it, and a cured trip violation closes.T9
    How do you shard?By company_id, because a rule and its expenses never cross companies. A directory maps each company to a shard.X2
    Q

    Drill

    predict, then reveal

    0 of 9 known

    1. Why keep a rule as data and not as code or as a SQL string?

    2. A rule requires amount at most 75.00 or a receipt. A 92.00 lunch has no receipt. What does the explanation name, and why both?

    3. What is the failing predicate under a NOT?

    4. Why can a receipt rule never decline a card?

    5. How does the index stay correct for a rule with OR and NOT?

    6. Why did the index read about 35 rules and not 10,000?

    7. Two expenses on a trip arrive out of order, and one is sent twice. Is the trip total right?

    8. A backfill worker crashes after it commits a chunk but before it acknowledges the job. What happens?

    9. A manager asks in June why an expense was flagged in January, and the rule changed in March. What do you show?

    R

    Numbers to say

    measured, derived or cited
    demand
    About 76 expenses a second at peak; 240 million a year.
    index
    580,000 evaluations a second at 10,000 rules; 4,400 with a scan.
    rules read
    About 35 of 10,000 per expense.
    latency
    p99 12 µs per evaluation at 10,000 rules.
    explain
    1,205 ns for one failing tree.
    record
    About 2,500 expenses a second on one connection.
    backfill
    About 350,000 expenses a second with 4 workers.
    deadline
    About 2 s for one published card-issuing API.

    Go and Postgres on an 8-core laptop shared with other jobs. Rule shapes are generated, so a real policy book will differ.