VAYULearn
Colour theme
Investigate a failure
VAYU Learn

Kafka & Streaming

Designing a Real-Time Fraud Detection System (End-to-End)

40,000 Transactions Per Second. 100ms to Decide. Wrong in Either Direction, You Lose.

Kafka & Streaming
Every millisecond in a fraud pipeline is budgeted. By the time the model scores the transaction, most of the latency budget is already gone.

TL;DR

  • Fraud detection is the sharpest latency constraint in data engineering — decisions must happen within the authorization window
  • The architecture is a chain of four layers: ingestion, feature computation, feature serving, and model inference — each with a strict latency budget
  • Training-serving skew is the silent killer — if offline features don’t match online features, the model is solving the wrong problem in production
  • Wrong in one direction: fraud passes. Wrong in the other: legitimate transactions are blocked. Both cost money.
  • Fallback strategies are not optional — a model that can’t serve must degrade gracefully, not fail open

Fraud detection is not a machine learning problem. It is a distributed systems problem with a machine learning component.


A card-present fraud attack. The attacker has a cloned card. They have 30 seconds before the cardholder gets an SMS alert.
Your fraud model has 100 milliseconds to decide.
At T+0: the transaction event hits Kafka. At T+12ms: Flink computes the behavioral features. At T+18ms: Redis returns the account history. At T+52ms: the model scores the transaction. At T+67ms: the decision is returned to the authorization network.
Approved.
The features were 8 minutes stale. The account had three suspicious transactions in the last 4 minutes. The model never saw them.

Fraud detection is the edge case that stress-tests everything in your data architecture simultaneously: ingestion throughput, stream processing latency, feature store consistency, model serving reliability, and the correctness of every feature computation in between.

Most architectures pass the functional tests. They fail at the seams — where feature pipelines lag under load, where the online store diverges from the training distribution, where the fallback path approves everything because nobody designed it to do otherwise.

This blog designs the system end-to-end. Not the happy path. The full thing — including the failure modes that cost money in both directions.


The Stakes Are Asymmetric

Fraud detection errors are not equal.

A false negative — fraud that passes — results in a direct financial loss: chargeback, investigation cost, potential regulatory exposure, and erosion of merchant confidence.

A false positive — a legitimate transaction blocked — results in customer friction, potential churn, support cost, and brand damage. For high-value customers, a blocked transaction at checkout is one of the highest-friction experiences in consumer finance.

Both error types cost money. The cost functions are different. The system must be designed with explicit thresholds for each — and those thresholds must be operationally tunable without a model redeploy.

This asymmetry also determines your fallback strategy. When the model cannot serve — due to latency violations, feature staleness, or infrastructure failure — defaulting to approve has a different risk profile than defaulting to reject. Neither is universally correct. The decision depends on your business context and must be made explicitly.


The Core Architecture

Transaction Event (card swipe / online payment)
↓
Kafka Topic
(partitioned by card BIN)
↓
Flink Stream Processor
(stateful feature computation)
↓
Redis Cluster
(online feature store, <5ms reads)
↓
Model API
(inference service, GPU or optimized CPU)
↓
Decision Engine
(rule layer + model score combination)
↓
Approve / Reject / Review

Each layer has a specific responsibility. Violating the responsibility boundary of any layer — for example, computing features inside the model API, or running business rules inside the stream processor — is where complexity compunds and latency budgets collapse.

Event Ingestion Layer

Kafka is the entry point. Partitioning strategy matters immediately.

Partitioning by card BIN (first 6 digits of the card number) ensures that all events from the same card family land in the same partition. This enables stateful stream processors to maintain per-card aggregations without cross-partition joins — which are expensive and introduce ordering ambiguity.

from kafka import KafkaProducer
import json
import hashlib

producer = KafkaProducer(
bootstrap_servers=["kafka-broker-1:9092", "kafka-broker-2:9092"],
value_serializer=lambda v: json.dumps(v).encode("utf-8"),
acks="all",
retries=3,
max_in_flight_requests_per_connection=1 # preserve ordering
)

def publish_transaction(event: dict):
card_bin = event["card_number"][:6]
partition_key = hashlib.md5(card_bin.encode()).digest()

