Designing and Implementing a Cryptocurrency Market Data System: From Snapshots to Real-Time Delivery
This article describes the end-to-end design of a cryptocurrency market data system, covering snapshot fields, data ingestion, field semantics, validation, storage, real-time delivery, and observability. It focuses on data accuracy, consistent modeling, layered storage, and high-concurrency presentation strategies for developers building internal dashboards or public market data services.
Designing and Implementing a Cryptocurrency Market Data System
1. Starting with a Market Snapshot
In practice, a typical cryptocurrency market snapshot usually contains the following fields: trading symbol, trading pair, market type, asset name, latest price, quote currency, 24-hour change amount and change percentage, open price, high price, low price, total market cap, market cap rank, and data update time. As an example, the latest price is 0.09359 USD, the open price is 0.09349 USD, the 24-hour high is 0.09539 USD, and the 24-hour low is 0.09119 USD. The change amount is approximately 0.0001 USD, the change percentage is approximately 0.107%, the market cap is approximately 93.73 million, the market cap rank is 164, and the data update time is precise to the second.
This seemingly simple record involves multiple stages: data collection, cleaning, calculation, storage, distribution, and presentation. For developers, understanding how this data is produced, how it flows, and how it is reliably presented is the first step in building a market data system. The following sections discuss the design from the overall architecture down to key details.
2. Market Data Collection and Ingestion
Market data originates from exchange or aggregated data service market APIs. Common forms include REST snapshot endpoints and WebSocket push channels. Each has different strengths:
REST snapshots: Suitable for scheduled polling. They are simple to implement and easy to debug, but real-time behavior is limited by the polling interval, and high-frequency polling can trigger rate limits. The design should use an exponential backoff retry strategy, identify rate-limit signals in response headers or error codes, and dynamically adjust request frequency.
WebSocket push: Suitable for real-time market subscriptions. The server actively pushes incremental updates, providing low latency and reduced traffic. Connection stability requires attention: reconnect after disconnection, heartbeat keepalive, and subscription recovery are three scenarios that must be handled. A common practice is to pull a snapshot once after a disconnect, then resume the subscription, avoiding data gaps during the push interval.
In either case, the collection layer should be decoupled from the business layer. Market data collection can be encapsulated as an independent data pipeline that outputs unified-format messages to a message queue for multiple downstream consumers, such as market display, alerting, and data analysis. This avoids duplicate requests to upstream APIs.
3. Data Modeling and Field Semantics
Market data appears flat, but its fields have clear semantic relationships. Modeling requires particular attention:
Price fields: Latest price, open price, high price, and low price all correspond to the same quote currency. Use high-precision types, such as decimal types rather than floating-point types, to avoid floating-point errors being amplified in change percentage calculations. In the example, the change amount 0.00009989 equals the latest price 0.09359 minus the open price 0.09349, and the change percentage equals the change amount divided by the open price and multiplied by 100%. Any rounding strategy should remain globally consistent.
Time semantics: The 24-hour window usually refers to a rolling window of the past 24 natural hours, not a fixed trading day. This means the high price, low price, and change percentage change in real time as the window slides. The server must clearly define the window start and end and document it.
Market cap and rank: Market cap is generally calculated as circulating supply multiplied by the latest price. The definition of circulating supply, such as whether locked or burned tokens are included, affects the result. This is a typical data-source definition issue. Market cap rank is a relative ordering that updates frequently, so it is better calculated asynchronously rather than tightly coupled with market data.
A concise modeling example is as follows (pseudo-code):
ticker = {symbol: "XXXUSDT",lastPrice: Decimal("0.09359"),openPrice: Decimal("0.09349"),highPrice: Decimal("0.09539"),lowPrice: Decimal("0.09119"),changeAmount: lastPrice - openPrice,changePercent: (changeAmount / openPrice) * 100,marketCap: circulatingSupply * lastPrice,updateTime: ts}
4. Data Validation and Exception Handling
The accuracy of market data directly determines product credibility, so validation cannot be omitted:
Logical consistency validation: The high price should be greater than or equal to the latest price and open price, and the low price should be less than or equal to the latest price and open price. When the change percentage is positive, the change amount should be positive. If contradictory data appears, the frame should be discarded and an alert triggered instead of being passed directly to users.
Anomaly detection: Extreme market events such as flash crashes and price spikes can produce brief, unreasonable quotes. Threshold filtering based on price volatility within a sliding window can be used, or the presentation layer can mark sudden changes.
Clock and latency: The data update time should record when the data was produced, not when it arrived. Pipeline latency should also be monitored. When market data is stale, for example when it has not updated beyond a configured threshold, the UI should show a “data delayed” notice to avoid misleading user decisions.
5. Storage and Query Design
Storage for a market data system is usually divided into three layers:
Hot data layer: The current latest snapshot is read-heavy and write-light with high QPS. It is suitable for an in-memory database or cache. The key is the trading pair, the value is the latest snapshot, and the expiration policy should match the data update cycle.
Historical data layer: K-line and tick-by-tick trade history have high write volume and are queried by time range. They are suitable for time-series storage, partitioned by trading pair and time, and support aggregation at multiple granularities such as 1 minute, 5 minutes, and 1 day.
Analytical data layer: Aggregate views such as market cap rankings and top movers can be precomputed by scheduled tasks and stored in the database. Queries then read the results directly, avoiding a full real-time scan on every request.
6. Real-Time Presentation and High-Concurrency Strategies
Market pages typically have frequent refreshes, high concurrency, and moderate consistency requirements. Common optimization techniques include:
Push-pull combination: The server pushes changed data over long connections, and the frontend throttles and merges updates, for example rendering once every 200 milliseconds to 1 second to avoid high-frequency DOM updates.
Incremental updates: Push only changed fields, such as latest price and change percentage, and update the corresponding cells on the frontend to reduce serialization and rendering overhead.
Asynchronous sorting and rankings: Ranking lists such as market cap rankings are refreshed periodically by the backend and broadcast to clients. The frontend does not perform full local sorting.
Static resources and edge caching: Use edge caching for the framework parts of the market page to accelerate first-screen loading, then fill dynamic data through APIs. This balances first-screen speed and data freshness.
7. Observability and Operations
A market data system is a strongly real-time service with high availability requirements, so a comprehensive observability system is recommended. Monitor and alert on metrics such as collection latency, push latency, validation failure rate, and reconnect count. Maintain versioning for upstream API changes, such as added or removed fields and changed definitions, and design the parsing layer for backward compatibility. Validate new data sources in a gray environment before connecting them to the main pipeline.
8. Conclusion
Behind a single market snapshot is a complete engineering chain of collection, calculation, validation, storage, distribution, and presentation. Developers should prioritize data accuracy, eliminate field definition ambiguity through unified modeling, balance real-time and historical queries through layered storage, and support high-concurrency presentation through push-pull combination and incremental updates. With this methodology, whether building an internal market dashboard or a public-facing market data service, the system can remain logically rigorous and easy to extend. In cloud environments, general cloud capabilities such as message queues, caches, time-series databases, and monitoring and alerting can be used to build these layers quickly, allowing teams to focus on business logic.
