Real-Time Anomaly Detection System for High-Traffic Platform
Machine LearningModel answerLast updated
Build a streaming anomaly detection architecture that processes millions of requests per second, handles extreme class imbalance, and maintains feature consistency.
You're building an anomaly detection system for a large-scale platform that needs to identify suspicious patterns in real-time across global traffic. The platform receives enormous request volume, but only a tiny fraction represents true anomalies—creating significant technical and ML challenges.
Context
Your platform processes 5 million requests per second worldwide. Suspicious patterns (credential stuffing, scraping bots, coordinated abuse) occur in roughly 0.01% of traffic. You need to:
- Flag anomalies within 500ms of the request arriving
- Route flagged events to a labeling system for model improvement
- Maintain consistency between the features your model sees during inference and what your training pipeline uses
Your Task
Design the end-to-end ML system. Address:
-
Architecture: Describe the data pipeline from request ingestion through model inference to action. How do you achieve sub-500ms latency at this scale?
-
Feature computation: How do you build time-windowed aggregations (requests per IP per minute, velocity metrics, behavioral patterns) in a streaming environment? What happens when traffic is fragmented across regions?
-
Labeling pipeline: With only 0.01% anomaly rate and perhaps 10,000–50,000 labels per day available from human reviewers, how do you decide which examples to label? How do you avoid wasting labels on redundant examples?
-
Feature consistency: The features computed at inference time (with live streaming state) will differ from features recomputed hours later when labels arrive. How do you ensure your training data reflects exactly what the model saw?
Discuss trade-offs, failure modes, and where you'd compromise under cost or complexity constraints.
Hints
Hint 1
Consider a multi-stage inference pipeline where a cheap filter sees all traffic and an expensive model sees only flagged candidates
Hint 2
Partition your stream by entity (IP, user, device) so all events for one entity flow to the same worker—this makes windowed aggregations local
Hint 3
Log the actual feature vector at inference time rather than recomputing features later when labels arrive
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem tests your ability to design a production ML system under strict latency, scale, and correctness constraints. I'll walk through the architecture, then dive into the hard parts: streaming features, smart sampling, and avoiding train-serve skew.
1. Establish Scale and Constraints
Start by translating requirements into concrete numbers:
- Ingest rate: 5M requests/sec, assume ~1 KB metadata each (IP, headers, user ID, device fingerprint, path, timestamp) → ~5 GB/sec, or 430 TB/day raw.
- Anomaly volume: 0.01% × 5M = 500 anomalies/sec, or 43 million/day. Humans can't label that. A realistic annotation budget is 10k–50k labels/day, so you need aggressive sampling.
- Latency budget: 500ms end-to-end means every stage (ingestion, feature computation, inference, action propagation) must stay well under 100ms.
- Actions: Allow, present CAPTCHA, rate-limit, block. False positives harm revenue, so optimize for precision at acceptable recall rather than raw accuracy.
Clarify whether detection is inline (blocks the request) or near-real-time (flags for subsequent requests). A practical answer: run cheap rule checks inline at the edge, and stream metadata asynchronously to a detector that updates edge policies within 500ms.
2. High-Level Architecture
┌─────────────────────────────────────────────────┐
│ Edge / CDN + WAF │
│ - Inline: IP blocklists, rate limits │
│ - Async mirror: send metadata to stream │
└──────────────────┬──────────────────────────────┘
│
┌────────▼────────┐
│ Kafka/Kinesis │ (partitioned by IP/user/device)
│ (regional) │
└────────┬────────┘
│
┌────────▼───────────────────────────────┐
│ Stream Processor (Flink/Spark) │
│ - Windowed aggregations │
│ - Write to online feature store │
└────────┬───────────────────────────────┘
│
┌────────▼────────┐
│ Feature Store │ (Redis / DynamoDB, regional)
│ TTL ~1 hour │
└────────┬────────┘
│
┌────────▼────────────────────────────────┐
│ Two-Stage Inference │
│ Stage 1: Fast filter (rules + GBDT) │
│ ~5ms, sees all 5M req/s │
│ Stage 2: Deep model (ensemble/NN) │
│ ~50ms, sees ~1% flagged │
└────────┬────────────────────────────────┘
│
┌────────▼─────────────────────────────────┐
│ Decision Service │
│ - Publish actions to edge cache │
│ - Log (request_id, features, score) │
└────────┬─────────────────────────────────┘
│
┌────────▼────────┐
│ Inference Log │ → Kafka → S3/Iceberg
└────────┬────────┘
│
┌────────▼────────────────────────────────┐
│ Sampling & Labeling Queue │
│ - Stratified, adaptive sampling │
│ - Human + weak labels (chargebacks) │
└────────┬────────────────────────────────┘
│
┌────────▼────────┐
│ Training │ → Model Registry → Deploy
└─────────────────┘
Multi-stage inference is critical. A single deep model cannot score 5M req/s economically. Stage 1 (lightweight GBDT or linear model on CPU) sees all traffic and passes ~1% (50k req/s) to Stage 2 (richer model, GPU if needed). This cuts cost by 100× while preserving recall.
Regional deployment: Each geographic region (us-east, eu-west, ap-southeast) runs its own pipeline. This keeps latency low and contains failures. If the detector goes down, fail open to static edge rules so legitimate traffic is never blocked by an outage.
3. Feature Engineering: Streaming Aggregations at Scale
Partition by entity key. Configure Kafka topics with partition keys like hash(ip), hash(user_id), hash(device_id). All events for a given IP flow to the same Flink task, making windowed state local—no cross-worker coordination needed.
Sliding/hopping windows. Use Flink's keyed state (backed by RocksDB, checkpointed to S3) to maintain:
- Requests per IP per 1 min, 5 min, 1 hour
- Distinct user-agents per IP (via HyperLogLog)
- Failed login attempts per account per 5 min
- Cart additions per session per minute (velocity)
- Inter-arrival time variance (bots are often too regular)
Approximation for memory efficiency:
- HyperLogLog for distinct counts (user-agents, paths)
- Count-Min Sketch for heavy hitters
- T-Digest for percentiles
Hot keys (shared IPs). Corporate proxies or carrier-grade NAT can generate 100k req/s from one IP. Salt the key (ip#0, ip#1, ..., ip#k), pre-aggregate per shard, then merge in a second Flink operator. Maintain per-ASN baselines so high volume from a known shared IP isn't automatically flagged.
Cross-region aggregation. Attackers often distribute load across regions. Each region publishes mergeable sketches (HLL, CMS) to a global topic every 5–10 seconds. Other regions consume and merge these into global_ip_requests_1min_lagged features. The model is trained with the same lag, so the feature distribution matches production.
Event time & late arrivals. Use event timestamps with watermarks (allow 5s lateness). Late events update state but don't retrigger downstream decisions.
4. Labeling Strategy: Adaptive Sampling Under Severe Imbalance
You have 43M anomalies/day but can label only 10k–50k. The goal: spend labels on informative examples while keeping an unbiased eval set.
Stratified reservoir sampling:
- Define strata by: score band × region × traffic type (login, checkout, API) × action taken.
- Maintain a weighted reservoir per stratum (Algorithm A-Res). This ensures rare slices (new regions, uncommon endpoints) are represented.
Allocate budget adaptively:
- 50% uncertainty sampling: Examples near the decision threshold, high ensemble disagreement, or high entropy. These improve the boundary.
- 20% novelty: Embeddings far from training clusters, or new ASN/device/fingerprint combinations. Catches zero-day patterns.
- 20% high-confidence positives: Verify precision on blocked traffic.
- 10% uniform random sample: The only unbiased source for recall estimation and prevalence monitoring.
Re-balance weekly based on where label noise and model error concentrate.
Diversity within strata. Cluster candidates by IP/24 + device fingerprint and sample a few per cluster. Avoids labeling 1,000 instances of the same botnet.
Record sampling probability p with each sample. Training applies importance weights 1/p; metrics use inverse-propensity weighting for unbiased estimates.
Weak supervision at scale. Downstream signals—chargebacks, account takeover reports, CAPTCHA solve failures—arrive with delay but cover volume. Use them as noisy labels; humans resolve conflicts and novel patterns.
5. Feature Consistency: Avoiding Train-Serve Skew
The trap: If you recompute features at labeling time (hours later), windowed aggregations will differ from what the model saw at inference. For example, "requests in last 5 min" computed now ≠ what it was then.
Solution: Log features at inference time.
At decision time, write an immutable record to Kafka (exactly-once semantics via Flink's two-phase commit):
{
request_id, event_ts, feature_vector, feature_schema_version,
model_version, score, threshold, action, sampling_stratum, sampling_prob
}
Stream to an Iceberg table (supports schema evolution, time travel).
When labels arrive hours later (keyed by request_id), join the label table to the inference log. Training data is exactly what was served.
Point-in-time correctness for new features: If you add a feature post-launch, backfill from the offline feature store using event_ts as-of joins. The offline store must be built from the same Flink job (one code path, dual sinks: online Redis + offline Iceberg).
Model version management:
- Every inference service pulls models from a registry and checks
feature_schema_version. Mismatches refuse to load. - Canary rollouts per region (5% → 50% → 100%).
- Track model version in logs so you can attribute performance shifts.
6. Trade-Offs and Failure Modes
Latency vs. richness: Richer features (graph embeddings, sequence models) cost latency. Keep Stage 1 ultra-lean; use Stage 2 for complexity.
Cost vs. coverage: Training on sampled data means rare attack vectors may be underrepresented. Augment with adversarial red-team data and synthetic attacks.
Fail-open vs. fail-closed: If the detector is down, fail open (allow traffic, rely on edge rules). False negatives are better than blocking all checkout.
Labeling bias: High-score sampling over-represents obvious attacks. The 10% uniform sample is your only unbiased ground truth—protect it.
Regional data residency: Some jurisdictions require data stay in-region. Run isolated pipelines and skip global aggregation for those regions; accept slightly lower recall.
Complexity
Throughput: O(requests/sec) with bounded per-request cost via approximations and multi-stage inference.
Latency: Sub-500ms end-to-end via regional pipelines, local windowed state, and caching.
Storage: Inference logs ~1 KB × 5M req/s × 86,400 sec/day = ~430 TB/day. Compress, partition by date, and TTL after 90 days. Feature store retains only recent windows (1 hour), ~10 GB per region.
Code Sketch (Flink Windowed Aggregation)
from pyflink.datastream import StreamExecutionEnvironment, TimeCharacteristic
from pyflink.datastream.window import TumblingEventTimeWindows
from pyflink.common import Time
from pyflink.common.watermark_strategy import WatermarkStrategy
env = StreamExecutionEnvironment.get_execution_environment()
env.set_stream_time_characteristic(TimeCharacteristic.EventTime)
# Kafka source with event-time extraction
requests = env.add_source(kafka_source) \
.assign_timestamps_and_watermarks(
WatermarkStrategy
.for_bounded_out_of_orderness(Time.seconds(5))
.with_timestamp_assigner(lambda event, ts: event['timestamp'])
)
# Key by IP, window by 1 minute, count
ip_counts = requests \
.key_by(lambda event: event['ip']) \
.window(TumblingEventTimeWindows.of(Time.minutes(1))) \
.reduce(lambda a, b: {
'ip': a['ip'],
'count': a.get('count', 1) + b.get('count', 1),
'distinct_ua': hll_merge(a.get('hll_ua'), b.get('hll_ua'))
})
# Sink to Redis (online) and Iceberg (offline)
ip_counts.add_sink(redis_sink)
ip_counts.add_sink(iceberg_sink)
env.execute("ip_aggregation")
Summary
A production anomaly detection system at this scale demands:
- Multi-stage inference to balance cost and latency.
- Partitioned streaming with local windowed state for scalable feature computation.
- Stratified adaptive sampling to handle extreme imbalance and allocate scarce labels intelligently.
- Logging features at inference time to ensure training data matches exactly what the model saw, avoiding train-serve skew.
The hardest part isn't the model—it's the infrastructure to serve it correctly at scale and keep the feedback loop consistent.