producer.send(
topic="payment-transactions",
key=partition_key,
value=event
)

acks="all" and max_in_flight_requests_per_connection=1 are non-negotiable for fraud events. You need durability guarantees and event ordering. At-least-once with acks=1 introduces replay risk that can corrupt velocity counters.

Stream Processing Layer

Flink handles stateful feature computation. The key design constraint: every feature must be computable from the event stream alone, with bounded state per key, and deterministically replayable.

Features that violate these constraints belong in the model’s offline training pipeline — not in real-time serving.

from pyflink.datastream import StreamExecutionEnvironment
from pyflink.datastream.functions import KeyedProcessFunction
from pyflink.common.state import ValueStateDescriptor
from pyflink.common.typeinfo import Types
import time

class VelocityFeatureProcessor(KeyedProcessFunction):
def open(self, runtime_context):
self.txn_count_5min = runtime_context.get_state(
ValueStateDescriptor("txn_count_5min", Types.INT())
)
self.txn_amount_5min = runtime_context.get_state(
ValueStateDescriptor("txn_amount_5min", Types.FLOAT())
)
self.last_merchant = runtime_context.get_state(
ValueStateDescriptor("last_merchant", Types.STRING())
)
self.last_txn_ts = runtime_context.get_state(
ValueStateDescriptor("last_txn_ts", Types.LONG())
)

def process_element(self, event, ctx):
now = ctx.timestamp()
window_start = now - (5 * 60 * 1000) # 5-minute window in ms

count = self.txn_count_5min.value() or 0
amount = self.txn_amount_5min.value() or 0.0
last_ts = self.last_txn_ts.value() or 0

# Approximate window — for exact windowing use Flink's window API
time_since_last = (now - last_ts) / 1000.0 if last_ts else None

features = {
"card_id": event["card_id"],
"txn_count_5min": count + 1,
"txn_amount_5min": amount + event["amount"],
"time_since_last_txn_sec": time_since_last,
"merchant_changed": event["merchant_id"] != (self.last_merchant.value() or ""),
"feature_timestamp": now
}

# Update state
self.txn_count_5min.update(count + 1)
self.txn_amount_5min.update(amount + event["amount"])
self.last_merchant.update(event["merchant_id"])
self.last_txn_ts.update(now)

yield features

State TTL is critical. Without TTL, state accumulates indefinitely for every card ever seen. At 40,000 transactions/second over months, this becomes unmanageable:

from pyflink.common.state import StateTtlConfig
from pyflink.common.time import Time

ttl_config = StateTtlConfig \
.new_builder(Time.hours(24)) \
.set_update_type(StateTtlConfig.UpdateType.OnCreateAndWrite) \
.set_state_visibility(StateTtlConfig.StateVisibility.NeverReturnExpired) \
.build()

descriptor = ValueStateDescriptor("txn_count_5min", Types.INT())
descriptor.enable_time_to_live(ttl_config)

Online Feature Store

Redis serves features to the model API with sub-5ms latency. The design constraint: reads must be single-key lookups. Multi-key lookups, pipeline operations, and Lua scripts all add latency that is invisible until you are 80ms into your 100ms budget.

import redis
import json
import time

class FeatureStore:
def __init__(self, host: str, port: int = 6379):
self.client = redis.Redis(
host=host,
port=port,
socket_timeout=0.003, # 3ms timeout — hard fail fast
socket_connect_timeout=0.005,
decode_responses=True
)

def write_features(self, card_id: str, features: dict, ttl_seconds: int = 86400):
key = f"features:card:{card_id}"
features["written_at"] = time.time()

pipe = self.client.pipeline()
pipe.hset(key, mapping=features)
pipe.expire(key, ttl_seconds)
pipe.execute()

def read_features(self, card_id: str) -> dict | None:
key = f"features:card:{card_id}"
features = self.client.hgetall(key)

if not features:
return None

# Freshness check — reject stale features
written_at = float(features.get("written_at", 0))
age_seconds = time.time() - written_at

if age_seconds > 300: # 5-minute freshness SLO
raise FeatureStaleError(
f"Features for {card_id} are {age_seconds:.0f}s old — exceeds 300s SLO"
)

