Build a Policy-Driven Expense Approval Engine
System DesignModel answerLast updated
Design an extensible rule evaluation system that validates expense reports against configurable business policies and returns a structured approval decision.
Background
Your team is building an internal tool to automate expense approvals. Finance has a growing list of policies — things like "meals over $75 need manager sign-off" or "any international trip requires VP approval" — and they keep adding new ones. Right now every new policy means touching the core evaluation code, which keeps breaking things.
Your job is to design a small but well-structured system that separates each policy from the engine that runs them, so new policies can be added as isolated units of code.
What to Design
An expense report has at minimum these fields:
amount: float
currency: str # e.g. "USD", "EUR"
category: str # e.g. "MEALS", "TRAVEL", "SOFTWARE"
date: date
employee_level: int # e.g. 1–5
vendor_id: str
is_international: bool
Your system needs three things:
1. A Rule abstraction
Each rule inspects a report and returns a structured result: did it pass, does it need review, or should it be rejected outright? The result should carry a human-readable reason.
2. An Evaluator class
It holds a list of rules and runs them all against a given report. It produces a single final decision: APPROVED, NEEDS_REVIEW, or REJECTED. Define clearly how multiple rule results get folded into one outcome.
3. A registration mechanism
New rule types should be addable without modifying the Evaluator. Concrete rule instances should be constructable from configuration (e.g., a rule type name plus parameters).
Example Interface
evaluator = Evaluator()
evaluator.add_rule(build_rule("category_cap", "meal-cap", category="MEALS", cap=75.0))
evaluator.add_rule(build_rule("approval_threshold", "large-spend", limit=500.0, approver="MANAGER"))
decision = evaluator.evaluate_report(report, context)
# decision.status -> "NEEDS_REVIEW"
# decision.reasons -> ["Over $500", ...]
# decision.required_approvers -> {"MANAGER"}
Requirements and Constraints
- Rules may inspect any combination of fields on the report.
- When multiple rules fire, define and justify your aggregation strategy.
- Some rules need external data (e.g., a live currency conversion rate, a vendor risk list). Show how rules access that data without coupling to a specific service.
- Address these edge cases explicitly:
- No rules are registered
- A rule throws an exception (e.g., the FX service is unavailable)
- Multiple rules each require a different approver
- Negative or zero amounts (refunds, data errors)
A written walkthrough plus working Python code is expected. Discuss the design trade-offs you made.
Hints
Hint 1
Think about what the Strategy pattern buys you here: if every rule implements the same interface, the Evaluator never needs to know what any specific rule does. What should that interface look like?
Hint 2
For aggregation, model outcomes as an ordered severity scale (pass < flag < fail). The final decision is the maximum severity across all rules — this makes the result order-independent and easy to reason about.
Hint 3
Rules that need external data (FX rates, vendor risk lists) should not call services directly. Consider passing an injected context object into each rule's evaluate method, so rules stay pure and tests can pass in fakes.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is an object-oriented design problem, not an algorithms problem. The interviewer is looking for three things: a clean rule abstraction, a deterministic aggregation policy, and a registration mechanism that keeps the engine itself closed to modification. The right pattern is Strategy: every rule implements one interface, and the Evaluator treats them all identically.
Core Design Decisions
1. Return structured results, not raw strings
Each rule returns a RuleResult dataclass rather than a bare "PASS" string. It carries:
- an
Outcomeenum (PASS,FLAG,FAIL) - the rule's id
- a human-readable message
- an optional
required_approver(e.g."MANAGER","VP")
This matters downstream — the UI needs to explain why a report is held for review, not just that it is.
2. Order outcomes by severity and take the maximum
Define PASS=0 < FLAG=1 < FAIL=2 using an IntEnum. Aggregation across N rules is then just max(outcome):
- any
FAIL→REJECTED - otherwise any
FLAG→NEEDS_REVIEW - otherwise →
APPROVED
This policy is associative and order-independent: rule registration order cannot change the outcome, and no rule can silently override another's rejection. Say this out loud in the interview — it shows you thought about correctness, not just happy paths.
3. Inject external data through a context object
Rules that need FX rates or vendor risk data must not call services directly. Instead, the Evaluator passes an EvaluationContext into each rule's evaluate() call. The context holds callable providers (e.g. fx_rate(currency, date) -> float). This keeps rules pure, makes them trivially testable with fakes, and lets the engine batch or cache I/O in one place.
4. Register rule types with a decorator; build instances from config
A module-level RULE_TYPES dict maps a string name to a class. A @register_rule_type("name") decorator fills it. Concrete rule instances are created by build_rule("type_name", rule_id, **params). Adding a new rule type means writing one new file and one decorator — the Evaluator is never touched. This satisfies the Open/Closed Principle directly.
Edge Cases
| Case | Handling |
|---|---|
| No rules registered | Report is APPROVED — state this explicitly; some orgs would choose NEEDS_REVIEW |
| Rule raises an exception | Catch it, convert to FLAG with the error message. Never auto-approve on error; never crash the whole batch |
| Multiple required approvers | Collect all required_approver values into a set on the final decision |
| Negative/zero amounts | A dedicated validation rule FAILs on these before policy rules run |
| Multi-currency | Normalize to USD inside EvaluationContext.amount_usd() using the injected rate; never hardcode a rate |
Complexity
- Time: O(R · c) per report, where R is the number of rules and c is the cost per rule. Pure rules are O(1); external lookups dominate — which is why the context caches them.
- Space: O(R) for the rule list, O(R) for collected results per evaluation.
Python Solution
from __future__ import annotations
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from datetime import date
from enum import IntEnum
from typing import Callable, Dict, FrozenSet, List, Optional, Set, Type
# ---------------------------------------------------------------------------
# Outcome severity — ordered so max() gives the right aggregation
# ---------------------------------------------------------------------------
class Outcome(IntEnum):
PASS = 0
FLAG = 1
FAIL = 2
OUTCOME_TO_STATUS = {
Outcome.PASS: "APPROVED",
Outcome.FLAG: "NEEDS_REVIEW",
Outcome.FAIL: "REJECTED",
}
# ---------------------------------------------------------------------------
# Core data structures
# ---------------------------------------------------------------------------
@dataclass(frozen=True)
class ExpenseReport:
report_id: str
employee_id: str
amount: float
currency: str
category: str
date: date
employee_level: int
vendor_id: str
is_international: bool = False
@dataclass
class EvaluationContext:
"""
Holds all external data providers. Rules read from here, never
call services directly. Swap in fakes during tests.
"""
fx_rate: Callable[[str, date], float] = field(
default=lambda currency, d: 1.0 # default: treat everything as USD
)
high_risk_vendors: FrozenSet[str] = frozenset()
def amount_usd(self, report: ExpenseReport) -> float:
return report.amount * self.fx_rate(report.currency, report.date)
@dataclass(frozen=True)
class RuleResult:
rule_id: str
outcome: Outcome
message: str = ""
required_approver: Optional[str] = None
@dataclass
class EvaluationDecision:
status: str
reasons: List[str]
required_approvers: Set[str]
# ---------------------------------------------------------------------------
# Rule abstraction
# ---------------------------------------------------------------------------
class Rule(ABC):
def __init__(self, rule_id: str):
self.rule_id = rule_id
@abstractmethod
def evaluate(
self, report: ExpenseReport, ctx: EvaluationContext
) -> RuleResult: ...
def _pass(self) -> RuleResult:
return RuleResult(self.rule_id, Outcome.PASS)
# ---------------------------------------------------------------------------
# Rule registry — new types plug in here, engine never changes
# ---------------------------------------------------------------------------
RULE_TYPES: Dict[str, Type[Rule]] = {}
def register_rule_type(name: str):
def decorator(cls: Type[Rule]) -> Type[Rule]:
if name in RULE_TYPES:
raise ValueError(f"Rule type already registered: {name!r}")
RULE_TYPES[name] = cls
return cls
return decorator
def build_rule(type_name: str, rule_id: str, **params) -> Rule:
if type_name not in RULE_TYPES:
raise KeyError(f"Unknown rule type: {type_name!r}")
return RULE_TYPES[type_name](rule_id, **params)
# ---------------------------------------------------------------------------
# Concrete rule implementations
# ---------------------------------------------------------------------------
@register_rule_type("approval_threshold")
class ApprovalThresholdRule(Rule):
"""FLAG any expense above a dollar limit and name the required approver."""
def __init__(self, rule_id: str, limit: float, approver: str = "MANAGER"):
super().__init__(rule_id)
self.limit = limit
self.approver = approver
def evaluate(self, report: ExpenseReport, ctx: EvaluationContext) -> RuleResult:
if ctx.amount_usd(report) > self.limit:
return RuleResult(
self.rule_id, Outcome.FLAG,
f"Amount exceeds ${self.limit:.2f} limit",
self.approver,
)
return self._pass()
@register_rule_type("category_cap")
class CategoryCapRule(Rule):
"""FAIL if a specific category exceeds its per-report cap."""
def __init__(self, rule_id: str, category: str, cap: float):
super().__init__(rule_id)
self.category = category
self.cap = cap
def evaluate(self, report: ExpenseReport, ctx: EvaluationContext) -> RuleResult:
if report.category == self.category and ctx.amount_usd(report) > self.cap:
return RuleResult(
self.rule_id, Outcome.FAIL,
f"{self.category} expense of ${ctx.amount_usd(report):.2f} "
f"exceeds ${self.cap:.2f} cap",
)
return self._pass()
@register_rule_type("international_travel")
class InternationalTravelRule(Rule):
"""FLAG international travel expenses for VP approval."""
def evaluate(self, report: ExpenseReport, ctx: EvaluationContext) -> RuleResult:
if report.category == "TRAVEL" and report.is_international:
return RuleResult(
self.rule_id, Outcome.FLAG,
"International travel requires VP approval",
"VP",
)
return self._pass()
@register_rule_type("high_risk_vendor")
class HighRiskVendorRule(Rule):
"""FLAG any expense from a vendor on the risk list."""
def evaluate(self, report: ExpenseReport, ctx: EvaluationContext) -> RuleResult:
if report.vendor_id in ctx.high_risk_vendors:
return RuleResult(
self.rule_id, Outcome.FLAG,
f"Vendor {report.vendor_id!r} is on the high-risk list",
"MANAGER",
)
return self._pass()
@register_rule_type("negative_amount_guard")
class NegativeAmountGuard(Rule):
"""FAIL reports with non-positive amounts — likely a data error."""
def evaluate(self, report: ExpenseReport, ctx: EvaluationContext) -> RuleResult:
if report.amount <= 0:
return RuleResult(
self.rule_id, Outcome.FAIL,
f"Invalid amount: {report.amount}",
)
return self._pass()
# ---------------------------------------------------------------------------
# Evaluator — closed to modification, open to new rule registrations
# ---------------------------------------------------------------------------
class Evaluator:
def __init__(self):
self._rules: List[Rule] = []
def add_rule(self, rule: Rule) -> None:
self._rules.append(rule)
def evaluate_report(
self, report: ExpenseReport, ctx: EvaluationContext
) -> EvaluationDecision:
if not self._rules:
# No rules → auto-approve; document this policy decision.
return EvaluationDecision("APPROVED", [], set())
worst_outcome = Outcome.PASS
reasons: List[str] = []
approvers: Set[str] = set()
for rule in self._rules:
try:
result = rule.evaluate(report, ctx)
except Exception as exc:
# Service outage, bad data, etc. — fail closed to human review.
result = RuleResult(
rule.rule_id, Outcome.FLAG,
f"Rule error ({type(exc).__name__}): {exc}",
)
if result.outcome > Outcome.PASS:
reasons.append(result.message)
if result.outcome > worst_outcome:
worst_outcome = result.outcome
if result.required_approver:
approvers.add(result.required_approver)
return EvaluationDecision(
status=OUTCOME_TO_STATUS[worst_outcome],
reasons=reasons,
required_approvers=approvers,
)
# ---------------------------------------------------------------------------
# Usage example
# ---------------------------------------------------------------------------
if __name__ == "__main__":
evaluator = Evaluator()
evaluator.add_rule(build_rule("negative_amount_guard", "guard-negative"))
evaluator.add_rule(build_rule("category_cap", "meal-cap", category="MEALS", cap=75.0))
evaluator.add_rule(build_rule("approval_threshold", "large-spend", limit=500.0, approver="MANAGER"))
evaluator.add_rule(build_rule("international_travel", "intl-travel"))
evaluator.add_rule(build_rule("high_risk_vendor", "risky-vendor"))
ctx = EvaluationContext(
fx_rate=lambda cur, d: 1.0,
high_risk_vendors=frozenset({"VENDOR_XYZ"}),
)
report = ExpenseReport(
report_id="RPT-001",
employee_id="EMP-42",
amount=620.0,
currency="USD",
category="TRAVEL",
date=date(2025, 6, 1),
employee_level=3,
vendor_id="VENDOR_XYZ",
is_international=True,
)
decision = evaluator.evaluate_report(report, ctx)
print(decision.status) # NEEDS_REVIEW
print(decision.reasons) # multiple flags
print(decision.required_approvers) # {'MANAGER', 'VP'}
Common Mistakes to Avoid
- Putting rule logic inside
Evaluator— that forces you to modify the engine every time policy changes. - Using string comparisons (
result == "FAIL") instead of an ordered enum — makes aggregation fragile and easy to misspell. - Letting rules call external services directly — impossible to unit test and hides I/O from the engine.
- Silently swallowing rule exceptions or, worse, treating an error as a pass — always fail closed.