RipplingExpense Rules Engine
Design an extensible corporate-card rules engine. Evaluate per-expense and per-trip policies, choose a useful return type, then support composite AND / OR / NOT rules and scale the design to millions of expenses and tens of thousands of rules.
Problem
- Input expenses are dictionaries with string keys and values. Typical fields include
expense_id,trip_id,amount_usd,expense_type,vendor_type, andvendor_name. Noteamount_usdarrives as a string ("49.99") and must be coerced tofloatbefore any numeric comparison. - Implement
evaluate_rules(rules: list<rule>, expenses: list<expense>) -> ...; the return type is part of the design discussion, but it should preserve which expense or trip violated which rule. - Base individual-expense rules include:
- no restaurant expense over $75 where
vendor_type == "restaurant"; - no airfare expenses;
- no entertainment expenses;
- no single expense over $250.
- no restaurant expense over $75 where
- Base group / trip rules include:
- no trip over $2000 total;
- no meal expenses over $200 total per trip.
- Design for future rule types and API-created rules; the last sentence of the prompt states that adding rules through an API must be supported later.
The two entry-point signatures the canonical shape exposes:
def evaluate_rules(rules: list[Rule], expenses: list[dict]) -> list[Violation]:
# Per-transaction pass: for each expense, each rule that is_violated_by(expense)
# emits a Violation(expense_id, rule_id, rule_description).
def evaluate_group_rules(group_rules: list[GroupRule], expenses: list[dict]) -> list[GroupViolation]:
# Per-trip pass: group expenses by rule.group_by, optionally filter each group,
# sum rule.aggregate_field, emit GroupViolation when total > rule.threshold.
# GroupViolation carries actual_value, threshold, and the contributing expense_ids.Examples
{
"expense_id": "001",
"trip_id": "001",
"amount_usd": "49.99",
"expense_type": "client_hosting",
"vendor_type": "restaurant",
"vendor_name": "Outback Roadhouse"
}A useful violation payload is explicit enough for API clients and notifications:
{
"rule_id": "single-expense-limit",
"expense_id": "004",
"trip_id": "002",
"message": "Expense 004 exceeds $250"
}Against the base rules, a representative expense set flags: a $153 restaurant meal (over the $75 restaurant limit), a $1996 airfare row (airfare disallowed AND over $250 — two violations for one expense), and a $59.50 entertainment row (entertainment disallowed). At the trip level, a trip whose rows sum to $2206.08 breaks the $2000 trip cap, and whose meal rows sum to $210.08 breaks the $200-per-trip meal cap. The same expense can be individually valid yet belong to a flagged trip.
Variants
SQL-style filter + validator
Some interviewers frame rules as SQL: separate "which rows does this rule apply to" (the WHERE clause) from "what makes an applicable row a violation." A single rule then holds filter_conditions (all must match for the rule to apply) and a distinct violation_condition:
@dataclass
class SQLLikeRule:
rule_id: str
description: str
filter_conditions: list[Condition] # WHERE: rows this rule applies to
violation_condition: Condition # what makes an applicable row a violation
def applies_to(self, e: dict) -> bool:
return all(c.matches(e) for c in self.filter_conditions)
def is_violated_by(self, e: dict) -> bool:
return self.applies_to(e) and self.violation_condition.matches(e)This cleanly splits applicability from the violation test; it is a structural alternative to the all-conditions-AND Rule, not a value conflict — clarify which framing the interviewer wants before coding.
Pitfalls
- Edge cases: parse
amount_usdas numeric before comparing (a comparison operator, not lexicographic); handle missing fields consistently (no key → treat the condition as non-matching rather than crashing); guard non-numeric garbage ("ABC"→ catchValueError/TypeError); handle empty groups (a trip with no expenses, or a filter that removes all rows, sums to 0 and should not flag); decide whether negative or zero amounts are invalid input or simply fail no threshold rule; clarify whether multiple rules can produce duplicate-looking messages for the same expense. - In AI-assisted rounds, interviewers expect the candidate to own the rule interface and the per-trip aggregation contract before prompting the tool. Some phone screens assume the candidate will use AI for the evaluator implementation; first narrate the rule design, walk through the examples, and decide how to prompt for a small
evaluatefunction rather than asking for a full end-to-end solution. Generating composite-rule boilerplate is fine, but the interface design has to come from you. - The interviewer can reverse direction on representation during plan review: one interviewer first approved a generic operand + operator design, then asked for hardcoded evaluation functions, forcing two rewrites. Lock the representation in explicitly before letting the AI generate code.
- Some phone screens mandate HackerRank's built-in agentic AI assistant under full screen share. Leave time to run the generated code — import errors in AI output have left candidates with nothing running and no time for the scale discussion.
Follow-ups
A AND B while B is defined as A AND C?Preparation
- Implement the base rule engine twice: once with simple per-expense functions, once with
Ruleobjects +AndRule/OrRule/NotRulecomposites so the same evaluator handles both flat and nested rules. - Also implement the data-driven
Condition(field, operator, value)+ genericevaluate_rulespath end to end, including theOperatorenum with float-coercing numeric comparisons and the missing-field / non-numeric guards. - Group expenses by
trip_idonce per evaluation pass; precompute trip totals and per-expense_typesums and feed them to aggregate rules so the same totals are not recomputed per rule. Return individual and group violations as two separate lists behind a single result object with ato_response()serializer. - Prepare a layered scale answer: rule storage, rule compilation into composite trees on load, field-based indexing of leaf predicates, streaming per-trip evaluation, and violation events emitted to a queue for notifications.