return features

The freshness check is not optional. A Redis cache hit on 8-minute-old features is worse than a cache miss — it silently degrades model accuracy while appearing healthy.

Model Serving Layer

The model API must enforce its own latency budget. A model that takes 90ms to score a transaction has already consumed the full budget before the decision reaches the authorization network.

from fastapi import FastAPI, HTTPException
import time
import asyncio

app = FastAPI()
MODEL_LATENCY_BUDGET_MS = 40 # this layer's budget within the 100ms total

@app.post("/score")
async def score_transaction(payload: dict):
start = time.monotonic()

features = payload.get("features")
if not features:
raise HTTPException(status_code=400, detail="Missing features")

try:
score = await asyncio.wait_for(
run_inference(features),
timeout=MODEL_LATENCY_BUDGET_MS / 1000
)
except asyncio.TimeoutError:
# Model exceeded budget — do not block, apply fallback
return apply_fallback_score(payload)

elapsed_ms = (time.monotonic() - start) * 1000

return {
"score": score,
"latency_ms": elapsed_ms,
"model_version": MODEL_VERSION
}

def apply_fallback_score(payload: dict) -> dict:
# Fallback: apply rule-based scoring when model times out
amount = payload.get("amount", 0)
is_international = payload.get("is_international", False)

# Conservative: flag high-risk characteristics for manual review
fallback_score = 0.85 if (amount > 5000 or is_international) else 0.3

return {
"score": fallback_score,
"latency_ms": MODEL_LATENCY_BUDGET_MS,
"model_version": "fallback-rules-v1",
"fallback": True
}

Decision Layer

The model score is not the decision. The decision combines model score with business rules — velocity limits, geographic anomalies, card-present vs card-not-present risk differentials, and account-level overrides.

def make_decision(
score: float,
features: dict,
account_config: dict
) -> dict:
# Tunable thresholds — no redeploy required
approve_threshold = account_config.get("approve_threshold", 0.3)
review_threshold = account_config.get("review_threshold", 0.7)

# Hard rules that override the model
if features.get("txn_count_5min", 0) > 10:
return {"decision": "REJECT", "reason": "velocity_limit", "score": score}

if features.get("is_card_stolen_flag"):
return {"decision": "REJECT", "reason": "stolen_card_flag", "score": score}

# Model-driven decision
if score < approve_threshold:
return {"decision": "APPROVE", "reason": "model_score", "score": score}
elif score < review_threshold:
return {"decision": "REVIEW", "reason": "model_score", "score": score}
else:
return {"decision": "REJECT", "reason": "model_score", "score": score}

The Latency Budget

At 100ms total, every millisecond is accounted for before a single line of code is written.

Where Budgets Get Violated

GC pauses in the JVM. Flink runs on the JVM. A GC pause during feature computation adds 20–50ms to a single event’s latency — transparently. The transaction sees a response within budget on average, but the p99 blows out.

# JVM settings for latency-sensitive Flink jobs
-XX:+UseG1GC
-XX:MaxGCPauseMillis=20
-XX:+ParallelRefProcEnabled
-Xms4g -Xmx4g # fixed heap — no expansion pauses

Redis connection pool saturation. At 40,000 transactions/second, each requiring a Redis read, the connection pool must be sized to handle burst traffic without queuing:

redis_pool = redis.ConnectionPool(
host=REDIS_HOST,
port=6379,
max_connections=200, # sized for peak TPS + headroom
socket_timeout=0.003,
socket_connect_timeout=0.005
)

Model server queue buildup. If the model API processes requests synchronously and inference takes 35ms, a single server handles ~28 requests/second per worker. At 40,000 TPS, the queue grows faster than it drains.

The solution is horizontal scaling with a load balancer, async inference batching, and aggressive timeout enforcement — not optimistic latency assumptions.


Feature Engineering Under Latency Constraints

What Features Actually Matter

Not all features contribute equally to model performance. Features with high latency cost and low marginal lift should be excluded from the real-time path and included only in offline retraining.

