Designing and Building a Real-Time Market Data Service: Engineering Practices That Work

    Real-time market data looks simple on the surface, but keeping it accurate and low-latency is hard. This article walks through a complete engineering playbook: defining strict field semantics, running a dual-channel snapshot-plus-stream ingestion pipeline, governing time semantics with dual timestamps, keeping derived metrics consistent, separating hot/warm/cold storage paths, and building observability and disaster recovery into the service. You'll come away with concrete rules—including monotonic merge logic and staleness contracts—that systematically eliminate data jitter and metric disputes.

    1. Why Market Data Is Hard

    On the surface, a market data record is trivially simple: a symbol, a trading pair, a last price, a set of interval highs and lows, a change percentage, a market cap and rank, and an update time—barely a dozen fields. But turning this into a stable production service is hard, and not because of the fields themselves. The difficulty lies in three things: the data changes continuously, multiple sources disagree on definitions, and downstream consumers are extremely sensitive to latency and consistency.

    A single quote can be overwritten many times per second. Any ingestion hiccup, clock drift, or duplicate consumption gets amplified downstream into “price jumps,” “abnormal change percentages,” or “flickering rankings.” The core engineering goals of a market data service can therefore be summarized as: low latency, unified definitions, traceability, and replayability.

    2. A Unified Data Model: Define Field Semantics First

    Before writing any ingestion code, you must nail down field semantics—otherwise every downstream calculation will disagree with the others. Here is a usable minimal model:

    Field Semantics Engineering Notes
    Symbol Unique asset identifier Decouple from trading pairs; one symbol can map to many pairs
    Trading Pair Market where the quote originates Part of the market data primary key
    Market Type Market category Use an enum, not free text, to avoid dirty values
    Last Price Price of the most recent trade Must carry a source and timestamp
    Open Price Price at the start of the statistics window Make explicit whether the window is calendar day or rolling
    High / Low Extremes within the window Monotonic—extremes only widen, never shrink
    Change % Derived metric Computed from last and open; never ingested directly
    Market Cap Derived metric Depends on the circulating-supply definition; mark as an estimate
    Update Time Data time Distinguish “ingestion time” from “quote time”

    The most important rule: derived fields are always computed server-side; never trust externally supplied values for them. Change percentage, market cap, and ranking are all derivable quantities. If you allow external writes for them, you will inevitably produce self-contradictory data such as “the last price didn’t change but the change percentage jumped.”

    A sample data structure:

    1. from dataclasses import dataclass
    2. @dataclass(frozen=True)
    3. class Quote:
    4. symbol: str # Asset symbol
    5. pair: str # Trading pair
    6. market_type: str # Market type enum
    7. last: float # Last price
    8. open: float # Window open price
    9. high: float # Window high
    10. low: float # Window low
    11. quote_ts: int # Quote time (ms)
    12. ingest_ts: int # Ingestion time (ms)
    13. @property
    14. def change_pct(self) -> float:
    15. if self.open == 0:
    16. return 0.0
    17. return (self.last - self.open) / self.open * 100.0

    3. The Ingestion Layer: Dual Channels—Full Snapshots Plus Incremental Streams

    Production market data typically comes from two kinds of sources: periodic full snapshots (poll all symbols’ current state on a schedule) and incremental push streams (only the changes). Both must coexist, for a simple reason: incremental streams drop packets and disconnect; full snapshots are the only reliable reconciliation baseline.

    The recommended dual-channel strategy:

    1. Incremental first: use the stream for low-latency updates to the last price and interval extremes;
    2. Snapshots as a safety net: pull a full snapshot at a fixed interval (e.g., every 30 seconds or every 5 minutes) to repair missed updates, correct extremes, and rebuild rankings;
    3. Monotonic merging: when merging, follow the rules “extremes only widen” and “last price goes to the newer timestamp.”
    1. def merge(old: Quote, new: Quote) -> Quote:
    2. if new.quote_ts <= old.quote_ts:
    3. return old # Drop stale and duplicate data
    4. return Quote(
    5. symbol=new.symbol, pair=new.pair, market_type=new.market_type,
    6. last=new.last,
    7. open=old.open, # Open price is fixed within the window
    8. high=max(old.high, new.high), # Extremes are monotonic
    9. low=min(old.low, new.low),
    10. quote_ts=new.quote_ts,
    11. ingest_ts=new.ingest_ts,
    12. )

    This merge logic is the anti-jitter core of the entire service. It guarantees that state never rolls back, even when upstream events arrive out of order.

    4. Time Semantics: Latency and Freshness

    The most common incidents in market data services aren’t calculation errors—they’re “computing new metrics from stale data.” You must therefore split time into two dimensions and expose both downstream:

    • Quote time: when the data was produced; used for freshness checks;
    • Ingestion time: when the data entered your system; used for end-to-end latency.

    Make freshness an explicit contract. For example, mark any symbol not updated for more than N seconds as stale, and let downstream consumers hide it or de-emphasize it—rather than continuing to display an outdated price.

    Window boundaries must also be unified: a calendar-day boundary at 00:00 versus a rolling 24-hour window produces significantly different change percentages. Pin the definition down in the API documentation so clients don’t each interpret it their own way.

    5. Computation and Derived Metrics: Consistency of Definitions Comes First

    Derived metrics must satisfy three properties: deterministic (same input, same output), replayable (historical raw data reproduces the value computed at the time), and explainable (every number traces back to a source).

    • Change %: (last - open) / open × 100%; return 0 rather than raising when open is zero;
    • Interval extremes: maintained monotonically by the merge logic, never overwritten externally;
    • Market cap: price × circulating supply; the supply definition must be labeled as an estimate with a configurable update frequency;
    • Ranking: sorted by market cap descending; introduce a small floating-point tolerance in comparisons so boundary jitter doesn’t cause ranks to flip back and forth.

    Floating-point precision is especially sensitive in price scenarios. Two practical approaches: store everything as fixed-point or integer minimal units (e.g., integers representing the “minimum price tick”), or format uniformly to a fixed number of decimal places at the presentation layer. Never round at different layers with different precision—that produces reconciliation mismatches you can never align.

    6. Storage and Push: Separate Read and Write Paths

    Market data workloads are characterized by high write volume, high read volume, and tiny per-record size, which suits a read/write-separated architecture:

    • Hot path: in-memory state (an in-process shared snapshot or a distributed cache) holds the latest quotes for millisecond-level reads;
    • Warm path: a time-series database or message queue carries change events for downstream subscription and incremental computation;
    • Cold path: periodic dumps to object storage for historical replay, audits, and model training;
    • Push: use long-lived connections to push increments to front ends, sending only on value changes, with a version number or timestamp so clients can discard stale packets.

    The push side must implement coalescing throttling: when change frequency exceeds push capacity, send the latest state at fixed intervals instead of queuing every update. This is the key to guaranteeing “eventually consistent and always newest.”

    7. Observability and Disaster Recovery

    A market data service must ship with its own dashboards, covering at minimum:

    • End-to-end latency percentiles (P50/P95/P99);
    • Time since the last update per symbol; alert when it exceeds a threshold;
    • Merge discard rate (proportion of stale packets); a spike usually signals clock or connectivity problems;
    • Extreme-value anomaly detection: trigger manual review when the last price deviates from interval extremes beyond a configured multiple;
    • Ingestion success rate and reconnect counts.

    For disaster recovery, follow the “multiple sources, graceful degradation” principle: automatically fail over to a backup source when the primary is unavailable; when all sources are down, enter stale degraded mode and explicitly stop updating rather than continuing to emit questionable numbers. Keep replayable copies of all raw messages so that after recovery you can recompute in time order and produce results consistent with new data.

    8. Deployment and Compliance Notes

    All of the above can be built entirely on general-purpose cloud infrastructure: a container platform hosts stateless ingestion and computation instances, a message queue handles event distribution and load leveling, a time-series database and object storage tier hot and cold data, and logging plus monitoring handle observability, with a configuration center distributing definition parameters. Autoscaling should be driven by two dimensions—the number of tracked symbols and the number of push connections—rather than CPU alone.

    Finally, be clear about boundaries: a market data service is responsible only for accurate, timely, traceable data. All metrics are objective computational results and do not constitute investment advice. Where circulating supply, market cap, or other estimated definitions are involved, explicitly flag the estimate nature and update time at the API layer to prevent misuse downstream.

    In summary, a reliable market data service = strict field semantics + monotonic merge rules + dual-timestamp governance + a read/write-separated architecture + comprehensive observability. Get these five things right, and the two most common problems—data jitter and definitional disputes—can be eliminated systematically.