Build a Real-Time Risk Scoring Gateway for Card Payments
System DesignModel answerLast updated
Design a low-latency, highly available service that scores each payment attempt using analyst-owned rules plus ML models and returns an explainable approve, block, step-up, or review verdict.
Problem
You are building the risk scoring gateway for a payments company. Before the platform authorizes or captures a charge, it calls your service synchronously. Your service must reply with one of four verdicts:
- approve: let the payment proceed
- block: reject it
- step-up: require extra verification (for example, 3-D Secure or an OTP)
- review: hold it for a human analyst
The verdict should draw on signals such as:
- amount and merchant
- account history and chargeback history
- device fingerprint, IP address, and geolocation
- the payment instrument used
- velocity (how often a card, device, or account has appeared recently)
- known fraud patterns
The design must blend deterministic rules (authored and owned by risk analysts) with ML model scores. It must stay fast, explainable, auditable, and available. Analysts must be able to write, test, and ship new rules and models safely. Confirmed fraud, chargebacks, and manual-review results must return to the system as training labels.
Constraints
- The check sits on the payment critical path. Target p99 under roughly 100-200 ms.
- Peak load is tens of thousands of requests per second, and traffic is bursty.
- High availability is mandatory, because an outage here stalls all payments.
- Labels are delayed and noisy. Chargebacks can arrive 30+ days later, and some fraud is never labeled.
- Every block or review needs reason codes usable by support, compliance, and dispute teams.
- Rule and model changes must roll out gradually, never as a big-bang deploy.
- Card numbers and other sensitive data must be tokenized or minimized. PCI and privacy requirements are hard constraints.
What to deliver
Walk through your requirements, the synchronous decision path, feature and data architecture, the rules and model lifecycles, scaling and failure handling, auditing and monitoring, and security. Call out the trade-offs you make. Before designing, list the clarifying questions you would ask (call pattern, business priorities for fraud loss versus approval rate, QPS and latency budgets, rule ownership and speed, available labels, compliance, and reusable infrastructure).
Hints
Hint 1
Frame everything around the business trade-off: fraud losses versus false declines. Thresholds for the four verdicts come from that trade-off, not from the model alone.
Hint 2
Split the work into a hot path (fetch precomputed features, run rules and model, combine) and a cold path (stream processing, feature computation, label ingestion, training). Keep anything slow or heavy off the hot path.
Hint 3
Decide explicitly what happens when a dependency is slow or down: per-call timeouts, a rules-only fallback, and a fail-open versus fail-closed policy that depends on transaction risk tier.
Hint 4
Plan for training-serving skew and delayed labels: share feature definitions between online and offline, snapshot the features used for each decision, and use shadow and canary stages before a model or rule goes live.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements and the core trade-off
Functional: return a verdict with reason codes; combine rules and model scores; give analysts tooling to author, test, and deploy; ingest outcome labels; keep a full audit trail.
Non-functional: p99 around 100-200 ms, tens of thousands of QPS with bursts, multi-zone availability, explainability, staged rollout, and PCI/privacy compliance.
The real objective is to balance fraud loss against approval rate (false declines cost revenue and customer trust). Each verdict threshold encodes that balance, so product and risk leaders should own it, and it should be configuration rather than code.
2. Synchronous decision path
- The payment service calls the Risk API with a payment token (never a raw card number), amount, merchant, device ID, IP, and an idempotency key. Retries return the stored decision instead of re-scoring.
- Enrichment gathers features in parallel from the online feature store and a few cached lookups (IP reputation, geolocation, block/allow lists), all under a strict deadline.
- The decision engine runs in this order:
- hard rules (sanctions hit, blocklisted instrument) that can short-circuit;
- the model score;
- policy logic that maps score plus rule signals to approve / block / step-up / review.
- The response carries the verdict, reason codes, and the rule-set and model versions used.
Latency budget example: about 5 ms network and parsing, 20-40 ms feature fetch (parallel), 10-30 ms model inference, under 10 ms rules, and the remainder as headroom. Per-stage timeouts keep a slow dependency from consuming the whole budget.
3. Features
- Online store: a low-latency key-value store (for example, Redis- or DynamoDB-style) keyed by card token, device, account, and IP. Stream processors (Kafka plus Flink or similar) update windowed counters such as "attempts on this card in the last 1 min / 1 h / 24 h" and distinct-merchant counts.
- Offline store: the same feature definitions, computed in batch for training. A single shared feature spec prevents training-serving skew.
- Point-in-time correctness: training joins must use feature values as they were at decision time, or labels leak the future.
- Decision snapshot: persist the exact feature vector used for each decision. This makes audits, replays, and debugging possible.
- Freshness: monitor feature lag. A stale velocity counter can quietly blind the model.
4. Rules engine
- Rules are declarative (DSL or JSON), versioned, and stored with owner and change history.
- Workflow: draft, backtest against historical traffic, shadow (evaluate without acting, log would-be outcomes), then percentage rollout, then full activation, with approval from a second person.
- Include a kill switch and fast rollback. During a live attack an analyst may need a new blocking rule in minutes, so a streamlined emergency path with extra monitoring is justified.
- Compile rules into an in-memory structure that is hot-reloaded on each node, so evaluation stays at sub-millisecond to low-millisecond cost.
- Maintain allow/block lists with expiry and audit.
5. Model lifecycle
- A model registry stores each model with its feature schema, training data window, metrics, and owner. Serving rejects a model whose schema mismatches the feature store.
- Typical choice: gradient-boosted trees, which are fast, strong on tabular data, and explainable with SHAP-style attributions that map to reason codes. Deep models can be added for sequence or graph signals if latency allows.
- Rollout: shadow (score but ignore), canary (small traffic slice, compare approval and fraud rates), then ramp up. Keep the previous version warm for instant rollback.
- Labels: chargebacks arrive 30+ days later and are incomplete. Use manual-review outcomes and issuer or customer-reported fraud as faster proxy labels. Train with a maturity window, treat recent unlabeled data carefully, and consider reweighting. Note the selection bias: denied transactions never reveal their true label, so reserve a small, controlled exploration slice (for example, approving some borderline cases) to learn from.
- Monitor score drift, feature drift, and calibration.
6. Scale and availability
- Stateless decision nodes behind a load balancer, autoscaled, deployed across multiple zones (and regions with local feature replicas if latency or residency demands it).
- Cache slow-changing data locally. Keep models loaded in memory, with batching only if it does not hurt tail latency.
- Protect the path with timeouts, circuit breakers, bulkheads, and load shedding for bursts.
- Degradation ladder: if the model service fails, fall back to rules only; if features are missing, use defaults and flag the gap; if the whole service is unreachable, apply a fail-open vs. fail-closed policy by risk tier. For example, small low-risk transactions fail open (approve with post-auth monitoring), while large or high-risk ones fail closed or go to step-up. Make this tier-based policy explicit and agreed with the business.
- Write decisions to an event log asynchronously, so logging problems never block the response.
7. Auditability and monitoring
Per decision, persist: request ID, tokens, feature snapshot, rule hits, model version and score, final verdict, reason codes, and timestamps. Use append-only, tamper-evident storage with retention per regulation.
Key metrics: latency percentiles and error rate, verdict distribution, approval rate by segment, chargeback and confirmed-fraud rate, review-queue false-positive rate, feature freshness, and score drift. Alert on sudden shifts in verdict mix, which often signal a bad deploy or an attack.
8. Security and privacy
Tokenize card data in a PCI-scoped vault and keep raw PANs out of this service. Encrypt in transit and at rest, apply least-privilege role-based access with audit to rule and model tooling, minimize and hash personal identifiers, and honor data residency and retention rules.
9. Common mistakes
- Doing heavy computation (aggregations, joins) on the hot path instead of precomputing it.
- Ignoring training-serving skew or point-in-time leakage.
- No stated fail-open/fail-closed policy.
- Deploying rules or models without shadow and canary stages.
- Opaque scores with no reason codes.
- Treating chargebacks as instant, complete labels, and ignoring selection bias from denied traffic.
- Sending raw card data through the risk service.
10. Likely follow-ups
How do you handle a coordinated attack that spikes traffic? (Rapid rules plus velocity limits plus load shedding.) How do you support multiple regions? (Regional feature replicas, local decisioning, async global aggregation.) How do you measure true model value when denials hide outcomes? (Exploration slice and counterfactual or A/B evaluation.)