Features worth the latency budget:

  • Transaction velocity (count and sum over 1, 5, 30 minute windows)
  • Time since last transaction on this card
  • Merchant category mismatch vs historical pattern
  • Geographic velocity (distance between consecutive transaction locations)
  • Device fingerprint match vs account history
  • Amount deviation from account baseline

Features that do not belong in the real-time path:

  • 30-day rolling averages (too expensive to compute in-window)
  • Network-graph features (merchant fraud rings, shared device signals) — precompute offline
  • Deep behavioral embeddings — compute offline, serve from feature store

The Training-Serving Skew Problem

This is the most common source of production model failure in fraud systems — and the hardest to detect.

During training, feature values are computed from historical batch data. In production, the same features are computed from the live event stream. If the computation logic is not identical, the model sees a different input distribution in production than it saw during training.

The model works. The predictions are systematically wrong.

# WRONG: different logic in training vs serving
# Training (batch, Spark)
df = transactions.groupBy("card_id").agg(
count("*").over(Window.partitionBy("card_id").orderBy("timestamp")
.rangeBetween(-300, 0)).alias("txn_count_5min")
)

# Serving (streaming, Flink)
count = self.txn_count_5min.value() or 0 # approximate, not bounded window

The fix is a shared feature definition library that compiles to both the offline (Spark/dbt) and online (Flink) execution environments. Feature stores like Feast enforce this — the feature definition is the source of truth, and both batch and streaming pipelines are generated from it.

# Feature definition (Feast)
from feast import Feature, FeatureView, Entity, ValueType
from feast.infra.offline_stores.contrib.spark_offline_store.spark_source import SparkSource
from feast.data_sources import KafkaSource

card_entity = Entity(name="card_id", value_type=ValueType.STRING)

card_velocity_fv = FeatureView(
>"card_velocity"
,
entities=["card_id"],
ttl=timedelta(minutes=5),
features=[
Feature(name="txn_count_5min", dtype=ValueType.INT64),
Feature(name="txn_amount_5min", dtype=ValueType.FLOAT),
Feature(name="time_since_last_txn_sec", dtype=ValueType.FLOAT),
],
>True, # serves from Redis
batch_source=SparkSource(table="card_velocity_features"),
stream_source=KafkaSource(topic="payment-transactions")
)

One definition. Two execution paths. Same feature values in training and serving.


Failure Modes That Cost Money in Both Directions

False Negatives (Fraud Passes)

Caused by:

  • Feature staleness — model scores on stale velocity signals, misses recent fraud pattern
  • Training-serving skew — model learned from features that don’t match what it receives in production
  • Novel attack vectors — model has no signal on new fraud patterns not present in training data
  • Fallback path approving high-risk transactions by default

Mitigation:

  • Freshness SLOs with hard failure on stale features
  • Continuous shadow scoring — run current and challenger models simultaneously, compare outputs
  • Feedback loop from confirmed fraud to model retraining pipeline
  • Explicit fallback logic that does not blindly approve

False Positives (Legit Blocked)

Caused by:

  • Model threshold too aggressive
  • Velocity features firing on legitimate high-frequency users (e.g., a merchant running reconciliation)
  • Geographic velocity false alarms (card used in two cities within 30 minutes via online transactions)
  • Fallback path rejecting everything during infrastructure degradation

Mitigation:

  • Tunable thresholds per account segment (premium customers get more permissive thresholds)
  • Rule exemptions for known high-velocity legitimate patterns
  • REVIEW outcome that routes to soft decline with step-up authentication instead of hard reject

Backpressure Cascade

At 40,000 TPS, a 200ms spike in Flink processing latency causes Kafka consumer lag to accumulate. If lag exceeds the feature freshness SLO, the system must decide: serve stale features or fail to the fallback path.

Neither is acceptable for long durations. The cascade looks like:

Traffic spike
→ Flink processing delay (state contention, GC pause)
→ Kafka consumer lag grows
→ Features written to Redis become stale
→ Freshness check fails
→ Fallback path activates
→ All decisions made by rules only
→ Fraud detection degrades to rule-based accuracy
→ False negative rate increases

