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.
- 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.
- 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.
- 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.
- 4A rule change is a backfill: chunks on a work queue, each one transaction, so a crash loses nothing and repeats nothing.
"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."
| question | answer 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.
| 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-functional | target |
|---|---|
| In-line decision | p99 < 50 ms inside a 2 s deadline |
| Rules read per expense | under 1% at 10,000 rules |
| Peak rate | ≈ 76 expenses/s |
| Backfill of one large company | minutes, no effect on the card path |
| Decisions lost or doubled by a crash | 0 |
| Explanation kept | The 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.
| quantity | arithmetic | result |
|---|---|---|
| Average rate | 20 million ÷ 2,628,000 s | ≈ 7.6/s |
| Peak rate | 10 × average, in working hours | ≈ 76/s |
| Rules per company | 50,000 ÷ 10,000 | 5 on average; 10,000 at most |
| Expenses a year | 240 million × 181 B | ≈ 43 GB with indexes |
| Violations a year | 5% × 240 million × 539 B | ≈ 6 GB with indexes |
| Backfill, a large company | 1 million ÷ 350,000/s | ≈ 3 s at lab rates |
| Backfill, every expense in a year | 240 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.
| call | success | errors | retry safe? |
|---|---|---|---|
| POST /authorizations {card, amount, category, merchant, country} | 200 approved, or declined with the rule | 429; on a timeout the processor's default applies | Yes: a decision writes nothing |
| PUT /expenses/{id} {revision, ...} | 200 verdicts | 409 older revision | Yes: id and revision |
| POST /rules/{id}/versions {tree, effective_from, backfill} | 201 version, backfill id | 422 with the reason | Idempotency-Key header |
| GET /rules/{id}/versions | 200 every version, who, when | 404 | Yes: a read |
| GET /expenses/{id}/violations | 200 rule version, failing predicates, facts | 404 | Yes: a read |
| GET /backfills/{id} | 200 chunks done of total | 404 | Yes: 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.
- 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.
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
);- 1Progress can never pass the plan.
- 2The chunk row commits with its work, so a chunk runs once.
-- 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;- 1A change inserts a row. Nothing updates a version.
- 2The trees, as stored. The service parses and checks them before insert.
- 3Derived at save time: every field in the rule is known at the swipe.
- 4The values the rule read. The explanation does not depend on later edits.
- 5One row per version per subject, so a retry inserts nothing.
- 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.
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.
| tool | capability | what it gives this design | also used for |
|---|---|---|---|
| Postgres | jsonb | Stores trees and facts as written, with no column per field. | Settings, event payloads |
| Postgres | Composite primary keys | One rule version per number; one violation per version and subject. | Idempotent writes |
| Postgres | INSERT ... ON CONFLICT | A retried event or chunk writes nothing new. | T9 |
| Postgres | FOR UPDATE SKIP LOCKED | Workers share the chunks of a backfill. | B6 |
| Postgres | Transactions | An expense and its violations commit together; so does a chunk. | Every multi-row change |
| Postgres | Partial indexes, partitions | Fast review queue; old months move away. | D2 |
| Postgres | Row-level security | One company never reads another's rules or expenses. | O6 |
| Service | Compiled rule snapshot per company | A decision reads memory only, with no database call. | Feature flags, routing tables |
| Service | Guard derivation | The index comes from the tree. Nobody tags a rule by hand. | Query planners, search percolation |
| Service | State keyed by trip | One 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.
| rule model | status | why |
|---|---|---|
| Rules in code | Not approved | Each change is a deploy, and companies cannot edit them. |
| A SQL WHERE clause per rule | Not approved | Injection risk, and a false WHERE explains nothing. |
| A free text expression language | Power users | Needs a parser and limits; the builder must render it back. |
| JSON tree of typed predicates | Approved | Checked at save time, easy to version, and each node can explain itself. |
| A forward-chaining rule network | Rules that feed rules | Built for rules that fire other rules. This prompt has none. |
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- 1Fields and operators are a closed list, each with a type. An unknown field fails at save time.
- 2The two trees let the builder ask two plain questions: does this apply, and what must hold.
- 3Each NOT flips what the walk wants, so a nested NOT needs no special case.
- 4An AND fails on its false children; the true ones did no harm.
- 5An OR that should be true failed on every child, so all of them count.
Tested source Go: fields · Go: evaluate · Go: explain
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},
}
// 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")
}
// 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.
| in-line | reporting | |
|---|---|---|
| When | The card waits | After settlement, and on each edit |
| Deadline | Under 2 s, end to end | Seconds to minutes |
| Fields | Amount, merchant, category, country | Those, plus receipt and attendees |
| Rules | Block rules that can run in-line | Every rule |
| Reads | Memory | Memory, then one transaction |
| Result | Approve or decline | A violation with its explanation |
| method | status | why |
|---|---|---|
| Load rules from the database per swipe | Not approved | The card path then depends on the database. |
| Snapshot in memory, refreshed on publish | Approved | A decision reads one version of the rule set, throughout. |
| Two rule engines, one per path | Not approved | The paths drift, and a swipe and its report disagree. |
| One evaluator; each field says when it is known | Approved | Inline eligibility is derived from the tree. |
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- 1One snapshot per decision. A publish swaps in a new one, and the old one finishes its work.
- 2A rule that reads a receipt can never block: the field does not exist yet.
- 3A preview, kept nowhere. If the swipe is declined, the trip never saw it.
- 4A repeat or a stale event does nothing.
- 5Adding a receipt fixes the violation, and the row stays as history.
Tested source Go: authorize and record
// 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.
| rules | scan/s | index/s | rules read | p99 |
|---|---|---|---|---|
| 1,000 | 46,976 | 5,008,769 | 3.8 | 1.0 µs |
| 10,000 | 4,410 | 582,811 | 35.1 | 12 µs |
| 50,000 | 379 | 75,240 | 173.2 | 105 µs |
| narrowing method | status | why |
|---|---|---|
| Scan every rule | Under 100 rules | Simple, and linear in rules. |
| A category column that an admin sets | Not approved | A wrong tag silently skips a rule. |
| Guards derived from the tree | Approved | Sound by construction, and proved against a scan. |
| Trip rules by the category they read | Approved | A taxi cannot change a meal cap, so that rule does not run. |
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- 1A guard is necessary, not sufficient. The index may return a rule that passes, never miss one that fires.
- 2An OR with an unguarded branch gives no guard, so that rule goes to the open bucket.
- 3The rule fires when require is false, so its guard comes from the negated tree: amount <= 75 gives amount >= 76.
- 4A rule sits under one field only: merchant, then country, then category. No expense reaches it twice.
- 5A sorted bucket stops at the first rule this amount cannot fire.
Tested source Go: guards · Go: index
// 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
}
// 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.
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- 1The key is the trip, not a calendar window. A trip has no fixed length.
- 2The aggregate keeps a row per expense, so idempotence costs one lookup.
- 3An edit is a subtraction and an addition, so totals never drift.
- 4Days between expenses count. A day with no spend is still a day away.
Tested source Go: trip aggregate
// 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
}
| method | status | why |
|---|---|---|
| Sum the rows on every expense | Reporting only | Correct, and too slow for the card path. |
| Calendar windows, by week or month | Not approved | A trip crosses windows, so the sum is wrong. |
| A counter with no expense ids | Not approved | A repeat counts twice, and an edit cannot subtract. |
| State keyed by trip, with ids and revisions | Approved | Order does not matter, and a repeat changes nothing. |
| case | behaviour |
|---|---|
| Each expense passes, the trip fails | A trip violation appears on the expense that crosses the cap. |
| A swipe would cross a block cap | The preview declines it before the trip changes. |
| An expense arrives weeks late | The trip reopens and its rules run again. |
| An edit lowers the total | The trip violation closes. |
| No booking names the trip | A 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.
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- 1In the same transaction, so a new version never lacks its backfill.
- 2A dead worker's chunk reappears when the lease ends.
- 3A crash between the commit and the acknowledgement runs the job again, and this line stops it.
- 4Only the subjects this chunk read. Expenses before the effective date keep their old result.
- 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
// 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
}
// 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
}
// 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
}
-- 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;| method | status | why |
|---|---|---|
| One transaction over all history | Not approved | Long locks; one bad row rolls back everything. |
| A script with an offset in memory | Not approved | A crash restarts from 0, or skips rows. |
| Evaluate lazily when a report reads | Small tenants | No backfill cost, and slow reports. |
| Chunks on a queue, one transaction each | Approved | Resumable and safe to run in parallel. |
| backfill of 100,000 expenses | expenses/s |
|---|---|
| 1 worker, chunks of 1,000 | 119,048 |
| 4 workers, chunks of 1,000 | 347,766 |
| audit question | answer 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.
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
- 0 failed: amount le 7500; the expense has 9200
- 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.
| event | result | why it is safe | saved by |
|---|---|---|---|
| The decision service misses the deadline | The processor applies its default. | Reporting still runs every rule, so a wrong approval becomes a flag. | Two paths |
| Postgres is down during a swipe | Decisions continue from memory. | The card path reads no database. Settlement events wait in the feed. | Snapshot |
| A settlement event arrives twice | The second changes nothing. | The revision check, then the unique violation key. | Unique key |
| Two edits arrive out of order | The older one is ignored. | Only a newer revision updates the row. | Revision |
| A backfill worker dies mid-chunk | The chunk rolls back. | The lease ends and another worker takes it. | Transaction, lease |
| A worker dies after the commit | The job runs again. | The chunk row exists, so the job only acknowledges. | Chunk row |
| A chunk keeps failing | It moves to the dead jobs. | The backfill stays running, and a person sees why. | Dead jobs |
| An admin saves a broken rule | 422 with the reason. | Types, depth and size are checked before insert. | Validation |
| A new rule flags far too much | Publish version 3, the old tree. | The backfill clears the wrong flags, and history keeps them. | Versions |
| A server holds an old snapshot | It decides on the last version for a moment. | Each decision records its version, and reporting uses the new one. | Version in row |
| step | add | it handles | move up when you see |
|---|---|---|---|
| 1 | One Postgres, a scan per expense. | About 46,976 expenses a second at 1,000 rules. | The card path waits on the database. |
| 2 | Rule snapshots in memory, refreshed on publish. | Decisions survive a database outage. | A large company's rules take most of the CPU. |
| 3 | The rule index. | About 580,000 evaluations a second at 10,000 rules. | A backfill slows settlement writes. |
| 4 | Backfill workers with a rate limit per company. | A large company in seconds to minutes, in the background. | Reports slow down the primary. |
| 5 | A read replica for reports, and monthly partitions. | Long queries leave the primary. | One primary nears its write limit. |
| 6 | Shards 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.
| question | answer | deeper |
|---|---|---|
| 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 |
0 of 9 known
Why keep a rule as data and not as code or as a SQL string?
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?
What is the failing predicate under a NOT?
Why can a receipt rule never decline a card?
How does the index stay correct for a rule with OR and NOT?
Why did the index read about 35 rules and not 10,000?
Two expenses on a trip arrive out of order, and one is sent twice. Is the trip total right?
A backfill worker crashes after it commits a chunk but before it acknowledges the job. What happens?
A manager asks in June why an expense was flagged in January, and the rule changed in March. What do you show?
- 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.