Transaction Policy Engine Design and Implementation
Data Structure DesignModel answerLast updated
Build a configurable rule engine that evaluates financial transactions against spending policies and returns approval decisions in real-time.
Problem
You need to build a system component that checks whether financial transactions comply with configurable spending policies. The engine must evaluate each transaction against a collection of policies and decide whether to approve or reject it.
Context
Your component receives transaction objects containing:
transaction_id: unique identifieruser_id: who initiated the transactionamount: monetary valuecurrency: e.g., USD, EURcategory: type of purchase (Travel, Software, etc.)merchant_name: where the purchase is made
Policies consist of conditions like "amount exceeds 500" or "category equals Travel", along with an action (permit or block).
Your Task
Design the data structures and logic for this engine. Specifically:
- Create a
Ruleclass that represents a single policy with its conditions and action - Implement
evaluate_transaction(transaction, rules)that returns either"APPROVED"or"DENIED" - Handle conflicts: when multiple rules match, define clear precedence rules
- Enable dynamic updates: policies should be changeable without code deployment
Design Constraints
- Evaluation latency must stay under 100ms
- Rules should be serializable (storable in databases or caches)
- Never use
eval()or execute arbitrary code from rule definitions - Missing transaction fields should not crash the evaluator
Example
txn = {"amount": 600, "category": "Travel", "user_id": "u123"}
policies = [
Rule("amount < 500", action="DENY", priority=0),
Rule("category == Travel", action="DENY", priority=0)
]
result = evaluate_transaction(txn, policies) # Returns "DENIED"
What to Cover
Explain your design choices for:
- How you represent conditions and operators
- How you resolve conflicts between overlapping rules
- How you ensure the system is fast enough for production
- What edge cases you handle
Hints
Hint 1
Think about rules as data, not code—how would you serialize a condition into JSON and parse it back safely?
Hint 2
When two rules match the same transaction but disagree, what tie-breaking strategy makes sense for financial controls?
Hint 3
Consider pre-processing rules once when they load, rather than re-sorting on every transaction evaluation
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution Approach
The core insight is to treat policies as structured data rather than executable code. Each rule is an object with three components:
- Conditions: a list of predicates (field, operator, value) that must all be true
- Action: either ALLOW or DENY
- Priority: a number for conflict resolution
This design enables storage in databases, runtime updates, and safe evaluation without code injection risks.
Data Model
Condition Class
Each condition represents a single comparison like amount > 500. Store it as a tuple (field_name, operator, expected_value). Map operator symbols to Python's built-in comparison functions:
OPERATORS = {
"==": operator.eq,
"!=": operator.ne,
"<": operator.lt,
"<=": operator.le,
">": operator.gt,
">=": operator.ge,
}
Parse condition strings with a regex that extracts the field, operator, and value. Convert the value to the appropriate type (int, float, or string) by trying numeric casts and falling back to strings. Handle quoted strings by stripping quotes.
When evaluating, look up the field in the transaction dictionary. If the field is missing or the comparison raises a type error, the condition returns False rather than crashing.
Rule Class
A rule bundles multiple conditions (AND logic), an action, and a priority. Provide methods to:
matches(txn): returns True if all conditions matchto_dict()andfrom_dict(): serialize to/from JSON for database storage
Conflict Resolution Strategy
When multiple rules match the same transaction, apply these precedence rules in order:
- Higher priority wins: sort rules by priority descending
- DENY beats ALLOW: at the same priority, evaluate DENY rules first
- First match decides: stop at the first matching rule
This implements a "deny-overrides" policy, which is appropriate for financial controls where safety matters. An administrator can create a high-priority ALLOW rule to whitelist specific cases that would otherwise be blocked by a lower-priority DENY.
If no rules match, return a configurable default (typically "APPROVED" since rules describe violations).
Implementation
import operator
import re
from dataclasses import dataclass
DEFAULT_DECISION = "APPROVED"
OPERATORS = {
"==": operator.eq,
"!=": operator.ne,
"<": operator.lt,
"<=": operator.le,
">": operator.gt,
">=": operator.ge,
}
CONDITION_PATTERN = re.compile(r"^\s*(\w+)\s*(==|!=|<=|>=|<|>)\s*(.+?)\s*$")
def parse_value(raw: str):
"""Convert string to int, float, or unquoted string."""
raw = raw.strip()
# Remove quotes if present
if len(raw) >= 2 and raw[0] == raw[-1] and raw[0] in ("'", '"'):
return raw[1:-1]
# Try numeric conversion
for cast_fn in (int, float):
try:
return cast_fn(raw)
except ValueError:
continue
return raw
@dataclass(frozen=True)
class Condition:
field: str
operator: str
value: object
@classmethod
def parse(cls, expression: str):
match = CONDITION_PATTERN.match(expression)
if not match:
raise ValueError(f"Invalid condition: {expression}")
field, op, raw_value = match.groups()
return cls(field, op, parse_value(raw_value))
def matches(self, transaction: dict) -> bool:
if self.field not in transaction:
return False
try:
op_fn = OPERATORS[self.operator]
return op_fn(transaction[self.field], self.value)
except (TypeError, KeyError):
return False
class Rule:
def __init__(self, conditions, action: str = "ALLOW", priority: int = 0):
# Allow single condition as string or list of conditions
if isinstance(conditions, str):
conditions = [conditions]
self.conditions = [
Condition.parse(c) if isinstance(c, str) else c
for c in conditions
]
self.action = action.upper()
self.priority = priority
def matches(self, transaction: dict) -> bool:
return all(cond.matches(transaction) for cond in self.conditions)
def to_dict(self):
return {
"action": self.action,
"priority": self.priority,
"conditions": [
{"field": c.field, "operator": c.operator, "value": c.value}
for c in self.conditions
],
}
@classmethod
def from_dict(cls, data: dict):
conditions = [
Condition(c["field"], c["operator"], c["value"])
for c in data["conditions"]
]
return cls(conditions, data.get("action", "ALLOW"), data.get("priority", 0))
def evaluate_transaction(transaction: dict, rules: list[Rule]) -> str:
# Sort: highest priority first, then DENY before ALLOW
sorted_rules = sorted(
rules,
key=lambda r: (-r.priority, r.action != "DENY")
)
for rule in sorted_rules:
if rule.matches(transaction):
return "DENIED" if rule.action == "DENY" else "APPROVED"
return DEFAULT_DECISION
Complexity Analysis
- Time: O(R log R + C) where R is the number of rules and C is the total conditions across all rules. The sort happens once per rule set load, so per-transaction evaluation is O(C) with early exit on first match. For thousands of rules, this completes in microseconds, well under the 100ms requirement.
- Space: O(R + C) to store the parsed rules and conditions.
Edge Cases Handled
- Missing fields: If a transaction lacks a field referenced in a condition, that condition evaluates to False
- Type mismatches: Comparing incompatible types (string vs number) returns False instead of throwing
- Empty rule list: Returns the default decision
- Catch-all rules: A rule with no conditions matches every transaction (useful as a low-priority default)
- Equal priorities: DENY action takes precedence over ALLOW
Production Considerations
Dynamic updates: Load rules from a database into an in-memory cache. When rules change, rebuild the sorted list atomically and swap it in. This keeps evaluation off the database hot path.
Scaling to many rules: Pre-sort rules once when loading. For 10,000+ rules, consider indexing by field (e.g., group all category rules together) to avoid evaluating irrelevant conditions.
Currency handling: Normalize all amounts to a base currency before evaluation, or include currency as a condition field.
Decimal precision: Use Decimal type for money rather than floating-point to avoid rounding errors.
Audit trail: Log which rule caused each decision for compliance and debugging.
Common Mistakes
- Using
eval()to execute rule strings (security vulnerability) - Crashing on malformed transactions instead of gracefully handling missing data
- Ambiguous conflict resolution that makes rule behavior unpredictable
- Sorting rules on every evaluation instead of once at load time
- Returning arbitrary exceptions instead of APPROVED/DENIED decisions