Worked design: real-time fraud features
Real-time fraud features
A payments company scores every card transaction for fraud before approving it. The model needs features such as "number of transactions on this card in the last 10 minutes", "amount spent on this card in the last 24 hours", "distinct merchants in the last hour" and "is this device new for this account?".
Scoring must take under 50 ms at p99, at 5,000 transactions per second at peak. Data scientists also need the same features, computed exactly the same way, for training on two years of history. Design the feature pipeline.
Hint 1
The feature has to be ready before the transaction it describes is scored. What does that mean for the current transaction?
Hint 2
How do you guarantee training sees what the online model would have seen?
Show solution
Two paths, one definition: transactions flow through Kafka into a stream processor (Flink) that maintains sliding or hopping window aggregates per card, device and account in state, and writes the latest values to a low-latency online store (Redis, DynamoDB, Cassandra or a feature store's online tier). The scoring service reads features by key in a few milliseconds, combines them with request-time features computed from the current transaction itself, and calls the model.
Offline: the same feature definitions compute history over the event log for training, with point-in-time joins so each training example only sees feature values as of its timestamp. A feature store (Feast, Tecton, Databricks) or one shared code path for both paths prevents training/serving skew. Log the served feature vector with each score to train on what was actually served.
Key decisions: whether the current transaction is included in its own windows (decide explicitly; usually computed at request time); event time with a small watermark; exactly-once or idempotent state updates; TTLs on keys; fallbacks when features are missing or stale (the model must still answer within 50 ms).
What a strong answer covers
- Separates online (low-latency store) and offline (training) paths from one feature definition (weight 3)
- Streaming window aggregates in a stateful processor keyed by card/device/account (weight 2)
- Point-in-time correct training data and logging of served features to avoid skew (weight 3)
- Latency budget: request-time features, online store reads, fallbacks for missing/stale values (weight 2)
- Addresses event time, late events and state size/TTL (weight 1)
Follow-ups
- A new feature needs 90-day history. How do you backfill it into the online store without downtime?
Compute the 90-day history offline in batch from the historical events, write it to the online store under the same keys (bulk load), and let the stream keep it current from a cut-over point. Overlapping by a little and making writes idempotent avoids gaps. Serve the feature only after it's verified, behind a flag.
- How would you detect that an online feature has drifted from its offline definition?
Log the online feature values at inference time, recompute the same features offline for the same entities and timestamps, and compare them (match rate, distribution difference). Alert when the mismatch exceeds a threshold. Sharing one feature definition for both paths also reduces drift.
1. Requirements
- Throughput: 5,000 transactions/s at peak.
- Latency: the whole scoring call under 50 ms p99, so the feature lookup must take a few milliseconds.
- Features: counts, sums and distinct counts over sliding windows (10 min, 1 h, 24 h) per card, account, device and merchant, plus "first time seen" flags.
- Training: two years of history, computed exactly like online.
- Correctness: approximate is acceptable for some features (distinct counts), but they must be the same approximation offline and online.
2. Data contracts
Transactions carry a unique txn_id, event_ts, card, account, device and merchant IDs. The authorization service is the producer, and it publishes to Kafka before calling the scorer, so the stream sees every transaction even if scoring times out.
3. Ingestion
auth service → Kafka (transactions, keyed by card_id) → Flink feature jobs → online store
↘ lake (raw, append-only) → offline feature computation
Keying by card_id keeps each card's events ordered within a partition. Features keyed by other entities (device, merchant) are computed in separate jobs that re-key the stream.
4. Storage and format
- Online store: a key-value store (Redis, DynamoDB, Cassandra, or a feature store's online tier) holding the latest feature values per entity key, with TTLs.
- Offline store: feature history in the lakehouse, with
entity_id,feature_tsand values, for point-in-time joins.
5. Transform: the streaming features
- Sliding windows in Flink keyed state. For "last 10 minutes", use either exact event lists with eviction (accurate, more state) or small buckets (for example 1-minute buckets summed over the last 10; cheaper, with a one-minute error bound). Pick per feature and document it.
- Distinct counts (merchants in the last hour) with exact sets for small cardinalities, or HyperLogLog sketches.
- "New device for this account" as a keyed state set of devices, with a TTL.
- Event time with a short watermark (seconds). Late events update state, but a decision already made can't be revisited.
Does a transaction count in its own features? The online feature is read before the current transaction has been processed by the stream, so it describes the past. Compute anything involving the current transaction (its amount compared with the 24 h average) at request time in the scorer. Training must follow exactly the same rule.
6. Serving
The scorer reads all features for the card, account and device in one batched read (a few ms), adds the request-time features, and calls the model. Within the latency budget there's a fallback for missing or stale features: default values, plus a flag the model was trained with, rather than timing out.
7. Quality
- Freshness: lag between event time and the online store's update, alerted above a threshold.
- Online/offline parity: sample served feature vectors (logged at scoring time) and recompute them offline. Alert on differences.
- Distribution drift per feature, compared with training.
8. Orchestration and backfill
Offline features are computed by batch jobs over the raw log using the same definitions (a feature store, or shared transformation code that both Flink and Spark run). For a new feature, backfill history offline, then bootstrap the online state from the offline values at a known timestamp and replay the stream from that point.
9. Failure modes
| Failure | Mitigation |
|---|---|
| Flink job lags (bursty traffic) | Autoscale; features flagged stale; model trained with a staleness flag |
| Online store outage | Fallback values; model still scores; alert |
| Training/serving skew | One definition, logged served vectors, parity checks |
| Hot key (a merchant with huge volume) | Pre-aggregation, sharded state, approximate counts |
10. Cost
State size is about the number of keys × the windows held, so it's driven by the longest window and the cardinality. Bucketed windows and sketches keep it bounded. Online store cost scales with keys and reads; TTLs remove dormant cards.
11. What changes at 10×
At 50k transactions/s: more Kafka partitions and Flink parallelism, sharded state, more pre-aggregation, and a strict per-feature latency budget. Most important: a shared feature platform, so each new model reuses features instead of building its own pipeline.