Mitigation: circuit breaker on the feature freshness check with graduated response — don’t fail immediately on first stale read, but track the rate of freshness violations and alert before the cascade completes.

Feature Staleness

The most dangerous failure — and the least visible.

A Redis cache hit on a 10-minute-old feature set returns a value, serves the model, produces a score, and makes a decision. No error is raised. No alert fires. The transaction appears processed correctly.

The fraud that the model would have caught — based on the 3 transactions in the last 4 minutes — was invisible to the feature computation that was already 10 minutes behind.

# Freshness monitoring — emit a metric on every feature read
def read_features_with_monitoring(card_id: str) -> dict:
features = feature_store.read_features(card_id)

if features:
age = time.time() - float(features["written_at"])
metrics.histogram("feature_age_seconds", age, tags={"card_id": card_id})

if age > 120: # 2-minute warning threshold
metrics.increment("feature_staleness_warning")
if age > 300: # 5-minute SLO breach
metrics.increment("feature_staleness_slo_breach")
raise FeatureStaleError(f"Feature age {age:.0f}s exceeds SLO")

return features

Idempotency and Exactly-Once at the Decision Layer

Kafka retries and network failures mean the same transaction event can arrive at the stream processor more than once. Without idempotency, a duplicate event causes a duplicate feature update — inflating velocity counters and corrupting the model’s input.

class IdempotentVelocityProcessor(KeyedProcessFunction):
def open(self, runtime_context):
self.processed_txn_ids = runtime_context.get_map_state(
MapStateDescriptor(
"processed_txn_ids",
Types.STRING(),
Types.LONG() # timestamp of processing
)
)

def process_element(self, event, ctx):
txn_id = event["transaction_id"]

# Deduplication window: 10 minutes
if self.processed_txn_ids.contains(txn_id):
return # already processed — skip

self.processed_txn_ids.put(txn_id, ctx.timestamp())

# ... compute features normally
yield self.compute_features(event, ctx)

State for processed transaction IDs must also have a TTL — otherwise it grows without bound. A 10-minute deduplication window aligned with the Kafka retention configuration is sufficient for most deployments.


The Fallback Strategy

When the model cannot serve — due to latency violations, infrastructure failure, or feature staleness — the system must have an explicit fallback.

Three fallback strategies, in order of safety:

Rule-based fallback. Apply a simplified rule set: velocity limits, geographic checks, BIN-level risk scores. Deterministic, fast, no feature store dependency. Accuracy degrades but the system continues operating.

Conservative threshold fallback. Use a lower model score threshold — approve only transactions that would be approved at a much more conservative threshold. Increases false positives but reduces fraud exposure during degraded operation.

Manual review queue. Route all transactions to a human review queue. Only viable if transaction volume is low enough and review capacity exists. Not viable at 40,000 TPS.

The wrong fallback: approve everything. This is operationally convenient and catastrophically wrong. A model outage that also opens the fraud path destroys the entire purpose of the system.

class FallbackDecisionEngine:
FALLBACK_RULES = [
lambda f: f.get("txn_count_5min", 0) > 5, # velocity
lambda f: f.get("amount", 0) > 10000, # high value
lambda f: f.get("is_international", False), # cross-border
lambda f: f.get("merchant_changed", False) and f.get("amount", 0) > 500,
]

def score(self, features: dict) -> dict:
risk_signals = sum(1 for rule in self.FALLBACK_RULES if rule(features))
fallback_score = min(0.95, risk_signals * 0.25)

return {
"score": fallback_score,
"model_version": "fallback-rules",
"fallback": True
}

Observability That Actually Matters

Infrastructure metrics (CPU, memory, Kafka lag) tell you the system is running. They do not tell you the system is correct. For fraud detection, you need a second tier of observability.

# Business-level metrics — the ones that actually matter
metrics.gauge("fraud_detection_rate_1h", fraud_rate_last_hour())
metrics.gauge("false_positive_rate_1h", block_rate_last_hour())
metrics.gauge("model_score_p50", score_percentile(50))
metrics.gauge("model_score_p95", score_percentile(95))
metrics.gauge("feature_freshness_p99_sec", freshness_percentile(99))
metrics.gauge("fallback_rate_5min", fallback_rate_last_5min())
metrics.gauge("decision_latency_p99_ms", latency_percentile(99))

