Project 01 · Streaming fraud detection
Real-Time Fraud Signals Pipeline
Kafka → Spark Structured Streaming → Delta, plus three fraud detectors scored against ground truth: every one of the 16,664 synthetic events carries its true label, so detector quality is measured rather than asserted.
$ make eval
Detector evaluation over 16664 labeled events
┏━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━┳━━━━━━┓
┃ Detector ┃ Ground-truth pattern ┃ Accounts w/ pattern ┃ Accounts flagged ┃ Precision ┃ Recall ┃ F1 ┃
┡━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━╇━━━━━━┩
│ velocity │ velocity_burst │ 226 │ 865 │ 0.26 │ 1.00 │ 0.41 │
│ geo │ impossible_travel │ 240 │ 240 │ 1.00 │ 1.00 │ 1.00 │
│ amount │ amount_outlier │ 200 │ 121 │ 0.97 │ 0.58 │ 0.73 │
└──────────┴──────────────────────┴─────────────────────┴──────────────────┴───────────┴────────┴──────┘
Scored 16664 events in 0.11s (151,143 events/sec, single process) At a glance
At a glance
- Problem
- Fraud ages out in minutes: score transaction streams with rules and statistics, and prove the detectors work against labeled ground truth.
- Approach
- Kafka -> Spark Structured Streaming (2-min watermark, checkpointed) -> Delta, with framework-free Python detectors scored against seeded labels.
- Run it
-
cd project-fraud-signals && make install && make eval - Tests
- 18 passing, 1 skipped · CI on every push
- Docs
- README (opens in new tab) Architecture (opens in new tab)
What exists — honestly
Status key →- Measured
Labeled synthetic producer (3 fraud patterns)
16,664-event eval set, seed 42
- Measured
Velocity, impossible-travel, amount z-score detectors
account-level P/R vs ground truth
- Needs infra
Kafka topic keyed by account_id
docker compose up
- Needs infra
Structured Streaming → Delta (2-min watermark, checkpoint)
make install-streaming
- Implemented
Streamlit operator dashboard
- Stub
dbt staging + marts
needs a packages.yml for dbt_utils
- Planned
Detectors inside the stream (foreachBatch)
- Planned
End-to-end latency p50/p95/p99
~154k/s
events scored by 3 detectors
16,664 events · single process · median of 5
How this was measured
- Method
- make eval, then detect_all() timed in-process by scripts/artifacts/fraud.py
- Date
- 2026-10-05
- Env
- 4 vCPU · Python 3.11.15 · seed 42
1.00 / 1.00
impossible-travel precision / recall
account-level vs seeded ground truth
How this was measured
- Method
- make eval (anomaly.evaluate)
- Date
- 2026-10-05
- Env
- 4 vCPU · Python 3.11.15 · seed 42
0.97 / 0.58
amount z-score precision / recall
117 of 200 outlier accounts caught
How this was measured
- Method
- make eval (anomaly.evaluate)
- Date
- 2026-10-05
- Env
- 4 vCPU · Python 3.11.15 · seed 42
0.26 / 1.00
velocity precision / recall
865 of 1,000 accounts flagged at threshold 5
How this was measured
- Method
- make eval (anomaly.evaluate)
- Date
- 2026-10-05
- Env
- 4 vCPU · Python 3.11.15 · seed 42
Caveat · A fixed 5-events-in-60s rule fires on ordinary traffic at this simulated rate; the sweep peaks at F1 0.79 with threshold 9.
Evidence ledgerRe-measured Oct 2026 from the project's own make targets on synthetic data (seed 42) — full ledger and transcripts.
Event replay
The labeled stream, event by event
A 160-event slice of the real evaluation stream in producer order. Each row shows the ground-truth label next to what the detectors did. About 15% of events carry a fraud label — higher than the producer's 5% per-decision rate because a velocity burst emits five to eight events.
| # | Account | Merchant | Ctry | Amount | Ground truth | Detectors |
|---|---|---|---|---|---|---|
| 559 | A0191 | gas | CA | $574.38 | velocity burst | acct caught |
| 558 | A0191 | subscription | CA | $297.91 | velocity burst | acct caught |
| 557 | A0383 | grocery | AU | $73.56 | normal | — |
| 556 | A0771 | subscription | DE | $74.09 | normal | — |
| 555 | A0203 | atm withdrawal | US | $158.81 | normal | — |
| 554 | A0576 | grocery | ES | $148.67 | normal | — |
| 553 | A0653 | restaurant | BR | $24.18 | normal | — |
| 552 | A0503 | restaurant | CA | $79.70 | normal | — |
| 551 | A0778 | atm withdrawal | JP | $133.71 | normal | — |
Detectors
Three rules, scored against the truth
Precision, recall and F1 are account-level: a pattern counts as caught when the
detector flags any event on an account that truly carries it. The source is the
repo's own detect.py, exported at build time.
detect.velocity_anomaly · catches velocity_burst
Velocity
Flags ≥ 5 events from one account inside any 60-second window.
- Precision
- 0.26
- Recall
- 1.00
- F1
- 0.41
226 of 226 labeled accounts caught · 865 accounts flagged
Catches every seeded burst, but at about 3 events per account per minute a fixed count fires on ordinary traffic too. The fix is calibration — see the threshold explorer.
Source src/anomaly/detect.py
def velocity_anomaly(events: Iterable[dict]) -> list[Anomaly]:
"""Flag accounts with >= VELOCITY_THRESHOLD events in any VELOCITY_WINDOW_SEC window."""
by_account: dict[str, list[dict]] = defaultdict(list)
for e in events:
by_account[e["account_id"]].append(e)
out: list[Anomaly] = []
for account_id, evs in by_account.items():
evs_sorted = sorted(evs, key=lambda e: _parse_ts(e["ts"]))
for i in range(len(evs_sorted)):
window_end = _parse_ts(evs_sorted[i]["ts"])
window_start = window_end.timestamp() - VELOCITY_WINDOW_SEC
count = 0
for j in range(i, -1, -1):
if _parse_ts(evs_sorted[j]["ts"]).timestamp() < window_start:
break
count += 1
if count >= VELOCITY_THRESHOLD:
ev = evs_sorted[i]
out.append(
Anomaly(
event_id=ev["event_id"],
account_id=account_id,
kind="velocity",
score=float(count),
detail=f"{count} events in {VELOCITY_WINDOW_SEC}s",
)
)
break
return out detect.geo_anomaly · catches impossible_travel
Impossible travel
Flags country changes with less than 1 hour between consecutive events.
- Precision
- 1.00
- Recall
- 1.00
- F1
- 1.00
240 of 240 labeled accounts caught · 240 accounts flagged
Perfect on this data — and easy here, because the producer's travel pattern hops country within 90 seconds. Real traffic needs geodistance and VPN handling.
Source src/anomaly/detect.py
def geo_anomaly(events: Iterable[dict]) -> list[Anomaly]:
"""Flag impossible-travel: country change within a window too small for the hop."""
by_account: dict[str, list[dict]] = defaultdict(list)
for e in events:
by_account[e["account_id"]].append(e)
out: list[Anomaly] = []
for account_id, evs in by_account.items():
evs_sorted = sorted(evs, key=lambda e: _parse_ts(e["ts"]))
prev = None
for ev in evs_sorted:
if prev is None:
prev = ev
continue
if ev["country"] != prev["country"]:
delta = (_parse_ts(ev["ts"]) - _parse_ts(prev["ts"])).total_seconds()
if delta < IMPOSSIBLE_TRAVEL_MIN_SEC_PER_HOP:
out.append(
Anomaly(
event_id=ev["event_id"],
account_id=account_id,
kind="geo",
score=round(IMPOSSIBLE_TRAVEL_MIN_SEC_PER_HOP / max(delta, 1), 2),
detail=f"{prev['country']}->{ev['country']} in {int(delta)}s",
)
)
prev = ev
return out detect.amount_zscore_anomaly · catches amount_outlier
Amount z-score
Flags amount ≥ 3.0 standard deviations above the account's mean.
- Precision
- 0.97
- Recall
- 0.58
- F1
- 0.73
117 of 200 labeled accounts caught · 121 accounts flagged
Precise but misses accounts whose few events make the mean and stdev unstable; per-account history (or a robust estimator) would lift recall.
Source src/anomaly/detect.py
def amount_zscore_anomaly(events: Iterable[dict]) -> list[Anomaly]:
"""Flag events whose amount is > ZSCORE_THRESHOLD stddevs above the account mean."""
by_account: dict[str, list[dict]] = defaultdict(list)
for e in events:
by_account[e["account_id"]].append(e)
out: list[Anomaly] = []
for account_id, evs in by_account.items():
amounts = [float(e["amount"]) for e in evs]
if len(amounts) < 4:
continue
mean = statistics.fmean(amounts)
stdev = statistics.pstdev(amounts) or 1.0
for ev in evs:
z = (float(ev["amount"]) - mean) / stdev
if z >= ZSCORE_THRESHOLD:
out.append(
Anomaly(
event_id=ev["event_id"],
account_id=account_id,
kind="amount",
score=round(z, 2),
detail=f"amount={ev['amount']} z={z:.2f}",
)
)
return out Threshold explorer
Calibration, not a new model
The velocity rule's low precision is a threshold problem. Re-running the detector at every threshold on the same labeled set shows where precision and recall cross — and what that costs in accounts flagged.
Precision / recall as the threshold moves
Each point re-runs the detector on the full labeled set — account-level scoring, same as make eval.
| Threshold | Precision | Recall | F1 | Accounts flagged |
|---|---|---|---|---|
| 3 | 0.226 | 1.000 | 0.369 | 999 |
| 4 | 0.231 | 1.000 | 0.375 | 978 |
| 5 | 0.261 | 1.000 | 0.414 | 865 |
| 6 | 0.325 | 1.000 | 0.490 | 696 |
| 7 | 0.449 | 0.987 | 0.617 | 497 |
| 8 | 0.609 | 0.916 | 0.731 | 340 |
| 9 | 0.783 | 0.801 | 0.792 | 231 |
| 10 | 0.898 | 0.659 | 0.760 | 166 |
Architecture
What runs where
Each lane is a path through the system, colour-coded by status. Every node names the file that implements it — click through to the source.
Local evaluation path
Measuredmake eval — runs anywhere, produces every published number
-
Producer
3 labeled fraud patterns, seed 42
generate.py — src/producer/generate.py (opens in new tab) -
JSONL sink
16,664 events
data/eval_events.jsonl
-
Detectors
velocity · geo · amount z-score
detect.py — src/anomaly/detect.py (opens in new tab) -
Evaluator
account-level P/R/F1 vs labels
evaluate.py — src/anomaly/evaluate.py (opens in new tab)
Streaming path
Needs infradocker compose up + make run-stream — Kafka 3.7, Spark 3.5
-
Producer
--sink kafka
generate.py — src/producer/generate.py (opens in new tab) -
Kafka
topic tx-events, keyed by account_id
-
Structured Streaming
2-min watermark · checkpoint · maxOffsetsPerTrigger
consumer.py — src/streaming/consumer.py (opens in new tab) -
Delta table
append; batch ids make replays idempotent
data/delta/tx_events
-
Streamlit Implemented
reads Delta (or JSONL), runs detectors
app.py — src/dashboard/app.py (opens in new tab)
Analytics modeling
Stubdbt models exist; the build needs a packages.yml for dbt_utils
-
stg_transactions
staging — dbt_fraud/models/staging (opens in new tab) -
fct_transactions
per-account amount z-score
marts — dbt_fraud/models/marts (opens in new tab) -
dim_account
marts — dbt_fraud/models/marts (opens in new tab)
Engineering narrative
Problem, judgment calls, and results
Problem
Fraud teams in telecom and fintech need to react in seconds, not hours. Batch ETL surfaces a compromised account long after the money has moved. This project is the streaming half of that problem: a producer publishes labeled transaction events, Spark Structured Streaming lands them in Delta with a watermark and checkpoint, and three detectors — velocity, impossible travel, and amount outliers — score the stream. Because every synthetic event carries its ground-truth label, detector quality is something the repo measures rather than asserts.
Judgment calls
Why streaming over batch? Fraud ages out fast. An anomaly that lands two
hours late is informational, not operational. The producer keys events by
account_id, which preserves per-account ordering in Kafka even when
consumers scale out.
Why Spark Structured Streaming over Flink? Flink has lower tail latency and richer state primitives. I picked Spark because the lakehouse is already Delta, so ingestion and analytics share one engine, and Structured Streaming’s batch-equivalent model matches how analytics teams already reason in SQL. For sub-100 ms decisions, Flink would be the right call.
Exactly-once, precisely. The consumer appends to Delta with a checkpoint. Delta’s streaming sink records each micro-batch id in its transaction log, so a batch replayed after a crash is recognised and skipped — that is what makes the pipeline exactly-once across the checkpoint boundary. The 2-minute watermark bounds how much late-event state Spark has to keep.
Detectors stay framework-free. The three detectors are plain Python
functions over event dicts, so they unit-test without a cluster and run the
same way in the evaluator, the Streamlit dashboard, or a future streaming
foreachBatch. Today they run in batch over the evaluation set; wiring them
into the streaming query is the next step, not something the demo claims.
Measured results
make eval generates 16,664 labeled events (seed 42,
1,000 accounts) and scores each detector at the
account level. Impossible travel lands at 1.00 / 1.00 precision / recall,
and the amount z-score detector at 0.97 / 0.58. The fixed velocity rule
is the instructive one: it catches every seeded burst but flags 865 of
1,000 accounts, for 0.26 precision. At
this simulated rate an ordinary account produces about three events a minute, so
“five in sixty seconds” fires on normal traffic. The threshold explorer on this page shows
the fix is calibration rather than a new model: threshold 9 reaches
0.78 precision at 0.80 recall. The detectors
score ~154k events per second in a single
process.
What I would do differently in production
- Replace the fixed velocity threshold with a per-account baseline, so precision holds up for naturally busy accounts.
- Swap per-account z-scores computed over the whole window for an online estimator (Welford or t-digest) to bound memory.
- Run the detectors inside the streaming query (
foreachBatch) and write scored events to their own Delta table. - Add a schema registry so producer/consumer compatibility is enforced at deploy time.
- Move the operator dashboard off Streamlit for anything customer-facing.
Stack
What it uses, and why
- Apache Kafka
- Topic keyed by account_id so per-account ordering survives consumer scale-out.
- Spark Structured Streaming
- Batch-equivalent semantics; one engine with the Delta lakehouse. Flink would win below ~100 ms.
- Delta Lake
- Streaming sink records batch ids in its log, so replays after a crash are idempotent.
- Python detectors
- Framework-free functions: unit-testable without a cluster, reusable in a stream or a batch job.
- Faker + seeded RNG
- Reproducible synthetic accounts and labeled fraud patterns (seed 42).
- Streamlit
- Operator dashboard over Delta (or JSONL) — fine for ops, not for customer-facing UI.