Skip to main content
Data Systems & Search Engines

Design Real-Time Fraud Detection & Risk Scoring Engine

Staff / Principal

Complete FAANG-level system design blueprint for Fraud Detection & Risk Scoring Engine. Covers capacity estimation, high-level architecture.

Production Scale: 10k TPS • 2,000 Risk Features/Transaction

Design Real-Time Fraud Detection & Risk Scoring Engine: Request Topology

5 Stages · 4 Sizing Benchmarks

Request traversal order for Design Real-Time Fraud Detection & Risk Scoring Engine (Data Systems & Search Engines) under target workload 10k TPS • 2,000 Risk Features/Transaction:

Stage 1

Risk Scoring Gateway & Deadline Enforcer

Stage 2

Flink Streaming Feature Aggregator

Stage 3

Low-Latency Online Feature Store (Redis / DynamoDB)

Stage 4

ONNX Model Inference & Policy Engine

Functional Requirements

  • •Score incoming payment and login events in real time using 2,000 behavioral, device, and velocity features
  • •Combine ML risk probabilities with deterministic compliance and blocklist policy rules to output Allow, Challenge, or Block
  • •Log exact online feature vectors alongside final decisions for model retraining and chargeback audits

Non-Functional Requirements

  • •Sub-50ms end-to-end p99 fraud decision latency at 10,000 TPS
  • •Zero training-serving skew between streaming online features and offline batch training sets
  • •Fail-safe graceful degradation within a 12ms enrichment deadline so partial feature outages do not block legitimate payments

Capacity & Scale Estimation (Back-of-the-Envelope Math)

Open Live Calculator
Production Scale Target10k TPS
Peak Throughput2,000 Risk Features/Transaction
Read-to-Write Ratio10 : 1
Availability Target99.999% SLA (Five 9s)

Estimate Custom QPS & Storage Growth Live

Calculate bandwidth ingress, 80/20 RAM cache sizing, and multi-year storage growth using our interactive developer utility.

Launch Calculator →

System Topology & Core Architectural Components

[Payment / Auth Ingress]
           |
           v (Kafka / Flink Streaming)
[Feature Store (Feast / Redis Online Store)] <---> [Inference Worker Pool]
           |                                              |
           v                                              v
[ScyllaDB Offline Store] <--------------------- [Rules Engine + XGBoost / GNN]
                                                          |
                                                          v
                                               [Risk Score / Decision Webhook]
                                               (APPROVE / CHALLENGE / REJECT)

1Risk Scoring Gateway & Deadline Enforcer

Orchestrates parallel feature lookups and rule evaluations within a hard 50ms SLA, falling back to cached defaults if secondary shards exceed 12ms.

2Flink Streaming Feature Aggregator

Maintains sliding time-window counters (card velocity, IP-to-device fan-out, chargeback ratios) continuously from Kafka transaction streams.

3Low-Latency Online Feature Store (Redis / DynamoDB)

Serves pre-computed 2,000-dimensional entity feature vectors in single-digit milliseconds via batched multi-get pipelines.

4ONNX Model Inference & Policy Engine

Executes quantized gradient-boosted trees and neural ensembles in ONNX Runtime (<15ms) alongside hot-reloadable OPA/Drools fraud rules.

5Feature Audit Log & Label Feedback Lakehouse

Captures immutable scoring snapshots and joins delayed chargeback outcomes in Iceberg/Parquet for zero-skew offline retraining.

Architectural Trade-Off Analysis & CAP Constraints

Trade-Off Decision Matrix

Engineering a resilient architecture for Design Real-Time Fraud Detection & Risk Scoring Engine at a scale of 10k TPS • 2,000 Risk Features/Transaction requires deliberate trade-offs across data consistency, replication latency, network partition tolerance, and storage economics:

DimensionSelected StrategyAlternative EvaluatedTrade-Off Rationale & Latency Impact
CAP Theorem PostureAP (High Availability with Low-Latency Fallback Scoring)CP (Strict Synchronous Feature Store Linearizability)Payment authorization windows allow at most 50ms for fraud evaluation. If cross-region feature synchronization stalls during a network partition, the engine scores on local cache features rather than aborting checkout.
Model Execution ModeHybrid Two-Tier (Deterministic Rules <5ms + Async ML Scoring <50ms)Synchronous Deep Learning Neural Graph Inference (>250ms)Allows strict checkout authorization SLAs (p99 < 80ms) while offloading complex behavioral clustering to asynchronous feature pipelines.
Feature Store ConsistencyLow-Latency Cache-Aside with Redis TTL + CDC Sync from PostgresDistributed 2-Phase Commit across RDBMS and Online CachePrevents transaction pipeline halts if feature store write latencies spike. Sub-second eventual consistency is acceptable for rolling window aggregates.
Anomaly Scoring FrameworkQuantized GBDT (XGBoost) + Graph Neural Network Edge WeightsRule-Based Regex & Static Threshold HeuristicsStatic rules suffer from high false positive rates and cannot detect sophisticated botnet fraud rings or synthetic ID fraud rings across accounts.
Ingress Message QueuePartitioned Kafka with Key Hashing on Account IDCentral AMQP / RabbitMQ Message BrokerEnforces strict per-account event ordering for rolling transaction velocity checks while scaling horizontally across cluster partitions.

