Adding Trip-Level Limits to an Expense Policy Checker
System DesignModel answerLast updated
Extend a per-expense policy engine so it also enforces trip-wide spending caps, and redesign its output to report both line-item and trip-level violations with clear explanations.
You have already built a policy engine for an expense-reporting product. Its function evaluateRules takes a list of submitted expenses and checks each one on its own against a set of configurable rules, such as a per-item cap. Many companies use this engine through a shared expenses API, and each company can define its own rules.
Now extend the engine to enforce trip-level rules, which depend on the combined spending of all expenses that share a trip:
- The total of all expenses on a trip must not exceed $2000.
- The total of meal expenses on a trip must not exceed $200.
In the sample data, trip "002" breaks both rules.
Describe how you would:
- Change the design and the return type of
evaluateRulesso the result contains trip-level violations next to the existing per-expense violations. - Group and aggregate the expenses, and decide in what order the checks run.
- Make an aggregate violation understandable to the employee and the approver, given that no single expense is the culprit.
- Keep the evaluation efficient, both for large batches and for single expense edits.
- Expose the new results through the shared, multi-company expenses API without breaking existing clients.
State your assumptions (currency, missing trip IDs, boundary behavior) and explain the trade-offs. Include a short code sketch of the extended evaluation.
Hints
Hint 1
Introduce a rule scope (expense vs. trip) and treat the new limits as configuration: an optional filter, an aggregate function, a comparison and a threshold. Then you do not need a new code path per rule.
Hint 2
Group expenses by trip once with a hash map and share that grouping across all trip rules. Do money math in integer cents, and decide what 'cannot exceed' means at exactly the limit.
Hint 3
A trip violation needs more than a rule name: include observed total, limit, overage and the contributing expense IDs. For production, think about incremental updates per trip, concurrent submissions, and versioning the changed response shape.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Overview
The first version judges each expense in isolation. A trip-level rule has no single expense to blame, so the engine needs three additions: a rule scope, a grouping and aggregation phase, and a new violation record. The cleanest approach is a two-phase evaluation that leaves the existing per-expense path untouched.
1. Clarify assumptions
- Grouping key: Expenses without a
trip_idare skipped by trip rules and must not crash the engine. - Money: Normalize to the company's base currency and store integer cents. Never sum floats.
- Boundary: "Cannot exceed $2000" means a violation only when total > 200000 cents. Exactly $2000 passes.
- Which expenses count: Expenses that already break a per-expense rule still count toward the trip total, since the money was spent. Make this a per-company setting (for example, exclude rejected expenses).
- Scale: Many tenants, tens to hundreds of rules each, usually fewer than 100 expenses per trip. Evaluation runs in batch and on every create, edit or delete.
2. Rules as data
Model each rule as configuration so every company can define its own:
Rule {
rule_id, company_id, version,
scope: EXPENSE | TRIP,
filter: { field, op, value } | null,
aggregate: SUM | COUNT | MAX # trip scope only
field: "amount_cents",
op: ">",
threshold: cents,
message_template
}
The two new rules become:
- Trip total:
TRIP, no filter, SUM(amount) > 200000 - Trip meals:
TRIP, filter category == meals, SUM(amount) > 20000
3. Grouping and evaluation order
- Validate and normalize. Convert currency to cents and move malformed records into an
errorslist. - Per-expense rules. Existing behavior, unchanged.
- Group once, then trip rules. One O(n) pass builds
trip_id -> [expenses]. Every trip rule reuses it. For each trip and rule, apply the filter, aggregate, compare with the threshold, and emit a violation that records the contributing expense IDs.
The phases are independent, so results are deterministic. Sort output by trip_id, then rule_id, to keep tests and diffs stable.
4. New return type
Replace the flat list with a structured result and version the API because this is a breaking change.
from dataclasses import dataclass, field
from collections import defaultdict
from typing import Callable, Optional
@dataclass
class Expense:
expense_id: str
trip_id: Optional[str]
category: str
amount_cents: int
@dataclass
class ExpenseViolation:
expense_id: str
rule_id: str
message: str
@dataclass
class TripViolation:
trip_id: str
rule_id: str
observed_cents: int
limit_cents: int
contributing_expense_ids: list
message: str
@dataclass
class EvaluationResult:
expense_violations: list = field(default_factory=list)
trip_violations: list = field(default_factory=list)
@dataclass
class ExpenseRule:
rule_id: str
violates: Callable[[Expense], bool]
message: str
@dataclass
class TripSumRule:
rule_id: str
limit_cents: int
message: str
filter: Callable[[Expense], bool] = lambda e: True
def evaluate_rules(expenses, expense_rules, trip_rules):
result = EvaluationResult()
for e in expenses:
for r in expense_rules:
if r.violates(e):
result.expense_violations.append(
ExpenseViolation(e.expense_id, r.rule_id, r.message))
by_trip = defaultdict(list)
for e in expenses:
if e.trip_id is not None:
by_trip[e.trip_id].append(e)
for trip_id in sorted(by_trip):
for r in trip_rules:
matched = [e for e in by_trip[trip_id] if r.filter(e)]
total = sum(e.amount_cents for e in matched)
if total > r.limit_cents:
result.trip_violations.append(TripViolation(
trip_id, r.rule_id, total, r.limit_cents,
[e.expense_id for e in matched],
f"{r.message}: ${total/100:.2f} > ${r.limit_cents/100:.2f}"))
return result
On the sample data, trip "002" yields two TripViolation entries (total and meals), while line-item problems stay in expense_violations.
5. Explainability
"Trip 002 broke the meals rule" is not actionable. Each trip violation should carry:
- Observed value, limit and currency, plus the overage (
observed - limit). - The contributing expense IDs so the UI can highlight the line items.
- Rule ID and rule version, so audits show which policy applied even after the rule changes.
Do not blame the "last" expense; that is order-dependent and feels arbitrary. List all contributors. Optionally flag the item that crossed the threshold (by submission time) as a hint only.
6. Performance
- Batch: O(n·R_e + n·R_t) time, O(n) extra space for the grouping. Share buckets between rules with the same filter.
- Incremental (the real production path): On create, edit or delete, re-evaluate only that expense's rules and that single trip's aggregates. For big trips keep running totals per
(trip_id, rule_id)and apply deltas. Keep a periodic full recompute as reconciliation. - Concurrency: Two expenses submitted simultaneously may each pass alone but jointly exceed the cap. Update the aggregate inside a transaction or use optimistic locking on a trip version.
- Multi-tenant: Cache each company's compiled rule set, invalidate on rule version change, and isolate noisy tenants with per-tenant rate limits or queues.
7. API integration and rollout
- Return
{ "expense_violations": [...], "trip_violations": [...] }under a new API version, or addtrip_violationsas an additive field so old clients keep working. - Allow filtering by
trip_idand support evaluating a single trip on demand. - Roll out in shadow mode first: compute trip violations, log them, and compare with expectations before they block approvals. Then enable per company behind a feature flag.
- Decide whether trip violations block submission or only flag for review, and make it a per-rule severity.
Edge cases and common mistakes
- Summing floats or mixing currencies.
- Using
>=and rejecting trips exactly at the limit. - Regrouping data separately for each rule.
- Crashing on null trip IDs.
- Returning only a rule name with no observed value or contributing expenses.
- Ignoring edits and deletes, which leave stale aggregates if only creates are handled.
- Forgetting that a trip can break several rules at once, so results must be a list, not a single status.