Design real-time system to fetch stock prices (Current, 1 day, 24 hrs, 1 month, 6 months)
Difficulty: MEDIUMCategory: HLDFrequency: 1Asked On 2020-03-24
Problem Statement
Designing a real-time stock market data system that fetches, processes, and serves stock prices at different granularities:
•Current (live tick-level data)
•1 Day (intraday historical data)
•24 Hours
•1 Month
•6 Months
The system must provide low-latency live prices for traders while also supporting efficient historical queries for charting and analytics.
✅ Functional Requirements
1.Real-time Stock Data Feed
•Fetch live stock prices from external data providers (e.g., NSE, BSE, NYSE, Nasdaq APIs).
•Support high-frequency updates (tick data every few ms).
2.Data Storage
•Store live data in a time-series database.
•Maintain aggregated data at different granularities (minute, hourly, daily).
3.APIs for Clients
•Current Price API → Returns latest price.
•Historical API → Returns prices for given time range (1 day, 24 hrs, 1 month, 6 months).
•Charting API → Returns OHLC (Open-High-Low-Close) + volume data.
4.Data Aggregation
•Aggregate tick-level data into candlesticks (1 min, 5 min, hourly).
•Support rolling windows for efficient retrieval.
5.Scalability
•Support thousands of requests per second from users.
•Handle spikes during trading hours.
6.Reliability & Fault Tolerance
•Ensure no data loss even if one data source fails.
•Use replication and failover strategies.
❌ Non-Functional Requirements
•Low Latency: <100 ms for current price requests.
•High Throughput: Millions of ticks ingested per second.
•Data Accuracy: Must match real exchange-provided values.
•Availability: 99.99% uptime.
•Consistency: Eventual consistency acceptable for historical queries; strong consistency needed for live prices.
🧱 System Components
1.Market Data Ingestion Service
•Connects to external stock exchanges.
•Normalizes feeds (different formats → common schema).
•Publishes tick data into a Kafka-like event bus.
2.Stream Processing Service
•Consumes tick data.
•Aggregates into candlesticks (1-min, 5-min, hourly, daily).
•Pushes results into time-series database.
3.Time-Series Database
•Stores tick-level and aggregated data.
•Options: TimescaleDB, InfluxDB, Cassandra.
•Partitioned by stock_symbol + time.
4.Cache Layer
•Redis for caching latest stock prices.
•Short-lived hot data for live trading queries.
5.API Gateway
•Exposes APIs for:
•GET /price/current/{symbol}
•GET /price/historical/{symbol}?range=1d/24h/1m/6m
•GET /price/ohlc/{symbol}?interval=5m
6.Analytics & Charting Service
•Processes data for visualizations.
•Supports technical indicators (Moving Averages, RSI, etc.).
🔄 Example Flow
1.Ingestion:
•System receives tick: AAPL → $174.35 @ 10:05:32.123.
•Published to Kafka topic stock_ticks.
2.Processing:
•Stream processor updates current_price[AAPL].
•Aggregates into 1-min OHLC bucket.
3.Storage:
•Tick → stored in time-series DB.
•Aggregates → stored in pre-computed tables.
4.Serving Requests:
•Trader queries: GET /price/current/AAPL.
•Response: $174.35 (last updated 12ms ago).
•Analyst queries: GET /price/historical/AAPL?range=1m.
•Response: JSON of daily closing prices for past 1 month.
⚖️ Trade-offs / Design Considerations
•Tick-level storage vs Aggregates: Storing raw ticks is expensive; pre-aggregate for efficiency.
•SQL vs NoSQL: SQL (TimescaleDB) for analytics, NoSQL (Cassandra) for scale.
•Consistency vs Latency: Strong consistency for live prices, eventual for history.
•Cost: Storing 6 months of tick-level data is huge (terabytes). Compress or downsample old data.
🧪 Open Discussion Points
•Should we store all raw ticks, or only keep last 1 day and aggregate the rest?
•How to handle market close / weekends / holidays in aggregation logic?
•How to design global replication (users in India querying NYSE data)?
•Can we extend system to also support alerts/notifications (e.g., “Stock > $180”)?