Sprint-1 Implementation Guide
What Was Built: A complete, working fraud detection MVP ready for local development and testing.
Overview
Sprint-1 delivers a functional fraud detection system with:
- Real-time decision API
- Rule-based scoring (ML deferred to Phase 2)
- Velocity-based detection
- Configurable policy engine
- Evidence capture
- Prometheus metrics
The implementation follows a smaller scope approach: FastAPI + Redis + PostgreSQL, without Kafka/Flink complexity for the MVP.
What's Included
Core Components
| Component | Description | Status |
|---|---|---|
| Decision API | FastAPI endpoint for fraud decisions | Complete |
| Feature Store | Redis-based velocity counters | Complete |
| Detection Engine | Card testing, velocity, geo, bot detection | Complete |
| Risk Scoring | Rule-based criminal + friendly fraud scoring | Complete |
| Policy Engine | YAML-configurable rules and thresholds | Complete |
| Evidence Vault | PostgreSQL-based immutable storage | Complete |
| Metrics | Prometheus metrics for monitoring | Complete |
| Tests | Unit and integration tests | Complete |
Infrastructure
| Service | Purpose | Port | URL |
|---|---|---|---|
| Redis | Velocity counters, entity profiles | 6379 | localhost:6379 |
| PostgreSQL | Evidence storage, chargebacks | 5432 | localhost:5432 |
| Prometheus | Metrics collection | 9090 | http://localhost:9090 |
| Fraud API | Decision endpoint | 8000 | http://localhost:8000 |
| Demo Dashboard | Visual testing interface | 8501 | http://localhost:8501 |
Project Structure
FraudDetection/
├── docker-compose.yml # Local infrastructure
├── requirements.txt # Python dependencies
├── dashboard.py # Streamlit demo dashboard
├── .env.example # Environment template
├── config/
│ ├── policy.yaml # Policy configuration
│ └── prometheus.yml # Metrics config
├── scripts/
│ └── init_db.sql # Database schema
├── src/
│ ├── api/ # FastAPI application
│ ├── config/ # Settings management
│ ├── schemas/ # Data models
│ ├── features/ # Velocity counters
│ ├── detection/ # Fraud detectors
│ ├── scoring/ # Risk scoring
│ ├── policy/ # Policy engine
│ ├── evidence/ # Evidence capture
│ └── metrics/ # Prometheus metrics
└── tests/ # Test suite
Fraud Detection Scenarios
Criminal Fraud Detection
The system detects the following criminal fraud patterns:
Card Testing Attacks
- Rapid small transactions on same card
- High decline rates (80%+ in 10 minutes)
- Multiple cards from single device
- Sequential BIN probing
Example trigger: A card with 5+ attempts in 10 minutes with 80%+ decline rate.
Velocity Attacks
- Card used more than 10 times per hour
- Device used with 5+ different cards in 24 hours
- IP address used with 10+ cards in 1 hour
- User spending exceeds normal limits
Example trigger: A device that's seen 5+ distinct cards in a day.
Geographic Anomalies
- Transaction from different country than card
- Transaction from known high-risk countries
- Transaction from datacenter IP (non-residential)
- Transaction from Tor exit node
Example trigger: Card issued in US, transaction from IP in Nigeria.
Bot/Automation Detection
- Transaction from emulated device
- Transaction from rooted/jailbroken device
- Transaction from cloud/datacenter IP
- Suspicious device fingerprint patterns
Example trigger: Device fingerprint indicates Android emulator.
Friendly Fraud Detection
The system also scores friendly fraud risk:
- Users with high historical chargeback rates (3%+)
- Users with 2+ chargebacks in 90 days
- High refund frequency (5+ in 90 days)
- Guest checkout for high-value transactions
Decision Flow
When a transaction arrives, the system:
- Checks idempotency - Returns cached result if already processed
- Computes features - Retrieves velocity counters and entity profiles
- Runs detection - All detectors run in parallel
- Calculates scores - Combines detector signals into risk scores
- Evaluates policy - Applies rules and thresholds
- Returns decision - ALLOW, FRICTION, REVIEW, or BLOCK
- Captures evidence - Stores immutable record for disputes
- Updates profiles - Refreshes entity velocity counters
Policy Configuration
The policy is configured via YAML and can be hot-reloaded without restarting.
Policy Settings GUI (v1.1)
A visual interface for managing policies is available in the dashboard's "Policy Settings" tab:
- Thresholds: Adjust friction/review/block thresholds with validation
- Rules: Add, edit, or delete detection rules
- Blocklists: Manage blocked cards, devices, IPs, and users
- Allowlists: Manage trusted cards, users, and services
- Version History: View change history and rollback if needed
All changes are tracked with semantic versioning (MAJOR.MINOR.PATCH) and linked to transaction evidence for audit purposes.
Score Thresholds
| Score Type | Block | Review | Friction |
|---|---|---|---|
| Overall Risk | 90%+ | 70%+ | 50%+ |
| Criminal | 85%+ | 65%+ | 45%+ |
| Friendly | 95%+ | 60%+ | 40%+ |
Built-in Rules
| Rule | Condition | Action |
|---|---|---|
| Emulator Block | Device is emulator | BLOCK |
| Tor Block | IP is Tor exit | BLOCK |
| Datacenter Review | IP is datacenter | REVIEW |
| High Value New Account | Amount >= $1000 + new account | FRICTION (3DS) |
| High Value New Card | Amount >= $500 + new card | FRICTION (3DS) |
Lists
- Blocklists: Cards, devices, IPs, or users that should always be blocked
- Allowlists: Cards, users, or services that skip fraud checks
Evidence Capture
Every decision is captured with:
- Transaction details (amount, service, event_subtype, timestamp)
- Entity identifiers (card token, device ID, IP, user)
- All computed features (velocity counters, entity features)
- Risk scores and confidence
- Decision and all triggered reasons
- Device fingerprint and geo data
- Verification results (AVS, CVV, 3DS)
- Policy version ID (v1.1) - Links to exact policy version used for decision
Evidence is immutable and linked by transaction ID for dispute representment. The policy version linkage enables full traceability of which rules and thresholds were active when a decision was made.
Metrics Exposed
Latency Metrics
- End-to-end processing time (target: under 200ms)
- Feature computation time (target: under 50ms)
- Scoring time (target: under 25ms)
- Policy evaluation time
Decision Metrics
- Total decisions by type (ALLOW, FRICTION, REVIEW, BLOCK)
- Approval rate (rolling)
- Block rate (rolling)
Scoring Metrics
- Risk score distribution
- Criminal score distribution
- Friendly fraud score distribution
System Metrics
- Redis operation latency
- PostgreSQL operation latency
- Cache hit/miss rates
- Error counts by type
Getting Started
Prerequisites
- Python 3.11+
- Docker and Docker Compose
- Redis (or use Docker)
- PostgreSQL (or use Docker)
Step 1: Start Infrastructure
cd /Users/omega/Projects/FraudDetection
docker-compose up -d
This starts:
- Redis on port 6379
- PostgreSQL on port 5432
- Prometheus on port 9090
Step 2: Set Up Environment
cp .env.example .env
# Edit .env if needed
Step 3: Install Dependencies
python -m venv venv
source venv/bin/activate
pip install -r requirements.txt
Step 4: Run the API
uvicorn src.api.main:app --reload --port 8000
Step 5: Run the Dashboard
streamlit run dashboard.py --server.port 8501
Open http://localhost:8501 for the visual demo interface.
Step 6: Test a Request
curl -X POST http://localhost:8000/decide \
-H "Content-Type: application/json" \
-d '{
"transaction_id": "txn_test_001",
"idempotency_key": "idem_test_001",
"amount_cents": 5000,
"card_token": "card_abc123",
"service_id": "mobile_prepaid_001",
"service_type": "mobile",
"event_subtype": "sim_activation"
}'
Step 7: Run Tests
pytest tests/ -v
API Reference
POST /decide
Make a fraud decision for a transaction.
Request body: PaymentEvent (see schema documentation)
Response:
{
"transaction_id": "txn_123",
"decision": "ALLOW",
"scores": {
"risk_score": 0.15,
"criminal_score": 0.10,
"friendly_fraud_score": 0.05
},
"reasons": [],
"processing_time_ms": 45.2
}
GET /health
Check service health and component status.
GET /policy/version
Get current policy version and hash.
POST /policy/reload
Hot-reload policy from configuration file.
Policy Management Endpoints (v1.1)
| Endpoint | Method | Description |
|---|---|---|
/policy | GET | Get current active policy with full configuration |
/policy/versions | GET | List all policy versions (most recent first) |
/policy/versions/{version} | GET | Get specific policy version details |
/policy/thresholds | PUT | Update score thresholds (validates friction < review < block) |
/policy/rules | POST | Add a new policy rule |
/policy/rules/{rule_id} | PUT | Update an existing rule |
/policy/rules/{rule_id} | DELETE | Delete a rule |
/policy/lists/{list_type} | POST | Add value to blocklist/allowlist |
/policy/lists/{list_type}/{value} | DELETE | Remove value from blocklist/allowlist |
/policy/rollback/{version} | POST | Rollback to a previous version (creates new version) |
/policy/diff/{v1}/{v2} | GET | Compare two policy versions |
Redis Key Patterns
All keys use fraud: prefix to avoid conflicts.
| Pattern | Purpose | TTL |
|---|---|---|
fraud:card:{token}:attempts | Card transaction attempts | 24h |
fraud:card:{token}:declines | Card declines | 24h |
fraud:card:{token}:accounts | Distinct subscriber accounts | 24h |
fraud:device:{id}:cards | Cards seen on device | 24h |
fraud:ip:{addr}:cards | Cards from IP | 24h |
fraud:profile:card:{token} | Card profile hash | 30d |
fraud:profile:device:{id} | Device profile hash | 30d |
fraud:idempotency:{key} | Cached decision | 24h |
Database Tables
transaction_evidence
Immutable record of every decision:
- Transaction identifiers and amounts
- Entity identifiers (tokenized)
- Scores and decision
- Features snapshot
- Device and geo data
chargebacks
Links chargebacks to original transactions:
- Transaction linkage
- Reason codes and descriptions
- Fraud type classification
- Representment tracking
policy_versions (v1.1)
Immutable version history with semantic versioning:
- Version string (e.g., "1.0.0", "1.1.0", "1.0.1")
- Full policy content as JSON
- SHA256 hash for integrity verification
- Change type (threshold, rule_add, rule_delete, rollback, etc.)
- Change summary and author
- Active version flag
- Links to previous version
policy_audit_log (legacy)
Tracks all policy changes:
- Version and hash
- Who changed it and when
- Full policy content
What's Not Included (Phase 2)
- Machine learning models (using rule-based scoring)
- Kafka streaming (using direct API calls)
- Flink stream processing (using Redis directly)
- Automated representment
- Economic optimization UI
- Champion/challenger A/B testing
- IRSF, ATO, subscription fraud detection
- Telco/MSP signal integration
Troubleshooting
Redis Connection Failed
Check that Redis is running:
docker-compose ps
redis-cli ping
PostgreSQL Connection Failed
Check that PostgreSQL is running and database exists:
docker-compose ps
psql -h localhost -U fraud_user -d fraud_detection
Slow Responses
Check latency metrics at http://localhost:9100/metrics. If feature computation is slow, verify Redis connection. If policy evaluation is slow, simplify rules.
Policy Reload Failed
Check YAML syntax in config/policy.yaml. The API will log validation errors.
Next Steps
- Generate synthetic test events to validate detection
- Monitor metrics in Prometheus
- Tune thresholds based on false positive rates
- Add more entities to blocklists as needed
- Prepare for Phase 2 ML integration
Document Version: 1.1 Implementation Date: January 3, 2026 Last Updated: January 3, 2026 - Added policy versioning and GUI documentation