Fault Tolerance, High Availability & Failure Mode Analysis

Operating at 10k TPS • 2,000 Risk Features/Transaction demands proactive defenses against cascading outages. The blueprint specifies four critical failure modes and remediation protocols tailored to Design Real-Time Fraud Detection & Risk Scoring Engine:

1. Feature Store Latency Breach (>100ms)

Blast Radius: Transactions risk timing out at the payment gateway checkout boundary.

Remediation Protocol: Circuit breaker trips to Fallback Rule Evaluator using local memoized profile snapshots and conservative velocity limits.

2. Kafka Partition Rebalance During Flash Sale Event

Blast Radius: Temporary consumer stall causing event queue backpressure.

Remediation Protocol: Cooperative Sticky Partition Assignor minimizes reassignment churn; consumer groups scale preemptively before planned traffic spikes.

3. Machine Learning Model Serving Pod OOM Crash

Blast Radius: Reduced inference capacity and elevated queue latency for risk scoring.

Remediation Protocol: Kubernetes Horizontal Pod Autoscaler provisions standby pods on CPU/memory limits with automated traffic shedding to cold model replicas.

4. Graph Database Shard Split During Ring Investigation

Blast Radius: Multi-hop fraud ring correlation queries return partial graph adjacency.

Remediation Protocol: Read replicas handle analytical queries with query timeouts; primary engine isolates entity resolution with optimistic locking.

Production Algorithm Implementation: Real-Time Sliding Window Velocity Counter (Redis Pipeline)

typescript

High-scale distributed systems rely on atomic synchronization primitives to enforce SLA boundaries. Below is the production implementation for Design Real-Time Fraud Detection & Risk Scoring Engine:

import Redis from 'ioredis';

export class FraudVelocityEngine {
  constructor(private redis: Redis) {}

  async evaluateVelocityRisk(
    accountId: string,
    amountCents: number,
    windowSec: number = 300,
    maxAllowedVelocity: number = 3
  ): Promise<{ allowed: boolean; velocity: number }> {
    const key = `velocity:${accountId}`;
    const now = Date.now();
    const windowStart = now - windowSec * 1000;

    const pipeline = this.redis.pipeline();
    pipeline.zremrangebyscore(key, 0, windowStart);
    pipeline.zadd(key, now, `${now}:${amountCents}`);
    pipeline.zcard(key);
    pipeline.expire(key, windowSec * 2);

    const results = await pipeline.exec();
    const velocityCount = results ? (results[2][1] as number) : 0;

    return {
      allowed: velocityCount <= maxAllowedVelocity,
      velocity: velocityCount
    };
  }
}

Design Real-Time Fraud Detection & Risk Scoring Engine: Design Scope & Constraints Summary

This staff / principal blueprint balances 3 core functional workflows against 3 availability and latency constraints tailored for 10k TPS • 2,000 Risk Features/Transaction. Review the FAQ trade-offs below to compare partitioning keys, replication topology, and failure isolation specific to Data Systems & Search Engines.

Architectural FAQs & Interview Deep Dives

1How does the scoring path extract 2,000 risk features per transaction inside a sub-50ms latency SLA?

Computing 30-day card velocity or merchant chargeback ratios at checkout time would blow the 50 ms budget. Instead, Apache Flink continuously updates rolling sliding-window counters (5-minute, 1-hour, 30-day) and device-graph aggregates into an Aerospike/Redis online feature store, so the inference service fetches a card's pre-computed feature vector in a single <5 ms pipelined multi-key read.

2Why combine an ONNX ML ensemble with deterministic policy rules rather than relying purely on model scores?

Gradient-boosted trees and neural ensembles compiled to ONNX Runtime excel at catching subtle behavioral anomalies in under 15 ms, but they lag against brand-new card-testing scripts or regulatory mandates. A deterministic rule engine executes alongside the model to enforce hard velocity ceilings, sanctions lists, and immediate zero-day overrides without waiting for a model retrain.

3How do you eliminate training-serving skew between offline model training and online real-time fraud inference?

The feature pipeline shares identical transformation logic across streaming and batch jobs, and every live scoring call logs the exact feature vector snapshot produced at decision time to an immutable Parquet/Iceberg lake. Offline training joins delayed chargeback labels back onto those point-in-time feature logs, preventing data leakage from post-transaction events.

4What graceful degradation protects payment conversion if an online feature store shard times out during peak traffic?

The risk gateway enforces a strict 12 ms deadline on enrichment calls: if a secondary feature shard stalls, the scorer substitutes sentinel missing-value flags, routes to a compact fallback model trained on core request-payload features (BIN, IP geo, amount, AVS/CVV), and triggers step-up 3DS authentication for borderline scores instead of blocking valid buyers.