Live Market Data Distribution Platform
System DesignModel answerLast updated
Build a streaming architecture to deliver current stock quotes to millions of users with sub-second latency and graceful degradation under load.
You're tasked with architecting a platform that streams live market quotes to end users. The system receives price feeds from exchanges, processes them, and pushes updates to client applications in near real-time.
What you need to design:
- How raw feeds are consumed, validated, and normalized across different sources
- Strategy for combining feeds from multiple exchanges into unified quotes
- Distribution mechanism to reach clients (protocol choice, connection management)
- How updates are batched and conflated to balance freshness with resource usage
- Scaling approach to support millions of simultaneous viewers
- Handling of uneven popularity (some tickers vastly more watched than others)
- Managing slow or disconnected clients without impacting others
- Operational concerns: monitoring what matters, handling failures, multi-region deployment
Constraints and assumptions:
- Coverage spans roughly 10,000 tradable instruments
- Peak inbound message rate reaches 1-2 million per second during volatile periods
- Target audience is 5 million concurrent users, each tracking around 20 instruments
- Acceptable end-to-end latency is under 250ms (p99) from exchange receipt to client display
- Users need current values only; historical lookups are handled separately
- Humans perceive updates effectively at 4-10Hz, enabling intelligent batching
Walk through your design from ingestion to client delivery, explaining trade-offs and how you'd validate it works at scale.
Hints
Hint 1
Consider how popularity distribution affects resource allocation—what changes when 100 symbols account for 80% of traffic?
Hint 2
Think about the semantic guarantees clients actually need: is every intermediate price tick critical, or just maintaining an accurate current view?
Hint 3
Explore where state lives in your architecture and which components can be stateless to simplify scaling and recovery.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a streaming last-value distribution problem where the core challenge is efficiently fanning out high-frequency updates to a massive, unevenly distributed subscriber base. The architecture prioritizes low latency, horizontal scalability, and graceful degradation.
1. Requirements and Scale Estimation
Start by clarifying scope and calculating capacity needs.
Functional scope:
- Users subscribe to instruments and receive live bid/ask/last trade updates
- New subscribers get immediate snapshots of current values
- No historical queries or replay beyond current session
Scale parameters:
- 10K instruments, ~20 watched per user on average
- 5M peak concurrent connections
- 1-2M inbound messages/second from exchanges
- Target: <250ms p99 latency within region
Bandwidth calculation:
- Conflate updates to ~4Hz per instrument per client (humans can't process faster)
- 5M connections × 4 updates/sec = 20M frames/sec system-wide
- At ~500 bytes per frame (compressed JSON deltas), that's ~10GB/sec egress
- WebSocket servers handle 50-100K connections each → need ~50-100 edge servers per region
2. Architecture Overview
Exchange Feeds → Ingest Layer → Normalization → Aggregation (sharded by symbol)
↓
Internal Message Bus
↓
Fan-out / Edge Tier
↓
Client WebSockets
Ingest layer runs redundant consumers per feed (primary/backup), parsing exchange-specific protocols and timestamping arrivals.
Normalization maps venue-specific identifiers to canonical symbols, standardizes price formats, and filters invalid data.
Aggregation maintains single-writer-per-symbol state, merging multiple sources into consolidated quotes with monotonic sequence numbers. Symbols are hash-partitioned across aggregator instances.
Message bus (NATS, Kafka, or Aeron) carries per-symbol updates, partitioned by symbol hash. This enables each edge node to subscribe only to symbols its clients need.
Edge tier maintains WebSocket connections, subscribes to relevant symbols on the bus, conflates updates locally, and writes batched frames to clients.
3. Protocol and API Design
WebSocket as primary interface:
- Full-duplex: clients send subscribe/unsubscribe commands on same connection
- Low per-message overhead for high-frequency updates
- Binary frames with compression for efficiency
Client → Server: {"action":"subscribe","symbols":["AAPL","MSFT"]}
Server → Client: {"type":"snapshot","symbol":"AAPL","seq":45123,"last":189.45,"bid":189.44,"ask":189.46}
Server → Client: {"type":"delta","symbol":"AAPL","seq":45127,"last":189.52}
Sequence numbers enable clients to detect reordering or gaps. Include periodic heartbeats (~5s) so clients can mark stale feeds.
REST endpoint for initial loads and fallback: GET /quotes?symbols=AAPL,MSFT with 1-second edge cache TTL.
Rate limiting: cap subscriptions per connection (~200), connections per user/IP, and subscription operations per second using token buckets at edge.
4. Critical Design Decisions
Deduplication and source arbitration:
Run redundant consumers per feed. Track (source_id, source_seq) high-water marks to identify duplicates. Accept first arrival, drop subsequent copies. When sequence gaps appear, request retransmission or fetch snapshots.
Aggregation strategy: Single-threaded processing per symbol eliminates race conditions. Compute best national bid/offer across venues, take latest trade for "last" price. Apply sanity checks: reject outlier prices unless confirmed by multiple sources, respect halt indicators.
Two-tier fan-out: Don't publish to every client individually—that doesn't scale. The bus publishes each update once per edge node. Edge nodes then fan out in memory to their local connections. This converts O(symbols × clients) to O(symbols × edge_nodes + local_distribution).
Hot symbol handling: Popular instruments naturally spread across all edge servers since users are load-balanced. Serialize each symbol update once per edge node and reuse the byte buffer for all local subscribers—critical for CPU efficiency.
Backpressure and delivery semantics: Guarantee: latest-value, at-most-once, eventually consistent. Clients need current state, not every intermediate tick.
Each connection maintains one "dirty" slot per subscribed symbol. During each conflation interval, write the newest value to that slot. Slow clients never accumulate unbounded queues because intermediate updates overwrite each other.
If a socket's send buffer grows too large:
- Increase that client's conflation interval (250ms → 1s)
- If sustained, disconnect gracefully with a reconnect signal
- On reconnect, serve fresh snapshots from edge cache
Scaling connections: Edge nodes are stateless except for subscription indexes. Use kernel-tuned epoll servers (Go/Rust/Netty). Each node handles 50-100K connections. Scale horizontally behind L4 load balancers.
For reconnection storms (after deploys), require clients to use jittered exponential backoff. Rate-limit connection acceptance and serve snapshots from local caches rather than hitting central stores.
5. Operational Concerns
Multi-region deployment: Run complete stacks in each region. Clients connect to nearest edge. Feed handlers can be centralized (lower cost) or replicated (lower latency). Edge tiers are always regional for proximity.
Failure handling:
- Feed handler failures: standby automatically promotes to primary
- Aggregator failures: reassign symbol partitions to healthy nodes, rebuild state from snapshots
- Edge failures: clients reconnect to other nodes via load balancer
- Bus failures: maintain snapshot store (Redis cluster) so restarted nodes can rebuild state
Monitoring metrics:
- Per-symbol: ingest rate, gap count, staleness
- Per-edge: connection count, subscription distribution, send buffer depth, conflation interval distribution
- End-to-end: latency from exchange timestamp to client delivery (sampled)
- Alerts: feed gaps, aggregator lag >100ms, edge nodes with >80% connections
Testing approach:
- Replay historic feed data at scale in staging
- Synthetic load: simulate 5M connections with realistic subscription patterns
- Chaos testing: kill aggregators, partition networks, saturate edge egress
- Shadow traffic: run new versions receiving production feeds without serving clients
6. Trade-offs and Extensions
Kafka vs. low-latency bus: Kafka adds durability and replay but costs 10-50ms latency. For last-value data, a lighter bus (NATS/Aeron) plus snapshot store provides sufficient recovery without the latency tax.
Conflation interval: Configurable per client or dynamic based on load. Fixed 250ms is simple; adaptive (degrading to 1s under pressure) is more resilient.
Snapshot consistency: Snapshots from edge cache may lag by conflation interval. Acceptable for this use case—showing "stale" indicator after 15s silence is better than claiming false freshness.
Cost optimization: Provision edge tier for peak (market open), but aggregation and bus can run smaller since symbol update rates are steadier. Consider spot instances for edge with automated failover.
Complexity
- Ingest throughput: O(feed_messages) = 1-2M/s
- Aggregation: O(active_symbols) state, O(1) per message per symbol
- Fan-out: O(symbols × edges) on bus, O(subscriptions) at edge = O(clients × symbols_per_client)
- Edge memory: O(connections + unique_symbols_watched) ≈ 5M connections + 10K symbols
- Egress bandwidth: O(clients × symbols × update_rate) ≈ 10GB/s after conflation
This architecture handles the stated scale comfortably and can grow to 50M+ connections by adding edge nodes.