Policy Engine for Flagging Company Card Spending
System DesignModel answerLast updated
Design a multi-tenant engine that checks card transactions and whole trips against configurable policies, with auditable results and an API that can evolve without breaking clients.
Problem
Your company's finance platform serves many customer organizations. You must design a service that reviews corporate card transactions and marks the ones a manager should look at.
Starting point
Transactions arrive as a list of dictionaries in which every key and value is a string. The first policy contains four checks:
- A restaurant charge must not exceed $75.
- Airfare is not allowed.
- Entertainment is not allowed.
- No single charge may exceed $250.
Define your own types for rules, then propose the signature and return type of:
evaluateRules(rules: list<Rule>, expenses: list<Expense>) -> ReturnType
The result will be returned by an expenses API shared by many companies.
Design goals
- Handle 100+ rules chosen per manager or team. New rules must be creatable through an API, and adding them must not break existing clients.
- State the evaluation semantics: ordering and priority, combinators (AND / OR / NOT), short-circuit versus exhaustive evaluation, and how conflicting rules are resolved.
- Make results explainable and auditable: a reason per violation, rule metadata, timestamps, and which policy and which actor or system caused it.
- Cover tenant isolation, authorization, observability, idempotency, deterministic output order, and resilience when part of a batch fails.
- Define the core models (Expense, Trip, Rule, Policy, RuleResult, EvaluationSummary) and explain how string inputs for amounts, categories, and vendor types are parsed and validated.
Extension: trip-level rules
Add rules that work on groups of expenses:
- (a) The total for a trip must not exceed $2000.
- (b) Total meal spending within a trip must not exceed $200.
In the sample data, trip "002" breaks both.
Extend the engine so single-expense and trip-level rules are evaluated together. Describe how you aggregate, what you cache, and how you update results incrementally. Then propose a backward-compatible return type that reports both expense-level and trip-level violations, including entity type, identifiers, violated rule codes, severity, readable messages, machine-readable fields, and pagination.
Clarifications to raise
Discuss, and state assumptions for, the following:
- Policy scoping (company / team / user) and how overrides and precedence work.
- Currency conversion, locale, whether tax and tip count toward meal caps, and per-diem versus per-transaction limits.
- Category taxonomy (expense type, vendor type): who assigns it, and what happens with unknown or wrong labels.
- Time windows (trip, day, month), receipts, exception and approval flows, notifications.
- Versioning, gradual rollout, rate limits, and long-term compatibility of the return type.
What to deliver
A structured design: assumptions, data models, rule representation, evaluation semantics, the function signature and return type, the aggregate extension, and the main trade-offs.
Hints
Hint 1
Treat rules as stored data (a small expression tree with a whitelist of fields and operators) rather than code, so new rules need no deploy and can be validated when they are created.
Hint 2
Return one flat, sorted, paginated list of results, each tagged with an entity type and ID. Adding trip-level results then means adding rows, not changing the shape, which keeps old clients working.
Hint 3
For aggregate rules, group parsed expenses by key once, compute each needed sum a single time, and cache per-group running totals so a new or edited expense only adjusts its own group rather than triggering a full recomputation.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Framing
The task starts as four if statements and grows into a multi-tenant platform. The strongest approach is to make rules data, fix the evaluation semantics early, and design a result shape that can grow without breaking clients.
1. Assumptions
- Scoping. Policies attach at company, team, or user level. For a given
rule_code, the most specific scope wins. A narrower scope may change parameters (raise $75 to $100) or disable a rule only if the parent marks it overridable. - Money. Store integer minor units plus an ISO currency code. Convert to the company's base currency using the rate on the transaction date, and record the rate used.
- Meal caps. Include tax and tip by default, behind a configurable flag.
- Per-diem versus per-transaction. Different rule kinds. Per-diem is an aggregate over (trip, day).
- Taxonomy. The card network's merchant category code maps to
vendor_type. The user or a classifier setsexpense_type. Unknown values becomeUNKNOWNand are flagged, never silently passed. - Workflow. Approvals, receipts, and notifications are downstream. The engine only emits flags.
- Scale. About 10k tenants and 50M expenses per month: roughly 20 evaluations per second on average and a few hundred at month-end peaks. Target p99 under 200 ms for a synchronous single-expense check. Large batches run asynchronously.
2. Parsing string input
Every raw dictionary passes through a schema validator:
- Amounts parse with
Decimal(never float), then convert to minor units. Reject negatives unless refunds are explicitly modeled. - Dates and currency codes are validated.
- Categories are lowercased and mapped through a tenant-aware alias table (
"restaurant","Dining", and the restaurant merchant code all map toMEALS).
An invalid row yields an error entry with field-level reasons. It is not dropped, and one bad row never fails the batch.
3. Data models
class Expense:
expense_id: str; trip_id: str | None; employee_id: str
amount_minor: int; currency: str; amount_base_minor: int
expense_type: str; vendor_type: str; txn_date: date
class Trip: trip_id: str; employee_id: str; start: date; end: date
class Rule:
rule_code: str; version: int
scope: "expense" | "trip" | "trip_day"
predicate: Node # expression tree
aggregate: Aggregate | None
severity: "INFO" | "REVIEW" | "BLOCK"
priority: int
message_template: str
class Policy:
policy_id: str; tenant_id: str; scope_ref: str
rules: list[RuleRef]; version: int; effective_from: datetime
class RuleResult:
rule_code: str; rule_version: int; policy_id: str
entity_type: str; entity_id: str
severity: str; message: str
fields: dict # {"observed": 9000, "limit": 7500, "currency": "USD"}
evaluated_at: datetime
class EvaluationSummary:
evaluation_id: str; counts_by_severity: dict
outcome: str; errors: list
4. Rule representation and semantics
A rule is a JSON expression tree:
{"all": [{"field": "expense_type", "op": "eq", "value": "MEALS"},
{"field": "amount_base_minor", "op": "gt", "value": 7500}]}
- Operators:
eq,in,gt,gte,lt,contains. Combinators:all,any,not. - A predicate that evaluates true means a violation.
- On creation, validate against a field/operator whitelist, check types against the Expense schema, and cap nesting depth. This keeps stored rules safe.
The base rules become MEALS AND amount > 75, type == AIRFARE, type == ENTERTAINMENT, and amount > 250.
Semantics
- Exhaustive across rules. Reviewers need every reason, so evaluation never stops at the first violation.
- Short-circuit within a predicate.
allandanystop early. This is purely a performance choice and does not change results. - Priority controls presentation and the ordering of output, not which rules run. Sort by
(entity_type, entity_id, priority, rule_code)for determinism. - Conflicts. Rules only flag; none "approve." An entity's outcome is its highest severity. Same-code conflicts across scopes follow the precedence above.
- Exemptions. An approved exception, keyed by
(rule_code, entity_id), downgrades the result to INFO but keeps it visible for the audit trail.
5. Function and return type
def evaluate_rules(rules, expenses, trips=(), *, page_token=None,
page_size=500) -> EvaluationResponse
class EvaluationResponse:
schema_version: str
evaluation_id: str # idempotency key, echoed back
policy_snapshot: list[dict] # policy_id + version used
results: list[RuleResult] # flat, sorted, paginated
summary: EvaluationSummary
next_page_token: str | None
A flat list tagged with entity_type is the key compatibility decision:
- Old clients filter to
entity_type == "expense"and see no change. - Trip results are just new rows with
entity_type == "trip". - Fields are only ever added, and clients must ignore unknown ones.
- Unknown severities are treated as REVIEW, which is documented.
- A breaking change requires a new
schema_version, negotiated by header.
6. Aggregate rules
An aggregate rule adds a group key, a row filter, an aggregation, and a threshold:
{"scope": "trip", "group_by": ["trip_id"],
"filter": {"field": "expense_type", "op": "eq", "value": "MEALS"},
"agg": {"fn": "sum", "field": "amount_base_minor"},
"predicate": {"op": "gt", "value": 20000}}
Single pass. Parse and validate expenses, then in one loop run expense-level rules and update accumulators keyed by (rule, group_key). After the loop, evaluate each group's predicate. Cost is O(E x R_expense + E x R_agg) with memory proportional to the number of groups. Share accumulators between rules with the same filter and key, so the $2000 total and the $200 meal cap each cost one add per expense.
Caching and incremental updates. Store per-group running totals (for example in Redis or a table keyed by tenant, trip, and measure), along with the contributing expense versions. When an expense is created, edited, or deleted, apply a delta to its group only and re-evaluate that group's rules. Use idempotent upserts keyed by expense_id and version so retries do not double-count. Rebuild periodically from source to correct drift, and invalidate on policy version change.
Sample outcome. Trip 002 yields two trip-level results, one for total over $2000 and one for meal total over $200, each with observed and limit values in fields, plus any expense-level flags.
7. Cross-cutting concerns
- Tenant isolation. Tenant ID comes from the authenticated token, never the payload. It is part of every key and query, with row-level security in storage.
- Authorization. Separate permissions to edit rules, assign policies, and read results.
- Idempotency. Clients send an idempotency key. The same key plus the same policy snapshot returns the same result.
- Determinism. Evaluate against a pinned policy version and use stable sorting. Do not call the clock inside predicates.
- Resilience. Isolate failures per rule and per row. A rule that errors emits an error entry and the batch continues, with the summary marked
PARTIAL. Use retries with backoff for dependencies like FX rates. - Observability. Per-tenant and per-rule metrics (latency, hit rate, error rate), structured logs with the evaluation ID, and traces. A sudden jump in a rule's hit rate often means a bad rule release.
- Rollout. Version rules and policies, canary new versions on a small tenant slice, and optionally run in shadow mode that records results without surfacing them.
- Audit. Persist results with policy and rule versions and the FX rate, so any past decision can be reproduced.
Trade-offs and common mistakes
- Data-driven rules versus code. Data is flexible and safe to ship, but less expressive. Offer a small set of named custom operators instead of arbitrary scripts.
- Synchronous versus batch. Sync checks give fast feedback. Month-end recomputation belongs in a queue.
- Common mistakes: using floats for money, stopping at the first violation, nesting results per expense so trip rules do not fit, ignoring FX, silently passing unknown categories, and failing a whole batch for one bad row.