Alert on fallback_rate_5min before it reaches 10%. By the time fallback is the majority of decisions, you have already degraded for minutes.

Alert on feature_freshness_p99_sec before it exceeds the SLO. The p99 crossing 120 seconds means 1% of decisions in the last window were made on stale features — this is the leading indicator for a cascade.


Trade-offs

Latency vs feature richness. More features improve model accuracy but increase feature computation time. Every feature added to the real-time path must pass a cost-benefit analysis: does the marginal accuracy improvement justify the latency cost?

Exactly-once vs throughput. Exactly-once semantics at 40,000 TPS requires deduplication state that grows with event volume. At-least-once with idempotent feature updates is the practical choice — same correctness guarantee at lower overhead.

Model accuracy vs threshold tuning. A more aggressive threshold catches more fraud but generates more false positives. The threshold is a business decision, not a technical one — but the system must expose it as a tunable parameter, not a hardcoded constant.

Single model vs ensemble. An ensemble of specialized models (velocity model, geographic anomaly model, behavioral model) often outperforms a single general model. But it triples the inference cost and complicates the serving layer. Start with one model. Graduate to ensemble when the accuracy gap is demonstrated and the latency budget can absorb it.


Operational Lessons

Run shadow scoring before every model update. A new model that performs better offline can perform worse online due to feature distribution shift. Shadow scoring — running the new model in parallel without affecting decisions — gives you production accuracy data before the rollout.

Treat the fallback path as a first-class system. It needs its own monitoring, its own accuracy tracking, and its own improvement cycle. A fallback path that was designed once and never revisited will be wrong when you need it most.

Feature freshness is a correctness SLO, not a performance SLO. A violation does not mean the system is slow. It means the system is producing incorrect decisions. Treat it with the same urgency as a data integrity failure.

Canary deployments for threshold changes. A threshold change that shifts 5% of decisions from APPROVE to REVIEW at 40,000 TPS affects 2,000 decisions per second. Canary to 1% of traffic first. Measure the business impact. Then promote.


🚀 Final Takeaway

Fraud detection is the clearest demonstration that data engineering and machine learning are not separate disciplines.

The model is 20% of the system. The ingestion pipeline, feature computation, feature store, serving layer, fallback strategy, and observability infrastructure are 80%. And the model is only as good as the features it receives — which are only as good as the streaming pipeline that computes them — in the 100 milliseconds between a card swipe and an authorization decision.

📌 Core Principle

The model cannot save you from a bad feature pipeline.
And the feature pipeline cannot save you from a bad fallback strategy.
Design the whole system. Or fail at the seam.

🔥 Next in Series

🏛️ Designing a Scalable Analytics Platform (Like Snowflake / BigQuery)

The fraud system makes decisions in milliseconds.

Now design a system that answers questions about billions of decisions — in seconds.

Next, we break down how analytics platforms like Snowflake and BigQuery separate storage from compute, how they handle query execution at petabyte scale, and what the architectural decisions look like when you are building something that needs to serve 10,000 analysts without a dedicated cluster for each one.

Because query engines at scale are not just fast databases. They are distributed systems with a query optimizer at the center.


🔔 Follow for More

Follow TheDataForge for high-signal deep dives on Spark, Kafka, Streaming, Lakehouse, and real-world data engineering — no fluff, only engineering truth.

⚡️Let’s connect — I post daily Big Data & Spark insights at DataForgeX on X.

💬 Comment Below

Have you designed a fraud detection system — or any real-time decision system — in production?

Where did it actually break first: the latency budget, the feature freshness, the training-serving skew, or the fallback path that nobody tested until it mattered?

Or have you inherited a system where the model was excellent but the features were wrong — and the model was getting blamed for the pipeline’s failures?

👇 Real failure stories from engineers who’ve built real-time decision systems under real stakes.


🏷️ Tags

#data-engineering #machine-learning #real-time-systems #apache-kafka #apache-flink #system-design #mlops #fraud-detection #distributed-systems #production-engineering #feature-engineering