Building a Real-Time Market Data System: Key Engineering Paths for Generating and Parsing Stock Quotes
Market data is a classic "high-frequency write, strong timeliness, snapshot plus incremental" scenario, where a single snapshot is small and changes fast. This article walks through the end-to-end engineering of a stock quote pipeline: data collection, normalization, multi-layer validation, hot/warm/cold storage tiering, real-time derived metrics, incremental push and subscription, timezone and trading-calendar handling, reliability and degradation, security and compliance, and a pre-launch checklist. Using a sample US quote snapshot (previous close 83, open 111.5, high 115.1, last 97.17) it shows how to handle a ~34% gap-up without either polluting downstream data or dropping a genuine move, and how to balance timeliness, consistency, and correctness under real production traffic.
1. Background and Problem Definition
Stock quotes are a typical “high-frequency write, strong timeliness, snapshot plus incremental” data scenario. A quote snapshot usually contains the latest price, opening price, previous close, high, low, and a data update time. It is small in size and fast-changing. A quote service has to solve four core problems:
- Timeliness: the end-to-end latency from when a quote is produced to when it reaches the user, which directly determines the business experience.
- Consistency: data from multiple feeds for the same instrument must converge to a single version, avoiding “quote jumping” and “data rollback.”
- Availability: source jitter, network partitions, or transient spikes must never leave downstream consumers with data gaps.
- Correctness: derived metrics such as change percent and amplitude depend on several base fields, so any single bad field can contaminate downstream calculations.
Using one US quote snapshot as a thread, the rest of this article breaks down the engineering solutions to these problems one by one. That snapshot has a data update time of 2026-11-20 08:38:48, and its field composition is a standard quote snapshot structure:
| Field | Meaning | Notes |
|---|---|---|
| Name / Symbol / Market / Currency | Instrument identity | Forms the unique business key of the instrument |
| Price | Latest trade price | High-frequency field |
| Open | First trade of the day | Reset every trading day |
| Prev close | Prior trading day’s close | Baseline for change-percent calculation |
| High / Low | Intraday traded price range | Monotonically non-decreasing / non-increasing |
| Stock update time | Snapshot generation time | Basis for judging data timeliness |
1.1 Reading Anomaly Signals from the Sample Data
One detail in this snapshot stands out: the opening price of 111.5 is well above the previous close of 83, meaning the stock gapped up about 34% at the open; the high then only reached 115.1, and the latest price fell back to 97.17, still about 17.07% above the previous close. This shows the quote went through a violent price reconstruction after the open.
In a real system, data like this maps to at least three possibilities:
- A genuine gap: an overnight event, an earnings release, or index inclusion triggering a repricing;
- Source switching: different collection channels returning inconsistent calibers, for example including pre-market prices;
- Dirty data: collection errors, unit mistakes, or field misalignment.
For this reason, a quote system must support both “anomalous but not discarded” and “filtering and isolation” at the same time. The concrete approach is covered in Section 4.
2. Data Collection Layer Design
2.1 Collection Frequency and Scheduling
Collecting quotes is essentially “polling plus compensation”: constrained by upstream rate limits, the collection frequency must match upstream capacity. It also has to handle empty data, timeouts, and error codes so that a single failure does not block the entire collection task.
Collection tasks fall into roughly three types:
| Task type | Typical cycle | Metrics of interest | Key requirements |
|---|---|---|---|
| Snapshot polling | Seconds | Latest price, high, low | High priority, independent rate limiting |
| Instrument metadata sync | Minutes / days | Name, code, market, currency | Low frequency, cacheable |
| End-of-day data calibration | After close | Close price, limit-up/down and other statistical fields | Aligned with the official caliber |
The polling interval should be tuned dynamically to quote activity: raise the frequency during the open, the close, and major-event windows, and lower it during quiet periods, to balance timeliness against cost.
2.2 Multi-Source Collection and Unified Access
A single data source cannot guarantee both availability and completeness. A common approach is to connect two or more quote sources and hide their differences behind a unified adapter layer:
- Unified interface: every data source implements the same collection interface, so upper-layer scheduling and processing logic does not need to be aware of source differences;
- Source labeling: each data point carries a source identifier and collection time, making conflict resolution and fault localization easier;
- Failover: when the primary source fails repeatedly, switch automatically to a backup source, recording an audit log for the switch.
2.3 Normalization and the Data Model
Normalization is the process of converting data from different sources and formats into a single internal structure. The following principles are recommended:
- Unique key: use “market + code” as the instrument’s business key to avoid same-name code collisions across markets;
- Unified time: store internally in UTC and localize only at the presentation layer;
- Price precision: handle prices, change percent, and similar values with fixed-point decimals (such as
Decimal) to avoid floating-point error being amplified in cumulative calculations; - Explicit fields: set missing fields explicitly to null and record a quality flag, rather than substituting a zero value for a missing one.
from decimal import Decimal, ROUND_HALF_UPfrom dataclasses import dataclass@dataclassclass Quote:symbol: str # Unique instrument identifier, e.g. "US:Example-Tech"market: str # Marketcurrency: str # Currencylast: Decimal # Latest priceopen: Decimal # Opening priceprev_close: Decimal # Previous closehigh: Decimal # Highlow: Decimal # Lowts_utc: int # Snapshot timestamp (Unix ms, UTC)seq: int # Source-side monotonic sequence numbersource: str # Data source identifierdef normalize(raw: dict) -> Quote:"""Convert external raw fields into the internal standard model, precision fixed to 4 decimals."""def price(v):return Decimal(str(v)).quantize(Decimal("0.0001"), ROUND_HALF_UP)return Quote(symbol=f"{raw['market']}:{raw['code']}",market=raw["market"],currency=raw["currency"],last=price(raw["price"]),open=price(raw["open"]),prev_close=price(raw["prev_close"]),high=price(raw["high"]),low=price(raw["low"]),ts_utc=raw["update_ts_ms"], # Raw time already converted to UTC millisecondsseq=int(raw["seq"]),source=raw["source"],)
3. Data Validation and Exception Handling
After normalization comes validation. The rules can be split into three layers.
3.1 Structural Validation
- Are all fields present, and are the types correct?
- Does the code conform to the market’s coding convention?
- Are prices greater than zero?
Data that is structurally invalid goes straight to a dead-letter queue and does not enter the main flow.
3.2 Business Rule Validation
- Range constraints: the latest price should fall between the day’s high and low, and the opening price should also fall within that range;
- Monotonicity: the high can only stay equal or increase, and the low can only stay equal or decrease; if a new value crosses an existing boundary, the data may be corrupted;
- Time sanity: the snapshot time must not be far ahead of the current time, nor stay stalled for a long time.
3.3 Volatility Validation
Using the previous close as the baseline, compute the day’s deviation. When it exceeds a threshold, put the record into a “pending confirmation” state instead of discarding it outright:
- If a same-direction deviation keeps occurring over a short window, treat it as a genuine move and clear the flag;
- If it clearly disagrees with another data source, defer to the result of multi-source voting.
3.4 Anomaly Isolation Strategy
def validate(q: Quote, high_water: Decimal, low_water: Decimal) -> str:"""Return "ok" / "reject" / "quarantine", never silently dropping suspicious data."""if not all([q.last > 0, q.open > 0, q.prev_close > 0]):return "reject" # Invalid structure or base valuesif not (q.low <= q.open <= q.high and q.low <= q.last <= q.high):return "reject" # Violates the price range constraint# Gap tolerance: configurable (e.g. 20% / 30%), set according to the market's price-limit rulesdeviation = abs(q.last - q.prev_close) / q.prev_closeif deviation > Decimal("0.30"):return "quarantine" # Suspected dirty data, sent to quarantine for review# Monotonicity check: a new snapshot must not shrink the day's rangeif q.high < high_water or q.low > low_water:return "quarantine" # Range shrinking, suspected different-caliber sourcereturn "ok"
Data in quarantine does not enter the formal distribution pipeline, but the original record is retained to support later traceback and data-source quality assessment. This way, anomalous data neither pollutes downstream consumers nor gets lost during a genuine violent move.
4. Storage Layer Design: Hot/Cold Tiering
Quote data has a clear hot/cold pattern: the most recent trading day’s data is read frequently, while historical data is used for traceback, analysis, and risk-modeling. Storage should be tiered accordingly.
4.1 Hot Data: In-Memory Cache
The latest snapshot fits well in an in-memory cache (such as a Redis-like cache service), keyed by instrument and given a short expiry as a fallback. Read latency is typically kept to the millisecond level, which is enough to support high-frequency queries.
Keep in mind:
- Update the cache with an “update cache first, then publish the incremental message” order, so subscribers never read a price that lags behind the cache;
- When the cache is unavailable, automatically fall back to querying persistent storage to avoid an avalanche.
4.2 Warm Data: Relational Database
Intraday time-series data and snapshots from the last several trading days are well suited to a relational or distributed database. Partitioning by trading day means queries naturally carry a time condition, which significantly reduces the amount scanned.
4.3 Cold Data: Object Storage Plus Columnar Format
Historical quotes are well suited to being written to object storage as columnar files (such as Parquet), partitioned by date. Columnar formats offer high compression and fast scans, which fit range queries and batch analysis.
-- Example: query a symbol's intraday trend (assuming the tick table is partitioned by trade_date)SELECTts,last_price,high,low,volumeFROM tickWHERE symbol = 'US:Example-Tech'AND trade_date = '2026-11-20'ORDER BY ts ASC;
4.4 Write Path
Writing quotes is a typical high-throughput scenario. Common optimizations include:
- Batch writes: merge updates within a short time window into batch requests;
- Asynchronous persistence: write to the cache and message queue first, then let the consumer persist in batches;
- Idempotent writes: use “symbol + time” as the unique key so that duplicate messages overwrite each other, making writes naturally idempotent.
5. Real-Time Computation and Derived Metrics
Raw snapshots contain only base fields; metrics such as change percent and amplitude must be computed server-side. There are two easily overlooked traps here.
5.1 Trading-Day Switch
After the open, the “previous close” field switches to a new baseline. If the cache is not refreshed in time, the change percent will jump. It is recommended to run an explicit end-of-day calibration task around the trading-day switch and to verify the continuity between the old and new previous close.
5.2 The Calculation Caliber for Change Percent
- Zero denominator: when the previous close is zero or missing, return a null change percent with a flag, rather than returning 0%;
- Precision: use fixed-point numbers for prices, and round the change percent only at the presentation layer, to avoid error accumulation from repeated intermediate rounding;
- Consistent direction: the change amount and the change percent must share the same sign, to avoid sign-handling errors.
def derive(q: Quote) -> dict:"""Compute derived metrics from the snapshot, return a structured result ready to distribute."""change = q.last - q.prev_closepct = (change / q.prev_close) * 100 if q.prev_close else Nonereturn {"symbol": q.symbol,"last": str(q.last),"change": str(change),"change_pct": None if pct is None else round(float(pct), 2),"amplitude_pct": round(float((q.high - q.low) / q.prev_close * 100), 2)if q.prev_close else None,"ts": q.ts_utc,"seq": q.seq,}
Computing from the opening sample data: the change amount is about 14.17, the change percent about 17.07%, and the amplitude about 26.96%. The amplitude is clearly larger than the change percent, indicating intense intraday back-and-forth; such instruments often need a higher push frequency.
6. Push and Subscription: Incremental First
Quote distribution generally has two modes:
- Full push: send a complete snapshot each time; simple to implement but wastes bandwidth;
- Incremental push: send only the changed fields; low bandwidth use, but requires clients to maintain local state.
Production environments typically use a combination of “full snapshot first, incremental after, periodic full-snapshot calibration”:
- After a client establishes a connection, the server sends one complete snapshot;
- Each subsequent update sends only the changed fields;
- At a fixed interval or on reconnection, a full snapshot is sent again to correct any client state drift.
6.1 Connection Management
- Long-lived connections carry the push, kept alive by heartbeats and reconnected automatically on timeout;
- The server maintains connection and subscription relationships (which clients subscribe to which instruments);
- Set an upper limit on subscriptions per connection to prevent a single connection from overwhelming the server.
6.2 Ordering and Idempotency
Out-of-order and duplicate messages are the norm in distributed systems. The fix is to attach a monotonically increasing sequence number (such as the source sequence or a timestamp) to each snapshot, and have the client discard stale messages by sequence:
// Client: idempotent drop based on sequence number, avoiding quote rollbackfunction acceptQuote(q) {const last = state.get(q.symbol);if (last && q.seq <= last.seq) return; // Stale or duplicate message, ignorestate.set(q.symbol, q);render(q);}
7. Timezone and Trading Calendar: An Underrated Complexity
The time in the raw data, 2026-11-20 08:38:48, is the quote time from a Beijing-time perspective. The regular session of the US market usually does not open until evening Beijing time, so this time point most likely corresponds to the pre-market phase, or represents a delayed snapshot.
The engineering problems this raises include:
- Daylight saving time: the US time zone switches DST twice a year, and on those days the trading hours shift by a whole hour;
- Trading-day boundaries: the trading calendar must be modeled explicitly and cannot be inferred from “natural days”;
- Cross-market: different markets have different time zones, so unified display requires converting market by market;
- Timestamp semantics: it must be clear whether a field is the “quote occurrence time” or the “data collection time”; the two cannot be mixed.
It is recommended to maintain an independent market-calendar service containing trading sessions, lunch breaks, holidays, and DST rules, and have all scheduled tasks take their time baseline uniformly from that service.
8. Reliability and Degradation Strategies
- Multiple replicas: make the collection and push services stateless, deploy multiple instances, so a single point of failure does not affect the whole;
- Peak shaving: buffer burst traffic at the ingress with a message queue, and let consumers process at their own capacity;
- Degradation: when the push channel fails, degrade to clients actively polling the snapshot endpoint;
- Circuit breaking: automatically break the circuit when an upstream data source stays abnormal, to avoid exhausting thread and connection resources;
- Replay: persist messages by time for a certain retention period, so that after a client disconnects it can replay to fill the gap.
9. Security and Compliance
Quote data is usually subject to upstream licensing constraints, so engineering must enforce:
- Call-quota management, to avoid being banned for exceeding limits;
- Access authentication, binding subscription relationships to user permissions;
- Transport encryption, with TLS enabled on the links;
- Distribution-scope control, making clear whether data may be shown to end users or is for internal use only;
- Full-pipeline audit logs, recording collection, distribution, and access behavior.
10. Pre-Launch Checklist
Before pushing a quote service to production, it is recommended to confirm each of the following:
- Is the instrument key unique, and is it isolated across markets?
- Are time fields unified to UTC, and does the presentation layer localize them correctly?
- Do prices use fixed-point numbers to avoid floating-point error?
- Are all three lines of defense in place: structural validation, range validation, and volatility isolation?
- Is the monotonicity of the high/low broken?
- Is the previous close refreshed correctly at the trading-day switch?
- When the change-percent denominator is zero, is a null value returned rather than a zero value?
- Do incremental pushes carry a sequence number, and can the client discard stale messages?
- Is there a degradation path when any of the cache, queue, or database fails?
- Does the trading calendar include DST and holiday rules?
- Do access authentication and transport encryption cover the entire pipeline?
- Are there monitoring metrics for end-to-end latency and data gaps?
Conclusion
The engineering difficulty of quote data lies not in the number of fields, but in balancing timeliness, consistency, and correctness. Behind a seemingly simple snapshot stand normalization, validation, tiered storage, derived computation, incremental distribution, and failure degradation working together. Do data-quality validation up front, keep idempotency and ordering under control at the message layer, and abstract timezone and trading-calendar logic into an independent service — only then can you build a real-time quote system that both withstands peak traffic and stays correct under anomalies.
