Real-Time Market Data System for Digital Assets: Architecture Design and Engineering Practices
This article walks through the architecture and engineering practices behind a real-time market data system for digital assets. It covers a standardized internal data model, a hybrid pull-and-push ingestion strategy, stateful stream computation for metrics such as 24-hour change and price extremes, layered storage with cold/hot separation, low-latency push delivery with frontend rendering optimizations, and fault-tolerance patterns including multi-source redundancy and end-to-end monitoring. Cloud deployment guidance maps these needs to general-purpose service categories. The design is also transferable to any domain requiring real-time data distribution and visualization, such as finance, energy, and logistics.
1. Background and Problem Definition
Digital asset markets are characterized by round-the-clock trading, frequent price movements, and a large number of participants. The value of market data depends directly on its timeliness and accuracy. A market quote refers to the instantaneous price of a given asset at a specific moment along with derived statistical indicators. It serves as input for trading decisions and as a foundational data source for analytics, risk monitoring, and frontend visualization.
A typical quote record has a fairly universal field structure. The raw data can be abstracted into a general model as follows:
| Field Category | Description | Engineering Focus |
|---|---|---|
| Asset identifier (code/name) | Uniquely identifies an asset | Requires a globally unique key to avoid name collisions |
| Trading pair (quote asset) | e.g., an asset/stablecoin combination | Affects pricing and conversion logic |
| Market type | Distinguishes spot, derivatives, etc. | Determines data scope |
| Last price | The most recent traded price | High-frequency update field |
| 24h change amount / percentage | Difference versus 24 hours ago | Requires a base price for calculation |
| Open / high / low price | Period starting point and price extremes | Requires sliding-window aggregation |
| Market cap | Circulating supply multiplied by price | Depends on external circulating supply data |
| Market cap rank | Position when sorted by market cap | Requires global sorting computation |
| Update time | Data timestamp | Determines data freshness |
The core engineering problem of a market data system can be summarized in a single sentence: how to ingest massive, heterogeneous, high-frequency price data and, after accurate computation and aggregation, reliably push it to tens of thousands of clients with as little latency as possible. This article develops an architecture around that goal.
2. Data Model Design: Field Abstraction and Standardization
Different data sources often differ in field naming, precision, and time format. A unified internal data model must therefore be established above the ingestion layer to perform normalization.
A suggested internal data structure (illustrative):
{"symbol": "A","quote_asset": "USDT","market_type": "SPOT","last_price": 0.06772,"quote_currency": "USD","price_change_24h": 0.002697,"price_change_percent_24h": 4.147,"open_price_24h": 0.06502,"high_price_24h": 0.06971,"low_price_24h": 0.06482,"market_cap": 110000000,"rank": 152,"timestamp": 1764200798000}
Design considerations:
- Unified precision and types: Price fields are best carried as fixed-point numbers or strings (to avoid floating-point errors), then formatted to the required precision at the presentation layer.
- Unified time baseline: All timestamps are normalized to UTC milliseconds, with the frontend rendering them in the user’s local time zone.
- Versioned schema: Because the data structure evolves with the business, fields should carry a version marker to prevent parsing errors between upstream and downstream.
- Separate raw values from computed values: The last price is a raw value, while change percentages and ranks are computed values. The two should be clearly distinguished in the model to support traceability and recomputation.
3. Data Collection and Ingestion: Multiple Sources with a Push-Pull Hybrid
Market data can be collected in two broad ways: polling (pull) and pushing, each suited to different scenarios:
- Polling mode: Request a snapshot endpoint at a fixed interval. Simple to implement and easy to reconcile against a full dataset, but subject to latency and request cost, so it needs to be combined with rate limiting and backoff strategies.
- Push mode: Subscribe to incremental updates over a long-lived connection. Low latency and bandwidth-efficient, but it requires handling reconnection after disconnects, out-of-order messages, and deduplication.
In practice, a “push-primary with polling fallback” hybrid strategy is common:
import asyncioasync def realtime_pipeline():"""Illustrative: push subscription as primary, periodic snapshot calibration as fallback"""async def consume_stream():async for tick in websocket_stream(): # incremental pushyield normalize(tick)async def periodic_snapshot():while True:snapshot = await fetch_snapshot() # full calibrationawait reconcile(snapshot)await asyncio.sleep(5) # periodic calibration to avoid driftawait asyncio.gather(consume_stream(), periodic_snapshot())
The ingestion layer must handle source rate limiting and degradation: automatically fail over to a backup source when a single source misbehaves; and when all sources show excessive latency, return the most recent valid value marked with a timestamp while explicitly informing clients of the data’s “freshness.”
4. Stream Computation and Aggregation: Real-Time Updates for Change and Extremes
Metrics such as the 24-hour change percentage, high, and low are all window aggregation results. There are two implementation paths:
- Stateful stream processing: Maintain per-asset state within a sliding window (starting price, extremes, volume) and update incrementally. High performance.
- Scheduled batch aggregation: Recompute the window at fixed intervals (e.g., every minute). Simple logic, but weaker real-time behavior.
Taking change percentage as an example, the essence of the calculation is:
Change % = (Latest price - Baseline price 24h ago) / Baseline price 24h ago × 100%
Illustrative pseudocode:
def compute_change(latest: Decimal, base_24h: Decimal) -> Decimal:if base_24h == 0:return Decimal("0") # guard against division by zeroreturn (latest - base_24h) / base_24h * 100
For global sorting requirements such as market cap rank, an ordered structure sorted by market cap is typically maintained, and an asset’s rank is updated incrementally when its market cap changes, avoiding the overhead of a full re-sort. All computation logic should be idempotent to handle message replay and duplicate consumption.
5. Layered Storage and Caching Strategy
Market data exhibits a clear hot/cold tiering. The last price is hot data read at high frequency, while historical K-line data and tick-by-tick trades are used for retrospective analysis.
- Hot data (latest snapshot): Kept in an in-memory cache for low read/write latency, serving real-time push and queries.
- Warm data (minute/hour-level aggregates): Written to a time-series database to support efficient range queries over time windows.
- Cold data (historical detail): Archived to object storage at lower cost for auditing and offline analysis.
The key to layered storage is consistency: the snapshot cache must stay in sync with aggregation results. A recommended order is “write the aggregate, then update the cache,” using a version number or timestamp to ensure the cache does not go stale or return dirty reads.
6. Real-Time Push and Frontend Rendering
There are two technical routes for delivering quotes to clients:
- Long-lived connection push (e.g., WebSocket): The server pushes actively over a bidirectional channel, suited to high-frequency quotes.
- One-way event stream (e.g., SSE): The server pushes in one direction; lightweight to implement and suited to read-only quote dashboards.
Frontend rendering must address the performance problems caused by high-frequency refreshes. Common techniques include:
- Throttling and batching: Merge multiple updates within the same render frame to avoid layout jitter.
- Incremental rendering: Update only the fields that change (e.g., refresh only the last-price figure) rather than redrawing the entire table.
- Backpressure awareness: When the client cannot keep up with the push rate, discard stale intermediate frames and keep only the latest state.
7. High Availability and Fault-Tolerance Design
A market data system’s stability directly determines business credibility. Key safeguards include:
- Multi-source redundancy: Integrate at least two independent data sources and fail over automatically when the primary source fails.
- Timeouts and retries: Set timeouts, a limited number of retries, and exponential backoff on all external calls to prevent cascading failures.
- Degradation strategy: Under extreme conditions, return a cached snapshot annotated with its data time and status.
- End-to-end monitoring: Monitor and alert on metrics such as collection latency, computation time, and push success rate, notifying on-call staff promptly when anomalies occur.
8. Cloud Deployment Recommendations
Building this kind of system in the cloud lets you reuse mature, general-purpose product categories from the industry and reduce the cost of self-hosting:
- Message queue: Absorb high-frequency quote messages, smoothing traffic spikes and decoupling upstream from downstream.
- Container platform: Deploy collection, computation, and push services in a containerized way, with elastic scaling to handle market peaks.
- Object storage: Archive historical quote detail at low cost for offline analysis.
- Logging service: Centrally collect and search runtime logs to speed up problem diagnosis.
- Monitoring and alerting: Visualize system health and business metrics and provide proactive alerts.
Taking Baidu AI Cloud as an example, its general-purpose cloud product categories—containers, message queues, object storage, logging, and monitoring/alerting—can support a full implementation of this architecture; the specific selection should be evaluated against real-time performance, throughput, and cost.
9. Conclusion
The core of a real-time market data system lies in balancing three qualities: low latency, accuracy, and stability. Through unified field modeling, a hybrid push-pull ingestion approach, stateful stream computation, hot/cold layered storage, push delivery optimized for high-frequency scenarios, and fault tolerance based on multi-source redundancy and end-to-end monitoring, developers can build a scalable, trustworthy market data service for digital assets. This architecture is equally transferable to any general-purpose scenario that requires real-time data distribution and visualization—across finance, energy, logistics, and beyond—offering broad engineering reuse value.
