Sub-50ms Payment Risk Scoring Service for Peak Traffic
System DesignModel answerLast updated
Architect an online scoring service that labels each card payment as approve, flag or block within 50 ms, handles 10k+ RPS and spikes, and ships new models with no downtime.
You are designing the risk-scoring layer for a payments platform that handles millions of card transactions per day. Each authorization request passes through this layer before it is completed.
Required behavior
- Every transaction must receive one of three outcomes: Approve, Flag (let it through but trigger manual review or step-up authentication), or Block.
- The full decision must come back within 50 ms per transaction.
- The platform must sustain 10,000+ requests per second and still succeed at a high rate during sudden surges such as holiday sales.
- Models must be replaceable without any service interruption.
What to cover in your answer
- Requirements and capacity estimates.
- Overall architecture and the request path.
- How features are produced, stored and served, both online and offline.
- Model choice and serving strategy.
- Scaling, fault tolerance and graceful degradation.
- Rollout of new models, monitoring and day-to-day operation.
State any assumptions you make, and explain the trade-offs behind your main decisions.
Hints
Hint 1
Start with numbers: translate 'millions per day' into average RPS, then compare it with the stated peak and a surge multiplier, and write a per-step latency budget that leaves headroom for tail latency.
Hint 2
Separate what must happen on the critical path (feature lookup, rules, inference, thresholding) from what can be asynchronous (logging, aggregate updates, case creation). Think about how features computed in a stream could lag behind a burst of attacks.
Hint 3
For model updates, think in stages: shadow traffic, then a canary split keyed consistently, then an atomic pointer swap with the old version kept warm. For overload, define an ordered degradation ladder rather than a single fallback.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify and size
Functional
- Score each authorization and return Approve, Flag or Block. Flag means the payment proceeds but is sent to review or step-up auth (OTP, 3DS).
- Run business rules next to the model: velocity caps, sanctions and merchant blocklists.
- Capture outcomes (chargebacks, analyst verdicts) as labels for retraining.
Non-functional
- p99 latency at most 50 ms, measured at the service boundary.
- Throughput: "millions per day" averages only ~50-100 RPS, so the real driver is the 10k RPS peak. Surges can reach 3-5x, so plan for about 50k RPS with pre-scaling.
- Availability of 99.99% or better. The service sits in the payment path, so it must fail by explicit policy (fail open or fail safe), never hang.
- Zero-downtime model changes.
Sizing: 10k RPS at ~2 KB per event is ~20 MB/s, or ~1.7 TB/day of raw events. At 50k RPS with ~200 features, the feature store sees up to ~1M key reads per second.
2. Architecture
Gateway --gRPC--> Decision Service (stateless)
1. parallel feature fetch -> online store (Redis/Aerospike)
2. in-process rules
3. model inference -> in-process GBDT / Triton
4. threshold policy
async -> Kafka (txn, features, score, decision)
Kafka -> Flink -> rolling aggregates -> online store
Kafka -> data lake -> labels + offline features -> training -> model registry
The API is idempotent on an idempotency_key so retries do not inflate velocity counters. The response carries the decision, score, reason codes and model version.
Latency budget (p99)
| Step | Budget |
|---|---|
| Network and decode | 5 ms |
| Feature fetch (parallel, batched) | 10 ms |
| Rules | 2 ms |
| Inference | 10 ms |
| Policy and response | 3 ms |
| Headroom for GC, retries, tail | ~20 ms |
Anything not required for the decision (logging, feature writes, case creation) goes off the critical path through Kafka.
3. Features
Three tiers:
- Request-time: amount, merchant category, distance from the previous location.
- Streaming aggregates: counts and sums per card over 1 minute, 1 hour and 24 hours; distinct merchants per device; failed attempts per IP. Flink maintains these.
- Batch: account age, historical chargeback rate, merchant risk embeddings, refreshed daily.
Precompute aggressively and key by entity so one request issues a few pipelined multi-gets in parallel.
Training/serving skew is the classic failure. Define features once (for example in a feature store with shared transformation code) and, more importantly, log the exact vector used at decision time and train on it.
Freshness gap: stream aggregates lag by about a second, so a card-testing burst can slip through. Add the current transaction to the fetched counts in-request, and use atomic counters on the hot path for the most critical velocity features.
4. Model and decision policy
- Primary: gradient-boosted trees (XGBoost or LightGBM). Strong on tabular data, sub-millisecond CPU inference, and explainable through SHAP-based reason codes.
- Optional second stage: a graph or sequence model over card, device and merchant relationships, served on GPU with dynamic batching using 1-2 ms windows. Precompute entity embeddings so online work is a lookup and a small head.
- Policy is separate from the model. Scores map to outcomes through thresholds tuned per segment (merchant tier, region, amount band) by balancing expected fraud loss, false-decline cost and review capacity. Threshold changes then need no redeploy.
- Imbalance (~0.1% positives): weighted loss or negative downsampling plus recalibration. Evaluate with PR-AUC and recall at a fixed false-positive rate, not accuracy.
5. Zero-downtime rollout
- Register the artifact with version, feature schema and offline metrics.
- Shadow: score live traffic with the new model, log only, compare score distributions, flag rate and latency.
- Canary: 1% to 10% to 50%, bucketed by hashed
card_idfor consistent per-card behavior. Auto-rollback on latency, error or decline-rate guardrails. - Hot swap: load the new version beside the old, warm it with synthetic requests, then flip an atomic pointer (or blue/green behind the load balancer).
- Keep the previous version resident for instant rollback.
6. Scaling and reliability
- Decision service is stateless: autoscale on CPU and RPS, pre-scale for known events because reactive scaling is too slow for a ramp, deploy multi-AZ and ideally active-active across regions.
- Online store: shard by entity key, replicate per AZ, and cache hot keys (large merchants) locally with a short TTL.
- Degradation ladder to protect the SLA:
- Drop the second-stage model and use GBDT only.
- Fill slow or missing features with defaults (train with feature dropout so the model tolerates this).
- Fall back to rules only.
- Last resort: apply a pre-agreed fail-open or fail-safe default, such as approving low-value transactions and stepping up or declining high-risk ones.
- Use per-dependency timeouts well under the budget, circuit breakers, and hedged reads for slow store replicas. Never retry blindly on the critical path.
7. Monitoring and operations
- Service health: p50/p99/p999 latency per stage, error and timeout rates, fallback-tier usage.
- Data health: feature null rates, distribution drift (PSI), stream lag.
- Model health: score distribution, approve/flag/block rates, and delayed-label metrics. Chargebacks arrive weeks later, so also watch proxy signals such as analyst-confirmed fraud and step-up failures.
- Keep a small random holdout (approve a sliver of would-be blocks) to measure true loss and avoid feedback-loop bias in training data.
- Retrain on a schedule plus on drift triggers. Fraudsters adapt, so a fast loop for rules and thresholds matters as much as model refreshes.
Common mistakes
- Sizing from the daily average instead of the peak and surge.
- Putting stream-processing or database writes on the synchronous path.
- Ignoring training/serving skew and the feature freshness gap.
- Tying thresholds to the model artifact, forcing redeploys for business tweaks.
- Having no defined behavior when dependencies are slow, which turns a partial outage into a total one.
- Evaluating with accuracy on a 0.1% positive class.