Skip to main content

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

ComponentDescriptionStatus
Decision APIFastAPI endpoint for fraud decisionsComplete
Feature StoreRedis-based velocity countersComplete
Detection EngineCard testing, velocity, geo, bot detectionComplete
Risk ScoringRule-based criminal + friendly fraud scoringComplete
Policy EngineYAML-configurable rules and thresholdsComplete
Evidence VaultPostgreSQL-based immutable storageComplete
MetricsPrometheus metrics for monitoringComplete
TestsUnit and integration testsComplete

Infrastructure

ServicePurposePortURL
RedisVelocity counters, entity profiles6379localhost:6379
PostgreSQLEvidence storage, chargebacks5432localhost:5432
PrometheusMetrics collection9090http://localhost:9090
Fraud APIDecision endpoint8000http://localhost:8000
Demo DashboardVisual testing interface8501http://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:

  1. Checks idempotency - Returns cached result if already processed
  2. Computes features - Retrieves velocity counters and entity profiles
  3. Runs detection - All detectors run in parallel
  4. Calculates scores - Combines detector signals into risk scores
  5. Evaluates policy - Applies rules and thresholds
  6. Returns decision - ALLOW, FRICTION, REVIEW, or BLOCK
  7. Captures evidence - Stores immutable record for disputes
  8. 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 TypeBlockReviewFriction
Overall Risk90%+70%+50%+
Criminal85%+65%+45%+
Friendly95%+60%+40%+

Built-in Rules

RuleConditionAction
Emulator BlockDevice is emulatorBLOCK
Tor BlockIP is Tor exitBLOCK
Datacenter ReviewIP is datacenterREVIEW
High Value New AccountAmount >= $1000 + new accountFRICTION (3DS)
High Value New CardAmount >= $500 + new cardFRICTION (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)

EndpointMethodDescription
/policyGETGet current active policy with full configuration
/policy/versionsGETList all policy versions (most recent first)
/policy/versions/{version}GETGet specific policy version details
/policy/thresholdsPUTUpdate score thresholds (validates friction < review < block)
/policy/rulesPOSTAdd a new policy rule
/policy/rules/{rule_id}PUTUpdate an existing rule
/policy/rules/{rule_id}DELETEDelete a rule
/policy/lists/{list_type}POSTAdd value to blocklist/allowlist
/policy/lists/{list_type}/{value}DELETERemove value from blocklist/allowlist
/policy/rollback/{version}POSTRollback to a previous version (creates new version)
/policy/diff/{v1}/{v2}GETCompare two policy versions

Redis Key Patterns

All keys use fraud: prefix to avoid conflicts.

PatternPurposeTTL
fraud:card:{token}:attemptsCard transaction attempts24h
fraud:card:{token}:declinesCard declines24h
fraud:card:{token}:accountsDistinct subscriber accounts24h
fraud:device:{id}:cardsCards seen on device24h
fraud:ip:{addr}:cardsCards from IP24h
fraud:profile:card:{token}Card profile hash30d
fraud:profile:device:{id}Device profile hash30d
fraud:idempotency:{key}Cached decision24h

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

  1. Generate synthetic test events to validate detection
  2. Monitor metrics in Prometheus
  3. Tune thresholds based on false positive rates
  4. Add more entities to blocklists as needed
  5. 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