How to Make Fraud Detection Logic Testable in Python
For Backend engineers building fraud and risk systems · Based on ArjanCodes Functional Core Python Design
// TL;DR
Fraud and risk engineers can use ArjanCodes Functional Core Python Design to separate their scoring rules from infrastructure. Extract each risk rule into a pure function, model the flow as raw signals → features → risk assessment → decision using frozen dataclasses, and keep all database lookups, model calls, and alert dispatch in a thin imperative shell. The result: risk logic you can test with plain values and no mocks, that stays stable as data sources and ML models change. Use it whenever a fraud function mixes feature fetching, scoring, decisioning, and persistence in one hard-to-test place.
Why is fraud detection code so hard to test?
Fraud logic tends to grow into one giant function that fetches account history from a database, pulls a model prediction, applies a dozen rules, makes a block-or-allow decision, writes the result, and fires an alert — all in one place. Every new rule makes it longer, and every test requires mocking databases, model servers, and notification systems. The decision-making — the part that actually matters — is buried under infrastructure.
The Functional Core, Imperative Shell pattern fixes this by separating what you decide from where data comes from and goes.
How do you pull risk rules into a pure functional core?
Start by auditing the function. List everything it does and tag each item as a calculation, a state mutation, external I/O, or a decision. Your risk rules — velocity checks, amount thresholds, geolocation mismatches, score weighting — are calculations. Extract each into a pure function that takes only what it needs as arguments and returns a value:
```python
def velocity_score(recent_tx_count: int, window_minutes: int) -> float: ...
def amount_risk(amount: float, account_avg: float) -> float: ...
```
Ask the core test question: called twice with the same inputs, does it always return the same output and touch nothing external? If yes, it's pure. Note that the model prediction is passed in, never fetched inside — that's the explicit dependencies principle keeping your core ignorant of the model server.
How do you model the fraud pipeline with immutable stages?
Name the stages data actually passes through: `RawTransaction → RiskFeatures → RiskAssessment → Decision`. Create a frozen dataclass for each. Use tuples instead of lists for any collections inside them so nothing gets mutated downstream.
Each transformation is a pure function taking the previous stage's immutable output plus any needed inputs — like the model score — and returning the next stage. No database calls, no logging, no alerting inside these functions. An orchestrator calls them in sequence using clear intermediate variables:
```python
features = extract_features(raw)
assessment = assess_risk(features, model_score)
decision = decide(assessment, policy)
```
Where does the database and model loading go?
Everything external lives in the imperative shell — your `FraudService`. It fetches account history, calls the model server to get a prediction, loads policy config, calls the orchestrator, then persists the decision and dispatches any alert. The shell is deliberately imperative. The core never knows it exists.
The payoff is testability: because the core receives already-fetched data and model scores as arguments, you test every rule and the whole decision with plain values — no mocking a database or model endpoint. If you ever find yourself needing to mock something to test a core function, a dependency has leaked and must be moved to the shell.
What does this change day to day?
Adding a new rule means writing one more pure function and wiring it into a stage, not surgery on a 400-line method. Swapping your feature store or model host only touches the shell. Reviewers can read and trust the risk logic in isolation. And when an auditor asks why a transaction was blocked, your immutable `RiskAssessment` and `Decision` snapshots record exactly what was computed at each step.
Next step: Pick your most-feared fraud function, run the audit to tag each line's concern, and extract the first pure rule today — then grow the pipeline one stage at a time.
// FREQUENTLY ASKED QUESTIONS
How do I test a risk rule that depends on a model score?
Pass the model score into the rule as an argument. The imperative shell calls the model server and hands the prediction to the pure core, so you can test the rule by calling it directly with any score value. No model endpoint or mock is required, and you can easily cover edge cases across the full score range.
Where should fraud alerts and database writes happen?
In the imperative shell, never in the core. The core returns an immutable Decision describing what should happen; the shell reads that result and performs the side effects — persisting the decision and dispatching alerts. This keeps your scoring and decisioning logic pure and fully testable with simple values.
How do I keep an audit trail with immutable data?
Each pipeline stage produces a frozen dataclass snapshot — RiskFeatures, RiskAssessment, Decision — that records exactly what was computed at that point. Because these are immutable, they can't be altered downstream, giving you a reliable, reproducible trail of why a transaction was blocked or allowed that you can log from the shell.