This repository is a runnable reference implementation of a real-time fraud monitoring pipeline for financial transactions.
It demonstrates:
- Streaming transaction ingestion (simulated stream)
- Online behavioral feature computation
- Millisecond-style model inference (lightweight ensemble)
- Action decisioning:
APPROVE,STEP_UP,BLOCK - HTTP scoring via FastAPI
- Streaming adapter for Kafka consumer/producer
Conceptual flow:
[Live Transaction] -> [Kafka Stream] -> [Feature Store] -> [ML Model Inference] -> [Action: Approve/Block]
Reference implementation mapping:
simulator= streaming source (Kafka substitute for local demo)FeatureEngineer= online feature store + stream computationModelEnsemble= model inference layerFraudMonitoringPipeline= decision engine
The pipeline computes these features per transaction:
-
Velocity metrics
tx_count_5m: number of transactions for a card in the last 5 minutesamount_sum_5m: total amount in the last 5 minutes
-
Geographic impossibility
- Computes Haversine distance between consecutive transactions for the same card
- Derives required speed in km/h
- Flags
impossible_travel = 1when speed exceeds threshold (900 km/h)
-
Amount deviation
- Rolling 30-day card spending baseline
amount_zscore_30damount_ratio_to_avg_30d
The reference ModelEnsemble includes fast approximations of:
- Isolation Forest-like anomaly score
- XGBoost-like supervised score
- Autoencoder-like reconstruction error score
- Graph-risk proxy score
Final risk is a weighted aggregate in [0, 1] and mapped to actions by thresholds:
< 0.35->APPROVE0.35 to <0.70->STEP_UP>= 0.70->BLOCK
src/realmonitoring/types.py— transaction, feature, score, and decision data modelssrc/realmonitoring/features.py— streaming feature computationsrc/realmonitoring/models.py— ensemble scoring and risk aggregationsrc/realmonitoring/pipeline.py— end-to-end process + action decisionsrc/realmonitoring/contracts.py— shared API contractssrc/realmonitoring/transforms.py— shared payload/domain transformerssrc/realmonitoring/simulator.py— deterministic transaction stream generatorsrc/realmonitoring/main.py— tiny runner for local demosrc/realmonitoring/api.py— FastAPI app with/healthand/scoresrc/realmonitoring/kafka_adapter.py— Kafka adapter (consume transactions, publish decisions)src/realmonitoring/kafka_worker.py— CLI entrypoint for Kafka looptests/test_pipeline.py— unit tests (happy path + anomaly edge cases)tests/test_api.py— API endpoint teststests/test_kafka_adapter.py— Kafka adapter unit testsARCHITECTURE.md— module boundaries and extension pointsCONTRIBUTING.md— development and contribution workflow
This codebase separates concerns by layer:
- Domain layer:
types.py - Core logic:
features.py,models.py,pipeline.py - Transport contracts:
contracts.py - Shared adapters/mappers:
transforms.py - Delivery channels:
api.py,kafka_adapter.py
This structure lets HTTP and Kafka paths reuse the same fraud scoring core.
- Python 3.10+
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txtPYTHONPATH=src python -m realmonitoring.mainpytestPYTHONPATH=src uvicorn realmonitoring.api:app --host 0.0.0.0 --port 8000curl -X POST http://127.0.0.1:8000/score \
-H "Content-Type: application/json" \
-d '{
"transaction_id": "tx_api_001",
"card_id": "card_abc",
"user_id": "user_abc",
"amount": 129.95,
"merchant_id": "m_101",
"merchant_category": "grocery",
"latitude": 39.9612,
"longitude": -82.9988,
"timestamp": "2026-07-08T12:00:00"
}'By default the adapter consumes from transactions.raw and produces to transactions.decision.
PYTHONPATH=src python -m realmonitoring.kafka_workerIf Kafka isn't running, you can still unit-test adapter logic with tests/test_kafka_adapter.py.
Initialize and push to your personal Git account:
git init
git add .
git commit -m "feat: modular real-time fraud monitoring reference project"
git branch -M main
git remote add origin <your-repo-url>
git push -u origin mainYou should see:
- Early low-risk transactions mostly
APPROVE - Later burst/high-amount/impossible-travel events becoming
STEP_UPorBLOCK - A summary with action counts and average latency
-
ModuleNotFoundError: realmonitoring- Ensure you run with
PYTHONPATH=srcor install package in editable mode.
- Ensure you run with
-
No suspicious events in output
- The simulator is deterministic by default, but scores may vary if you change thresholds or generator logic.
- Replace simulator with Kafka consumer/producer
- Add Redis/Feast-backed online feature store
- Serve real models via FastAPI or gRPC
- Add drift monitoring and champion/challenger model routing