Real-Time Market Data Engineering: Governance and Architecture Practices

    This article breaks down the engineering challenges of real-time market data, a data type defined by high event density, rapid value decay, and strict causal ordering. It explains how to build a latency budget across ingestion, transport, processing, and publishing; how to merge snapshots and deltas using monotonic sequence numbers; how to design partitioning and fan-out for one-to-many distribution; and how to choose between compression and delta encoding. It also covers unified data contracts, tiered degradation and bulkhead isolation, observability metrics, and cost control, ending with a recommended implementation order.

    1. Introduction: The Engineering Challenge of Market Data

    Market data is a data type where high frequency, time-series semantics, strong consistency, and low latency coexist. Compared with typical business data, it has three distinctive characteristics. First, it is event-dense: peak message rates can reach hundreds of thousands of messages per second. Second, its value decays quickly: the analytical value of the data drops significantly after a few milliseconds. Third, it has strict causal constraints: deriving subsequent state depends on the correct preceding order, and any single out-of-order or duplicate message can corrupt downstream metrics.

    Because of this, the design goal of a market data system is usually not “store the data,” but “ensure that every consumer sees a correct state sequence within an acceptable latency.” This article breaks down the technical layers that matter for that goal.

    2. Latency Budget: Layer First, Then Optimize

    The most common mistake in low-latency optimization is starting with micro-tuning. A more effective approach is to first establish a latency budget and split the end-to-end path into measurable stages:

    1. Ingestion latency: protocol parsing, authentication, timestamping, and entry into the internal channel on the data source side;
    2. Transport latency: queuing and fan-out time inside the channel, strongly related to partition strategy and batch parameters;
    3. Processing latency: incremental composition, metric computation, risk checks, and other compute stages;
    4. Publishing latency: writing results to the distribution layer and pushing them to terminals.

    With a layered budget, optimization has a clear target. In practice, the largest share of the path is often not the compute logic itself, but queuing and serialization overhead. For example, when batch parameters are set too large, average latency may look unchanged, but P99 and P99.9 degrade significantly, and this tail latency is exactly what affects user experience.

    Instrument each stage to record elapsed time, and use percentiles rather than averages as the core metric:

    1. # Example: per-stage instrumentation that reports percentiles instead of averages
    2. from dataclasses import dataclass, field
    3. import time, statistics
    4. @dataclass
    5. class StageTimer:
    6. samples: dict = field(default_factory=lambda: {"ingest": [], "calc": [], "publish": []})
    7. def record(self, stage: str, cost_ms: float):
    8. self.samples.setdefault(stage, []).append(cost_ms)
    9. def report(self):
    10. for stage, vals in self.samples.items():
    11. if not vals:
    12. continue
    13. s = sorted(vals)
    14. p99 = s[int(len(s) * 0.99) - 1]
    15. print(f"{stage}: count={len(s)} p50={statistics.median(s):.2f}ms p99={p99:.2f}ms max={s[-1]:.2f}ms")

    3. Ordering Consistency: Merge Semantics for Snapshots and Deltas

    Market data consumers usually receive two kinds of data at the same time: full snapshots (which describe the state at a given moment) and incremental pushes (which describe changes to the state). The most common mistake when merging them is “overwriting newer state with an older snapshot.”

    Correct merging must rely on a monotonic sequence number, not arrival order:

    1. class QuoteBook:
    2. def __init__(self):
    3. self._seq = -1
    4. self._state = {}
    5. def apply_snapshot(self, seq: int, state: dict):
    6. # Accept a snapshot only when it is newer than the current sequence
    7. if seq > self._seq:
    8. self._state = dict(state)
    9. self._seq = seq
    10. def apply_delta(self, seq: int, patch: dict):
    11. # Discard out-of-order or duplicate older deltas
    12. if seq <= self._seq:
    13. return False
    14. self._state.update(patch)
    15. self._seq = seq
    16. return True

    This logic reflects two key principles:

    • Idempotency: redelivering a message with the same sequence number produces no side effects;
    • Monotonicity: state can only move forward, so network jitter or reconnect replays never cause state regression.

    On top of this, you also need gap detection. When a consumer detects a discontinuity in sequence numbers, the correct strategy is not to continue on a best-effort basis, but to actively request a fresh snapshot to rebuild state. This “fail fast + targeted recovery” design is much safer than letting a corrupted state spread silently.

    4. Partitioning and Fan-Out in the Message Channel

    Market data distribution is essentially a one-to-many broadcast problem. As the number of subscribers grows, having each subscriber pull independently makes upstream pressure grow linearly with the subscriber count. Two mechanisms are then needed:

    • Tiered distribution: upstream communicates with only a small number of relay nodes, and the relays handle fan-out to subscribers, moving fan-out cost from the core path to the edge;
    • Subscription filtering: push filter conditions down to a point close to subscribers so that irrelevant data does not consume core bandwidth. For example, if a terminal only cares about a few symbols, there is no need to push the full market data stream to it.

    For partitioning strategy, you need to trade off between two extremes. Hashing by symbol gives good load balancing but scatters correlated events from the same moment. Partitioning by business dimension preserves logical relationships between events but can create hotspots. A common compromise in practice is grouping by symbol + ordering guarantees within each group, which maintains strict ordering inside a single symbol while allowing different symbols to be processed in parallel.

    5. Transport Efficiency: Snapshot Compression and Delta Encoding

    Market data has extremely high temporal locality: the state at two adjacent moments usually differs very little. This makes delta encoding the most cost-effective optimization:

    Encoding Use Case Characteristics
    Raw JSON Debugging, early prototypes Readable, but large size and parsing overhead
    Binary serialization Production main path Small size, fast parsing, requires contract maintenance
    Dictionary/bitset compression Sparse structured data High compression ratio, requires extra decoding logic
    Delta differencing Highly similar adjacent states Smallest transfer volume, depends on ordering guarantees

    Note that compression is not unconditionally beneficial. There is a trade-off between CPU and bandwidth: a higher compression ratio usually means higher compute cost, so in scenarios with ample bandwidth but tight compute, disabling some compression can actually yield lower end-to-end latency. This trade-off must be decided from measured data, not from general rules of thumb.

    6. Unified Data Contract

    Market data systems often serve consumers across multiple technology stacks. Inconsistent field naming, inconsistent units (for example, prices as integer cents versus floating-point dollars), and unclear timestamp time zones and precision are all long-term maintenance costs.

    The recommended approach is declarative contract + code generation, making the contract the single source of truth:

    1. syntax = "proto3";
    2. message QuoteTick {
    3. int64 seq = 1; // Monotonic sequence number, used for out-of-order detection
    4. string symbol = 2; // Symbol identifier
    5. int64 price_minor = 3; // Expressed in the smallest currency unit to avoid floating-point error
    6. int64 size = 4; // Quantity
    7. int64 exchange_ts = 5; // Exchange timestamp (milliseconds)
    8. int64 ingest_ts = 6; // Local ingestion timestamp (milliseconds)
    9. }

    Several design decisions in this definition are worth highlighting:

    1. Represent amounts as integer minor units. Floating-point numbers accumulate error after repeated arithmetic, so monetary fields in financial data should use fixed-point integers;
    2. Keep both the source timestamp and the ingestion timestamp. The difference between them is the ingestion latency, the most direct signal of link health;
    3. Put the sequence number first. The sequence number is the basis of all consistency decisions and should not be an optional field.

    7. High Availability and Failure Degradation

    Availability design for a market data path must answer one question clearly: when a dependency is unavailable, how far should the business degrade?

    Common strategies are tiered:

    • Tier 1 degradation: latency rises but the path stays complete, and terminals display a latency marker;
    • Tier 2 degradation: pushes for some symbols stop, and only core symbols remain;
    • Tier 3 degradation: only server-side snapshot queries are served, and active pushes stop.

    For implementation, apply bulkhead isolation to external dependencies: assign separate connection pools, thread pools, and timeout budgets per data category so that a single source failure cannot exhaust all resources. Also, all timeouts must be explicit and bounded; unbounded waiting is forbidden.

    1. import threading, queue
    2. class IsolatedChannel:
    3. """Assign an independent queue and capacity limit per data source to prevent failure propagation"""
    4. def __init__(self, name: str, capacity: int = 10_000):
    5. self.name = name
    6. self.q = queue.Queue(maxsize=capacity)
    7. def submit(self, item, timeout: float = 0.05):
    8. try:
    9. self.q.put_nowait(item) # Non-blocking submit; drop and count when full
    10. return True
    11. except queue.Full:
    12. self.dropped += 1
    13. return False

    Backpressure handling also matters. When downstream consumption capacity is insufficient, the system has only three options: block upstream, drop messages, or buffer to disk. Market data scenarios usually adopt “drop + count + snapshot fallback,” because stale data has no value, but the dropping behavior must be observable.

    8. Observability: Make the Path Self-Explaining

    The difficulty of troubleshooting a market data system is that problems often happen within milliseconds and are hard to reproduce afterward. Observability must therefore be built during the design phase and cover at least three metric categories:

    • Latency: per-stage percentile latency, and the distribution of the difference between source and ingestion timestamps;
    • Completeness: sequence gap counts, snapshot recovery counts, out-of-order drop rate;
    • Capacity: channel backlog depth, drop counts, changes in the number of fan-out nodes.

    Combined with distributed tracing, you can stitch together the full path of a message and quickly locate the specific stage when a problem occurs, instead of relying on guesswork.

    9. Balancing Cost and Architecture

    The largest costs in a market data path usually come from two places: bandwidth and in-memory resident state. Effective cost controls include:

    1. Subscription granularity control: subscribe precisely to what each terminal actually needs, avoiding full broadcast;
    2. Tiered retention: keep high-frequency data for a short window in the hot layer, sink cold data to object storage, and query it back when needed;
    3. Sampling and aggregation: monitoring metrics do not need to be recorded one by one and can be pre-aggregated at the gateway;
    4. Elastic scaling: scale the ingestion layer by connection count and the compute layer by message rate, keeping the two decoupled.

    10. Conclusion

    The core of engineering governance for market data is not choosing a particular component, but making the semantics explicit: how ordering is guaranteed, how state is merged, how failures degrade, and how latency is measured. Once these semantics are clear, the concrete implementation choices (message queues, stream processing engines, time-series storage, containerized deployment, or general cloud infrastructure such as that provided by Baidu AI Cloud) are just replaceable implementation details.

    The recommended rollout order is: first define a unified data contract and sequence number semantics, then set up latency instrumentation and percentile observability, then complete the partitioning and fan-out strategy design, and finally introduce compression, degradation, and cost optimization step by step. Following this order yields verifiable gains at each step and avoids blind tuning without observability.