Real-Time Market Data System Architecture: A Practical Engineering Guide

    This article walks through the design of a real-time market data system from the ground up: how to define the data model and the 24-hour change calculation rules, how to build a high-concurrency ingestion layer with validation, idempotency and queue partitioning, how to run event-time window aggregation, how to layer caching with hot, warm and cold storage, and how to expose query and push APIs with rate limiting and graceful degradation. It also covers observability metrics, alert tiers, failure drills, a troubleshooting checklist for issues such as cache breakdown, message backlogs and inconsistent change percentages, and compliance considerations for displaying market data.

    Real-Time Market Data System Architecture: A Practical Engineering Guide

    1. Where to Start: Choosing an Architecture for Real-Time Market Data

    The core goal of a real-time market data system is to deliver market snapshots to users with acceptable latency and acceptable stability, under conditions of high-frequency updates, very large numbers of connections, and strong consistency requirements. The questions that usually come up are: how should a real-time market data system be architected, how do you keep the 24-hour change accurate, what typically causes latency, how do you scale out when messages back up, and how do you avoid cache breakdown.

    Before choosing an architecture, three constraints need to be pinned down:

    1. Business definition constraints: is the displayed value the exchange’s official 24-hour change, or a locally computed rolling-window value? The two can disagree, and the choice must be stated in the API documentation.
    2. Consistency constraints: do the latest price, high, and low require strong consistency? If second-level eventual consistency is acceptable, caching and asynchronous persistence can lower the cost.
    3. Traffic scale constraints: a few hundred trading pairs with low-frequency quotes, or tens of thousands of trading pairs with sub-second updates? The scale leads to very different ingestion and storage choices.

    In general, a real-time market data system splits into six stages: data ingestion, message buffering, real-time computation, tiered storage, cache service, and presentation. Each layer is described below with an implementable design.

    2. Data Model and Change-Percentage Definitions

    2.1 Core Fields

    A market data record normally carries identity information, price information, change information, scale information, and metadata:

    Category Field examples Purpose
    Identity Asset code, trading pair, market type Uniquely identifies the instrument
    Price Latest price, open, high, low Describes current and interval prices
    Change 24-hour price change, 24-hour change percentage Derived from the first and last prices in the interval
    Scale Market cap, market cap rank Reflects the size and position of the asset
    Metadata Quote currency, update time Used for explanation, tracing, and auditing

    In engineering practice, it is worth writing down which of three change-percentage definitions the system implements:

    1. Source-provided definition: use the 24-hour open price and change percentage supplied by the exchange or data provider directly, with no recomputation on your side.
    2. Local rolling-window definition: with the current time as T, take the earliest valid quote in [T-24h, T] as the open price and the latest quote as the latest price.
    3. Trading-day definition: compute over the natural day, UTC day, or trading day as defined by the data source.

    If the definition is left unstated, the change percentage may not match what users see on the exchange’s own page. A recommended approach is to add explicit fields to the response, for example:

    1. {
    2. "changeMode": "rolling_24h_local",
    3. "basePriceSource": "first_valid_tick_in_window",
    4. "updateTime": "2026-11-24T11:58:39Z"
    5. }

    2.2 Price Precision and Storage Representation

    Price fields should not use floating point. Use strings or fixed-point values instead. Floating point accumulates error after repeated addition, subtraction, multiplication, and division, which makes it especially unsuitable for financial market data. Recommended conventions:

    • External transmission: strings, for example "0.08879".
    • Internal computation: Decimal, BigDecimal, or scaled integers.
    • Timestamps: UTC ISO 8601 strings or millisecond timestamps, consistently.
    • Version tracking: add a version or updateTime field so cache and storage consistency can be validated.

    Example model:

    1. {
    2. "symbol": "ABC/USDT",
    3. "marketType": "CRYPTO",
    4. "baseAsset": "ABC",
    5. "quoteAsset": "USDT",
    6. "lastPrice": "0.08879",
    7. "openPrice24h": "0.08829",
    8. "highPrice24h": "0.09268",
    9. "lowPrice24h": "0.08759",
    10. "priceChange24h": "0.0004994",
    11. "priceChangePercent24h": "0.566",
    12. "marketCap": "88870800",
    13. "rank": 168,
    14. "updateTime": "2026-11-24T11:58:39Z",
    15. "version": 17829364
    16. }

    3. High-Concurrency Data Ingestion Architecture

    The goal of the ingestion layer is to absorb high-frequency quotes reliably while performing validation, normalization, idempotency, and buffering. The typical path is:

    1. data source subscription → field validation → normalization → idempotent deduplication → message queue → stream consumption

    3.1 Data Source Integration Options

    Different sources integrate differently. The common options are:

    • WebSocket subscription: suited to real-time quote pushes. The client must maintain heartbeats, reconnection, and resubscription from a checkpoint.
    • REST polling: suited to feeds with relaxed latency requirements. A backoff strategy is needed so the data source is not overwhelmed.
    • Private protocol or dedicated line: suited to institutional-grade feeds. Requires network failover and multi-source redundancy.

    When integrating, keep the original source fields:

    1. {
    2. "source": "exchange_a",
    3. "symbol": "ABC/USDT",
    4. "eventTime": 1764000000000,
    5. "receiveTime": 1764000000123,
    6. "seq": 88213
    7. }

    3.2 Field Validation Rules

    At minimum, validate the following before writing to the message queue:

    1. Required fields: symbol, lastPrice, eventTime, and source must not be empty.
    2. Format checks: symbol must match the BASE/QUOTE form, prices must be positive, and timestamps must not be implausibly far in the future.
    3. Range checks: when a price deviates too far from the current reference price, route it to a dead-letter queue rather than publishing it live.
    4. Time checks: eventTime must not exceed the server’s current time by more than a tolerance, for example 30 seconds, and must not be too old, for example earlier than 24 hours before the current time.
    5. Numeric precision: retain at most the precision the source provides, for example 8 or 10 decimal places; truncate or reject anything beyond it.

    3.3 Idempotency and Deduplication Keys

    High-frequency feeds produce duplicates easily, so an idempotency key is recommended:

    1. dedup_key = source + ":" + symbol + ":" + eventTime + ":" + seq

    If the source has no seq, use source + symbol + eventTime + price as a weak idempotency key. Idempotency state can be stored in Redis or an in-memory database, with a TTL that covers the maximum retransmission window, for example 5 to 30 minutes.

    3.4 Message Queue Partition Keys

    To preserve ordering for a given trading pair, the partition key should be:

    1. partition_key = marketType + ":" + symbol

    For example CRYPTO:ABC/USDT. Quotes for the same trading pair then land in the same partition, and consumers can process them in order.

    If a single trading pair generates so much traffic that it creates a partition hotspot, the options are:

    • Hash-shard by symbol.
    • Split extremely high-frequency trading pairs into several sub-partitions.
    • Perform a secondary aggregation over windows for the same symbol to reduce raw write pressure.

    3.5 Consumer Scaling and Backlog Alerts

    Consumers should scale out automatically based on message backlog. Example thresholds:

    Metric Example threshold Action
    Consumer lag Above 100,000 messages Trigger a scaling evaluation
    Backlog growing for 5 minutes Consumption capacity below 50% of production Scale out consumer instances
    Single-partition lag More than 3x the partition average Investigate a partition hotspot
    Write failure rate Above 1% Pause non-critical writes and alert

    When scaling out, add consumer instances first, but make sure there are enough partitions. If the partition count is lower than the number of consumer instances, the extra instances sit idle.

    4. Real-Time Computation and Aggregation

    Change percentage, high, and low are fundamentally aggregations over a price series within a time window. An initial design that uses deque(maxlen=window_size) to simulate 24 hours by sample count is semantically wrong: a 24-hour window should be defined by event time, not by a fixed number of samples.

    In production, use a stream processing framework such as Flink, Spark Structured Streaming, or a custom event-time aggregator. The core principles are:

    1. Use event time: key off the quote’s own eventTime rather than the system’s receive time.
    2. Set watermarks: allow a degree of out-of-order arrival, and route records beyond the tolerance to a late-data path.
    3. Expire old window data: a sliding window must evict expired records by time.
    4. Roll the open price: when the window slides, the open price should become the earliest valid price inside the window.
    5. Guard against empty windows: if no valid data exists in the window, return an empty state or mark the data as stale.

    The following example aggregates over an event-time window and is intended only to illustrate the idea:

    1. from collections import deque
    2. from decimal import Decimal, InvalidOperation
    3. class EventTime24hWindowDemo:
    4. def __init__(self, window_seconds=86400, late_tolerance=300):
    5. self.window_seconds = window_seconds
    6. self.late_tolerance = late_tolerance
    7. self.samples = deque() # (event_time, Decimal(price))
    8. self.watermark = 0
    9. def _to_decimal(self, value):
    10. try:
    11. price = Decimal(str(value))
    12. except InvalidOperation:
    13. return None
    14. if price <= 0:
    15. return None
    16. return price
    17. def push(self, event_time, price):
    18. price = self._to_decimal(price)
    19. if price is None or event_time is None:
    20. return {"status": "dropped", "reason": "invalid_field"}
    21. if event_time < self.watermark - self.late_tolerance:
    22. return {"status": "dropped", "reason": "too_late"}
    23. if event_time < self.watermark:
    24. # Do not write back into the online snapshot; route to a late-data channel for offline correction
    25. return {"status": "late", "reason": "side_output"}
    26. # The online path expects approximately ordered event times; severe disorder belongs to a stream processor or the late-data side output
    27. self.samples.append((event_time, price))
    28. self.watermark = event_time
    29. cutoff = event_time - self.window_seconds
    30. while self.samples and self.samples[0][0] < cutoff:
    31. self.samples.popleft()
    32. if not self.samples:
    33. return {"status": "empty", "reason": "no_valid_tick_in_window"}
    34. open_price = self.samples[0][1]
    35. latest = self.samples[-1][1]
    36. high = max(p for _, p in self.samples)
    37. low = min(p for _, p in self.samples)
    38. change = latest - open_price
    39. change_pct = (change / open_price * Decimal("100")) if open_price else Decimal("0")
    40. return {
    41. "status": "ok",
    42. "eventTime": event_time,
    43. "openPrice24h": str(open_price),
    44. "lastPrice": str(latest),
    45. "highPrice24h": str(high),
    46. "lowPrice24h": str(low),
    47. "priceChange24h": str(change),
    48. "priceChangePercent24h": str(change_pct.quantize(Decimal("0.001"))),
    49. "windowStart": self.samples[0][0],
    50. "windowEnd": self.samples[-1][0]
    51. }

    If stronger consistency is required in production, this single-machine sample should not be the final design. Instead, move the logic onto a stream processing engine that manages the following centrally:

    • Event-time windows.
    • Watermarks.
    • Late-data side outputs.
    • State backend persistence.
    • Exactly-once or at-least-once semantics.
    • Window triggering and late-update policies.

    5. Storage and Cache Tiering Strategy

    Market data has both hot real-time characteristics and cold historical characteristics. If traffic is modest and the retention period is short, “cache plus database” is enough. If data volume is large and historical queries are common, tiered storage is the better fit.

    5.1 Hot Tier: Cache

    The hot tier holds the latest snapshot for each instrument. The workload is read-heavy with few writes, which suits an in-memory cache. Recommended setup:

    • Cache key: quote:latest:{marketType}:{symbol}
    • Cache value: the full snapshot as JSON.
    • TTL: 5 to 15 seconds, or update-driven invalidation.
    • Null caching: for instruments that do not exist or have halted trading, cache a null value for 5 to 30 seconds to avoid penetration.
    • TTL jitter: add random jitter when writing in bulk so entries do not expire simultaneously.

    Cache protection strategies:

    1. Prevent penetration: cache a null value or a short-TTL null marker for symbols that do not exist.
    2. Prevent breakdown: when a hot key expires, use a mutex lock, logical expiration, or singleflight so only one request goes to the source.
    3. Prevent avalanche: randomize TTLs, use multi-level caching, and fall back to stale data.
    4. Version validation: check updateTime or version before backfilling the cache so old data does not overwrite new data.

    5.2 Warm Tier: Database or Time-Series Store

    The warm tier holds recent high-frequency quotes for interval statistics, replay, and auditing. Design points:

    • Batched writes: batch 100 to 500 records or 500 milliseconds to reduce database pressure.
    • Partitioned indexes: partition by symbol and time, for example symbol + yyyy-mm-dd.
    • Indexed fields: symbol, eventTime, source, updateTime.
    • Unique key: source + symbol + eventTime + seq, used for idempotent writes.
    • Retention period: the last 7, 30, or 90 days, depending on query needs.

    5.3 Cold Tier: Object Storage Archive

    The cold tier holds historical data at low cost and serves offline analysis and auditing. Recommended:

    • Format: Parquet, ORC, or compressed CSV.
    • Compression: Zstd or Snappy.
    • Directory layout: date=2026-11-24/symbol=ABC-USDT/part-0001.parquet
    • Metadata: schema version, covered time range, checksum.
    • Archive cadence: daily or hourly.
    • Verification: generate a checksum after writing and verify integrity on read.

    5.4 Consistency Across Tiers

    Typical problems in market data pipelines are a stale cache, a fresher database, and gaps in the archive. Recommended practices:

    • Use updateTime or version to decide which copy is newer.
    • Check whether the database version is newer before backfilling the cache.
    • Let archive jobs only archive data whose write has been confirmed complete.
    • Run cache-versus-database version comparisons for core trading pairs.
    • If eventual consistency is acceptable, return a stale flag in the API response.

    6. Serving and Presentation Layer

    The serving layer is also read-heavy, so it should read from cache first and avoid letting large volumes of requests reach the database. The recommended API surface follows.

    6.1 Single-Instrument Quote Query

    1. GET /v1/quotes/{symbol}

    Returns the latest snapshot. On a cache hit, return it directly; on a miss, go through the merged source-fetch path.

    6.2 Batch Quote Query

    1. GET /v1/quotes?symbols=ABC/USDT,DEF/USDT,GHI/USDT

    The batch endpoint should cap the number of symbols per request, for example 20 or 50. Suggested internal implementation:

    • Look up all symbols in cache in one batch call.
    • Batch-fetch only the misses.
    • Merge results and backfill the cache.
    • Report partial failures explicitly instead of failing the whole request.

    6.3 Push and Polling Backoff

    High-frequency instruments can use WebSocket pushes; low-frequency ones can be polled on a schedule. Suggested client backoff policy:

    • Wait 1 second after the first failure.
    • Wait 2 seconds after the next failure.
    • Wait 5 seconds after the one after that.
    • Wait 30 seconds after repeated failures.
    • Gradually shorten the interval once the connection recovers.

    Server-side push needs heartbeat detection, connection limits, message sequence numbers, and the ability to backfill after a disconnect.

    6.4 Cache-Aside with Merged Source Fetch

    The read path should be:

    1. Request arrives.
    2. Look up cache.
    3. On a hit, return immediately.
    4. On a miss, acquire the source-fetch lock.
    5. Only the lock holder fetches from the source.
    6. On success, backfill the cache and return.
    7. On failure, return degraded data or an error code.

    6.5 Rate Limiting, Authentication, Timeouts, and Degradation

    The service layer needs protective mechanisms:

    • Authentication: API key, token, or tenant signature.
    • Rate limiting: per user, per endpoint, and per IP.
    • Timeouts: 100 to 300 milliseconds for a single-instrument query.
    • Retries: retry idempotent GET requests once only, to avoid amplifying load.
    • Degradation: when the cache is unavailable, return the most recent snapshot with stale=true.
    • Error codes: a single, consistent set of error code definitions.

    Example error codes:

    Error code Meaning
    INVALID_PARAM Invalid parameters
    AUTH_FAILED Authentication failed
    RATE_LIMITED Request limit exceeded
    QUOTE_NOT_FOUND No quote exists for the instrument
    UPSTREAM_TIMEOUT Upstream timed out
    CACHE_DEGRADED Cache is degraded
    INTERNAL_ERROR Internal error

    7. High Availability and Observability

    A market data system faces end users directly, so it needs clearly defined metrics and alert tiers. The metrics worth watching most closely are listed below.

    7.1 Core Metrics and Thresholds

    Metric Example threshold Notes
    End-to-end latency p95 Below 200 ms From data generation to a queryable result
    Message backlog lag Alert above 100,000 Requires scaling out if sustained for 5 minutes
    Consumption failure rate Alert above 1% Check for dirty data or downstream failures
    Cache hit rate Investigate below 90% Check hot keys, TTL, and key design
    Source-fetch error rate Alert above 2% Check the database or upstream
    Healthy replica count Alert below the expected count Remove automatically and scale out
    Push disconnect rate Alert above 5% Check the network and heartbeats

    7.2 Alert Tiers

    • P0: core quotes unavailable, message queue fully backed up, database not writable.
    • P1: noticeable latency on some trading pairs, sharp drop in cache hit rate, widespread push disconnects.
    • P2: a single unhealthy instance, archive delays, log anomalies while the service remains available.

    7.3 Failure Drills and Degradation Plans

    Before launch, rehearse at least the following:

    1. Cache failure: verify merged source fetching, rate limiting, and stale-data degradation.
    2. Message queue backlog: verify scaling out, dropping non-critical quotes, and catching up after recovery.
    3. Database failure: verify cache fallback and write buffering.
    4. Data source disconnect: verify multi-source failover and heartbeat detection.
    5. Single trading pair hotspot: verify partition splitting and merged aggregation.

    Degradation principles:

    • Protect core trading pairs first.
    • Non-critical assets may update with a delay.
    • When quotes are unavailable, return the most recent snapshot marked as stale.
    • Never keep displaying obviously wrong prices.

    8. Troubleshooting Checklist

    Symptom Common causes Where to look
    Change percentage differs from the exchange Different definition, different window, different open-price source Confirm whether to use the official definition or a local rolling window
    Price precision anomalies Floating point in use Switch to strings or fixed-point values
    High quote latency Message backlog, slow consumption, cache penetration Check lag, scale out, add caching
    Cache breakdown A hot key expired Mutex locks, logical expiration, singleflight
    Out-of-order messages Poor partition key choice or merged multi-source feeds Partition by symbol and use event time
    Partition hotspot Too much traffic for one trading pair Sub-partitions, secondary aggregation, scaling out
    Stale cache data Backfill without version checks Validate with updateTime or version
    Gaps in the archive Writes not confirmed complete Use checksums and completion markers
    Frequent push disconnects Missing heartbeats or network jitter Heartbeats, reconnection, backoff, backfill

    9. Engineering Takeaways and Compliance Notes

    A reliable real-time market data system is fundamentally the coordination of data modeling, idempotent ingestion, event-time computation, tiered storage, cache service, and observable operations. Three principles should hold throughout the design:

    1. Accuracy first: use fixed-point or string prices, define the change-percentage rule explicitly, and compute aggregations over event-time windows.
    2. Timeliness: use a message queue to absorb bursts, stream processing to compute, and caching to reduce read latency, so the latest quote reaches users as quickly as possible.
    3. Stability as a baseline: stateless services, multiple replicas, authentication and rate limiting, degraded responses, and end-to-end monitoring together handle traffic peaks and sudden failures.

    One point deserves particular emphasis: market data is time-sensitive, varies by source, and is subject to licensing restrictions. Any system displaying market data externally should defer to the original data source’s definitions and comply with the relevant data licenses and display requirements. This article discusses technical architecture and engineering implementation only and does not constitute investment advice.