Threshold-Crossing Price Notifications at Scale
System DesignModel answerLast updated
Design a service where users set price-level triggers on securities and get notified quickly, exactly once, through push, email or SMS, even during market-open bursts.
Price Trigger Notification Service
You are asked to design a backend that lets investors register price triggers on securities and be told when the market price passes a level they chose.
For example, a user might ask to be notified when a given stock rises above 150 or falls below 90.
What to cover
Walk through your design and discuss:
- Functional requirements: what users can create, change and see, and whether triggers fire once or repeatedly.
- APIs: the main endpoints and the validation you would apply.
- Data model: what is stored, where, and how it is partitioned.
- Architecture: how market data and trigger definitions come together.
- Evaluation strategy: how you decide efficiently, and correctly, that a price has crossed a level.
- Scalability and latency: how the design copes with a large number of triggers and with sudden bursts.
- Reliability and deduplication: how you avoid both missed and duplicate notifications.
- Delivery: push, email and SMS, including user preferences and retries.
Assumptions you may use or adjust
- Tens of millions of users and a couple hundred million active triggers, heavily skewed toward popular tickers.
- Around 10,000 symbols.
- Peak market data of several hundred thousand quote updates per second at the open.
- A market-wide move can fire millions of triggers within minutes.
Hints
Hint 1
Scanning every trigger for a symbol on every price update does not scale. Think about how to organise thresholds so that one update only touches the triggers it actually passes.
Hint 2
Define 'crossing' using the interval between the previous price and the new price, not just the new price. This matters when updates are conflated or the price gaps.
Hint 3
Duplicates can appear at several layers (replays, queue redelivery, delivery retries). Plan an idempotency mechanism for each layer, such as a conditional state transition and a unique key per trigger event.
Hint 4
Keep the notification pipeline decoupled from evaluation through a queue, so a burst of triggers cannot slow down price processing.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
1. Requirements
Functional
- Create, list, update and delete triggers of the form
(user, symbol, direction ABOVE/BELOW, threshold). - One-shot triggers (default) fire once and then disarm. Recurring triggers re-arm after a cooldown or after the price moves back past the level.
- Notify through push, email or SMS according to user preferences.
- Keep a history with trigger time and trigger price.
Non-functional
- p99 latency from price move to notification of about 5 s, with push closer to 1 s.
- No missed triggers. Internally at-least-once, effectively-once from the user's point of view.
- Favour availability over strict ordering across symbols.
Scale (assumed): 200M active triggers, 10K symbols, 500K-1M raw updates per second at peak. Conflating to the last price per symbol every 100-250 ms gives roughly 40K-100K effective updates per second. CRUD is around 1K writes per second. A gap at the open can fire 5-10M triggers within minutes.
2. APIs
POST /v1/alerts {symbol, direction, threshold, type, channels, expires_at?} + Idempotency-Key
GET /v1/alerts?status=ACTIVE&cursor=...
PATCH /v1/alerts/{id}
DELETE /v1/alerts/{id}
GET /v1/alerts/{id}/events
PUT /v1/users/{id}/notification-prefs
Validate that the symbol exists, the threshold is positive, and the user is under a cap (say 200). If the condition is already true at creation, either reject it or define it as "fire on the next crossing". State which you choose.
3. Data model
- alerts: id, user_id, symbol, direction, threshold (decimal, never float), type, status (ACTIVE / TRIGGERED / DISABLED / EXPIRED), version, last_triggered_at, cooldown. Stored in a sharded SQL database or a wide-column store, partitioned by id, with a secondary index on user_id.
- alert_events: unique on
(alert_id, version), with trigger price, tick timestamp and per-channel delivery status. - notification_prefs: device tokens, email, phone, quiet hours, channel order.
Changes to alerts are published through change data capture to a stream keyed by symbol.
4. Architecture
Market feed -> Normalizer/conflator -> Kafka "ticks" (by symbol)
Alert API -> DB --CDC--> Kafka "alert-changes" (by symbol)
both -> Evaluator workers (in-memory index per symbol)
-> Kafka "triggers" -> Notification service
-> per-channel queues -> APNs/FCM, email, SMS providers
Because both topics are partitioned by symbol, one worker owns all state for a symbol, so no cross-node coordination is needed. The notification service is separate so that a burst of fired triggers cannot slow evaluation.
5. Evaluation
Scanning all triggers per tick fails: a single popular ticker may have millions.
- Keep two sorted structures per symbol: ABOVE triggers by ascending threshold and BELOW triggers by descending threshold (sorted array, skip list or balanced tree).
- Track
last_price. On a move fromp_prevtop_new:- If up, fire ABOVE triggers with
p_prev < threshold <= p_new. - If down, fire BELOW triggers with
p_new <= threshold < p_prev.
- If up, fire ABOVE triggers with
- Cost is O(log n + k) with k the number fired. Using the interval means conflation or a gap cannot skip a level.
- Remove fired one-shot triggers from the index and emit
{alert_id, version, symbol, price, tick_seq}. - Recurring triggers re-arm using hysteresis (e.g. price retreats 0.5% past the level) or a cooldown, which prevents flapping around the threshold.
Memory: about 40 bytes per entry, so 200M triggers is roughly 8 GB, easily spread across ~50 partitions.
Hot symbols: cost depends on k rather than n, so one core usually copes. If not, split a symbol's thresholds into ranges across several workers fed the same ticks.
Ordering: a trigger created at time T must only fire on ticks after T. Applying changes and ticks per symbol in timestamp order guarantees this.
Market closed: seed last_price from the previous close and treat the opening print as a move from it, so overnight gaps fire.
Recovery: checkpoint (change offset, tick offset, last_price) per partition. On restart, rebuild the index from a snapshot of active triggers plus the change stream, then replay ticks from the checkpoint so crossings during downtime still fire.
6. Deduplication and reliability
Duplicates come from evaluator replays, queue redelivery and delivery retries, so deduplicate at every layer:
- State transition: the trigger consumer runs a conditional update (
SET status='TRIGGERED' WHERE id=? AND version=? AND status='ACTIVE'). Only the winner proceeds. - Event key: insert into
alert_eventswith the unique(alert_id, version). A conflict means already handled. - Delivery key: pass the same key as the idempotency token to providers that support it, and record per-channel status before and after sending.
Use retries with exponential backoff and jitter, and a dead-letter queue for permanent failures. Fall back across channels (push to email to SMS) when a channel fails, and respect quiet hours and per-user rate limits.
7. Notification delivery and bursts
- Fan-out per channel with separate queues, so a slow SMS vendor does not delay push.
- Priority lanes: push first, SMS last since it is costly.
- Autoscale consumers on queue lag. The queue absorbs the 5-10M burst; provider rate limits set the drain speed, so budget for it and degrade gracefully (batch emails, collapse multiple triggers per user into one message).
8. Trade-offs and common mistakes
- Comparing only to the latest price instead of the interval: misses gaps.
- Floats for prices: use decimals or integer ticks.
- Evaluating in the database with a range query per tick: too slow and too hot on popular symbols.
- No idempotency on the trigger path: replays send duplicates.
- Coupling evaluation and sending: a burst stalls price processing.
- Ignoring flapping on recurring triggers.
- Conflation trades a little latency (100-250 ms) for a large load reduction. This is acceptable because users do not need tick-level precision, but the interval-based check keeps it correct.