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:
- 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.
- 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.
- 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:
- 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.
- 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.
- 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:
{"changeMode": "rolling_24h_local","basePriceSource": "first_valid_tick_in_window","updateTime": "2026-11-24T11:58:39Z"}
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
versionorupdateTimefield so cache and storage consistency can be validated.
Example model:
{"symbol": "ABC/USDT","marketType": "CRYPTO","baseAsset": "ABC","quoteAsset": "USDT","lastPrice": "0.08879","openPrice24h": "0.08829","highPrice24h": "0.09268","lowPrice24h": "0.08759","priceChange24h": "0.0004994","priceChangePercent24h": "0.566","marketCap": "88870800","rank": 168,"updateTime": "2026-11-24T11:58:39Z","version": 17829364}
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:
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:
{"source": "exchange_a","symbol": "ABC/USDT","eventTime": 1764000000000,"receiveTime": 1764000000123,"seq": 88213}
3.2 Field Validation Rules
At minimum, validate the following before writing to the message queue:
- Required fields:
symbol,lastPrice,eventTime, andsourcemust not be empty. - Format checks:
symbolmust match theBASE/QUOTEform, prices must be positive, and timestamps must not be implausibly far in the future. - 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.
- Time checks:
eventTimemust 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. - 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:
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:
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
symbolto 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:
- Use event time: key off the quote’s own
eventTimerather than the system’s receive time. - Set watermarks: allow a degree of out-of-order arrival, and route records beyond the tolerance to a late-data path.
- Expire old window data: a sliding window must evict expired records by time.
- Roll the open price: when the window slides, the open price should become the earliest valid price inside the window.
- 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:
from collections import dequefrom decimal import Decimal, InvalidOperationclass EventTime24hWindowDemo:def __init__(self, window_seconds=86400, late_tolerance=300):self.window_seconds = window_secondsself.late_tolerance = late_toleranceself.samples = deque() # (event_time, Decimal(price))self.watermark = 0def _to_decimal(self, value):try:price = Decimal(str(value))except InvalidOperation:return Noneif price <= 0:return Nonereturn pricedef push(self, event_time, price):price = self._to_decimal(price)if price is None or event_time is None:return {"status": "dropped", "reason": "invalid_field"}if event_time < self.watermark - self.late_tolerance:return {"status": "dropped", "reason": "too_late"}if event_time < self.watermark:# Do not write back into the online snapshot; route to a late-data channel for offline correctionreturn {"status": "late", "reason": "side_output"}# The online path expects approximately ordered event times; severe disorder belongs to a stream processor or the late-data side outputself.samples.append((event_time, price))self.watermark = event_timecutoff = event_time - self.window_secondswhile self.samples and self.samples[0][0] < cutoff:self.samples.popleft()if not self.samples:return {"status": "empty", "reason": "no_valid_tick_in_window"}open_price = self.samples[0][1]latest = self.samples[-1][1]high = max(p for _, p in self.samples)low = min(p for _, p in self.samples)change = latest - open_pricechange_pct = (change / open_price * Decimal("100")) if open_price else Decimal("0")return {"status": "ok","eventTime": event_time,"openPrice24h": str(open_price),"lastPrice": str(latest),"highPrice24h": str(high),"lowPrice24h": str(low),"priceChange24h": str(change),"priceChangePercent24h": str(change_pct.quantize(Decimal("0.001"))),"windowStart": self.samples[0][0],"windowEnd": self.samples[-1][0]}
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
{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:
- Prevent penetration: cache a null value or a short-TTL null marker for symbols that do not exist.
- Prevent breakdown: when a hot key expires, use a mutex lock, logical expiration, or singleflight so only one request goes to the source.
- Prevent avalanche: randomize TTLs, use multi-level caching, and fall back to stale data.
- Version validation: check
updateTimeorversionbefore 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
symboland time, for examplesymbol + 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
updateTimeorversionto 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
staleflag 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
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
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:
- Request arrives.
- Look up cache.
- On a hit, return immediately.
- On a miss, acquire the source-fetch lock.
- Only the lock holder fetches from the source.
- On success, backfill the cache and return.
- 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:
- Cache failure: verify merged source fetching, rate limiting, and stale-data degradation.
- Message queue backlog: verify scaling out, dropping non-critical quotes, and catching up after recovery.
- Database failure: verify cache fallback and write buffering.
- Data source disconnect: verify multi-source failover and heartbeat detection.
- 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:
- Accuracy first: use fixed-point or string prices, define the change-percentage rule explicitly, and compute aggregations over event-time windows.
- 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.
- 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.
