Building a Real-Time Market Data System: Collection, Computation, and Monitoring in Practice
Market data systems face their toughest test on high-volatility trading days, when tick-by-tick trades, order book quotes, and index events surge far above normal levels. This article walks through a four-layer architecture for a real-time market data platform—collection, message buffering, stream computation, and storage—along with key design decisions such as event-time windowing, watermark configuration, handling late and out-of-order data, tiered storage, and monitoring strategies. It includes practical checklists for pre-launch validation and guidance on choosing between self-managed and cloud-based infrastructure. A working code example illustrates minute-bar aggregation logic, and a detailed table outlines the parameters to verify before going live.
Market Spikes Are the Ultimate Stress Test
For ordinary investors, a day of extreme market volatility is just a headline. For engineers, it means a data deluge. During turbulent sessions, the frequency of tick-by-tick trades, order book quotes, and index constituent changes rises sharply, putting far more pressure on the market data pipeline, computation engine, and alerting system than usual.
This article does not cite specific price movements. If you need to verify a particular trading day’s performance, refer to closing data published by the exchange or the index provider. The question we care about is: how do you design a market data processing system that stays stable on normal days and doesn’t collapse under peak load?
The Four-Layer Architecture and Pre-Launch Design Checks
A market data processing platform typically breaks down into four layers:
- Data collection layer: Ingests raw data streams from exchanges or data vendors through market data gateways. Common protocols include TCP-based proprietary binary protocols and standard publish-subscribe protocols. The goal of this layer is to be fast and lossless, typically using persistent connections plus local disk buffering to prevent data loss when downstream services fail.
- Message buffering layer: Uses a high-throughput message queue to smooth out traffic spikes. Flow during market open, close, and major events can be several times higher than during quiet periods; the message queue handles this traffic shaping.
- Real-time computation layer: Cleans, aggregates, and derives indicators from the stream—for example, minute bar synthesis, price change statistics, and index weighting calculations.
- Storage and serving layer: Writes real-time results to a time-series database or in-memory cache for query services. Full trade details are archived to object storage for backtesting and auditing.
The four layers give you direction, but you need to pin down concrete parameters before launch. The table below lists the key items to verify:
| Check Item | Recommended Approach | Questions to Confirm |
|---|---|---|
| Message queue partition key | Hash by security symbol so events for the same symbol stay ordered within one partition | Do messages for the same symbol always land in the same partition? |
| Message retention period | At least as long as the longest downstream failure recovery time, plus a replay window | Can you re-consume from any position within the retention period? |
| Stream processing watermark | Set the allowed out-of-order duration based on historical arrival delay distribution, e.g., P99 | Is watermark latency monitored? |
| Computation parallelism | Aligned with the message queue partition count | Does any single task experience sustained backpressure? |
| Time-series DB partitioning and TTL | Partition by symbol and time; set retention policies for hot, warm, and cold data | Do queries hit the right partitions? Is expired data cleaned up on schedule? |
| Capacity estimation baseline | Peak event rate = daily average × peak multiplier measured from historical data | Was capacity planning based on peak or average load? |
Real-Time Computation: From Tick Data to Bars
Synthesizing Minute Bars and Handling Out-of-Order Data
Using a stream processing approach, you can partition by security symbol first, then apply tumbling windows based on event time. The code below is for illustration only; production systems should use the event-time window operators provided by a stream processing framework.
# Pseudocode for illustration only; not for direct production use.# Input `trades` is a batch of tick-by-tick trades with fields:# symbol, event_time (exchange timestamp in seconds), price, volume.# Assume Bar is a pre-defined bar data structure.def window_start(ts, window_seconds=60):return ts - (ts % window_seconds)def aggregate_bar(trades, window_seconds=60):# Sort by (symbol, event_time) first, so that open takes the earliest# trade price by event time in the window, and close takes the latest.# Taking values in arrival order produces wrong results when data# arrives out of order.ordered = sorted(trades, key=lambda t: (t.symbol, t.event_time))bars = {}for t in ordered:key = (t.symbol, window_start(t.event_time, window_seconds))if key not in bars:bars[key] = Bar(open=t.price, high=t.price, low=t.price,close=t.price, volume=0)bar = bars[key]bar.high = max(bar.high, t.price)bar.low = min(bar.low, t.price)bar.close = t.pricebar.volume += t.volumereturn bars
This code only handles out-of-order data within a single batch. Cross-batch disorder requires a watermark mechanism.
A watermark can be understood as a point in time meaning “the system considers all events before this time to have essentially arrived.” It is computed as the maximum observed event time minus the allowed out-of-order duration. A window closes and emits its result only when its end time is earlier than the watermark.
The allowed out-of-order duration is a critical parameter. Set it too large and bar output is noticeably delayed. Set it too small and valid trades that arrive late get dropped. This value should be derived from the arrival delay distribution in historical data, not guessed from experience.
You also need an explicit strategy for late data:
- Data arriving within the allowed lateness window updates the already-emitted bars and sends correction messages downstream.
- Data exceeding the allowed window is written to a side output stream (a late-data table), counted, and used to trigger an alert—never silently discarded.
Price Change and Index Calculations
Price change is fundamentally an incremental calculation based on the previous close:
Price change = (Latest price − Previous close) ÷ Previous close × 100%
The previous close is a classic slowly changing dimension. It should be loaded into memory before each trading session opens, with version information retained. This way, even if the computation process restarts intraday, it can recover from the same baseline price.
Index calculation requires maintaining a pre-built constituent and weight table. The divisor method is commonly used: the index equals the weighted market cap of constituents divided by a divisor. When constituents change or corporate actions occur, the divisor is adjusted to keep the index continuous. Specific rules should follow the index provider’s official announcements. Implementation must handle these edge cases:
- Corporate actions (splits and dividends): The previous close must be adjusted for splits and dividends; otherwise, artificial price drops will appear.
- Constituent changes: Switch the constituent table at the effective time specified in the announcement, not when the system receives it.
- Suspensions and resumptions: Whether bars are generated during a trading halt, and whether the previous value carries forward, must be explicitly defined in the rules—and downstream consumers must read the same rules.
Storage and Query Optimization
Market data is classic time-series data: write-heavy, read-light, with queries typically bounded by time ranges. In practice, you can tier data by access frequency:
- Hot data (intraday ticks and minute bars): kept in an in-memory cache or high-performance time-series storage.
- Warm data (recent months of history): kept in a distributed time-series database, partitioned by both time and symbol.
- Cold data (full historical details): archived to object storage in columnar formats such as Parquet, partitioned by date and symbol, for offline backtesting.
Note that vague claims like “very low query latency” are meaningless. Latency should be described with concrete metrics—for example, P99 latency at a given concurrency level and data volume. Each team should run load tests against its own workload before drawing conclusions.
On the query side, design partitioning and indexes around the highest-frequency access pattern: “symbol plus time range.” If queries can’t hit partitions, they degrade into full table scans, which become the first bottleneck during peak periods.
Monitoring and Alerting: Calibrate Thresholds, Don’t Copy Them
Observability of the market data system itself matters just as much. Build monitoring across three dimensions.
1. Data quality monitoring
- Feed interruption detection: alert when a data source has produced no messages for longer than a configured number of seconds during trading hours.
- Price jump detection: alert when price changes versus the previous trade or previous close exceed a threshold. Thresholds should be set using historical volatility percentiles per instrument. The 2% used in this article’s example is illustrative only and should not be treated as a universal threshold.
- Volume anomalies: volume at zero for an extended period, or deviating significantly from the same period historically.
The core difficulty with data quality alerts is distinguishing “genuine market behavior” from “data source failures.” A single metric easily produces false positives. Use multi-signal confirmation: escalate to a critical alert only when a price anomaly also appears on another data source, or coincides with a volume anomaly. For false positives, set alert severity levels and suppression windows, and record the reason whenever a human confirms an alert was benign, gradually tuning the rules.
2. Pipeline latency monitoring
Instrument end-to-end timing from “exchange send time” to “platform processing complete,” track percentile latencies rather than averages alone, and set tiered alert thresholds accordingly. Averages mask tail latency—and the tail is exactly what breaks first during market spikes.
3. Capacity monitoring
Set early warnings on message queue backlog, consumer lag, computation task backpressure, and storage write rates. The goal is to scale out before peak demand arrives, not to react after backlogs have already built up.
Self-Managed vs. Cloud Services
If you already use compliant cloud-managed message queues, stream processing, logging, and monitoring services, you can reduce the burden of building infrastructure yourself. When evaluating them, consider three things: the degree of vendor lock-in, how costs scale with peak traffic, and data residency and compliance requirements.
Self-managed setups (e.g., running your own Kafka and Flink clusters) offer more control but come with high operational costs. Hybrid approaches are common: keep the hot path on self-managed clusters while moving archiving and offline analytics to the cloud. The right choice depends on your team’s operational capabilities and compliance boundaries.
Pre-Launch Checklist
- Peak load testing: Test at several times the highest historical event rate, recording how latency and backlog evolve.
- Feed interruption drills: Deliberately cut off a data source and verify that alerts fire promptly and that data is complete after recovery.
- Late data replay: Inject out-of-order and late events from historical data and verify that corrected bars are accurate.
- Alert severity and on-call paths: Confirm the recipient, response time, and resolution steps for each alert level.
- Rollback plan: Ensure you can switch back to the previous computation logic and recompute from raw messages.
Conclusion
Behind a single market close headline lies an engineering chain of data collection, stream computation, time-series storage, and reliability safeguards. When designing such systems, base capacity planning on peak scenarios, ensure computational correctness through event-time semantics, and balance storage cost against performance with tiered storage. Validate these designs before launch with load tests, feed interruption drills, and late data replay—only then can the system deliver stable output when markets turn volatile.
