Real-Time Market Data Pipeline for Digital Assets: Collection, Validation, and Rendering

    This article walks through a production-grade pipeline for digital asset market data, covering four layers: ingestion, validation, transport and storage, and frontend rendering. It defines a unified internal market data model with high-precision decimals and dual timestamps, a dual-channel collection strategy that merges full snapshots with incremental pushes using last-write-wins, and a validation ruleset that adds a time dimension to distinguish genuinely quiet markets from stale cached values. It also describes hot/warm/cold storage tiering, publish-subscribe push with throttling, batch rendering via a single animation frame loop, observability metrics and capacity estimation, and how these map to generic cloud capabilities. The key takeaway is that reliability comes from keeping prices fresh, self-consistent, and explainable across the whole chain.

    1. Starting From a Single Market Snapshot

    In digital asset trading applications, market data display is the most fundamental module and also the most easily underestimated. A typical market snapshot usually contains the following information: symbol code, trading pair, market type, latest traded price, quote currency, 24-hour change amount and change rate, open price, high price, low price, market cap, market cap ranking, and the data update timestamp.

    Here is a set of sample data (fields have been neutralized):

    1. {
    2. "symbol": "GLM",
    3. "pair": "GLMUSDT",
    4. "market_type": "CRYPTO",
    5. "name": "Golem",
    6. "last_price": 0.09359,
    7. "quote_currency": "USD",
    8. "change_24h": 0,
    9. "change_rate_24h": 0.000,
    10. "open_24h": 0.09359,
    11. "high_24h": 0.09539,
    12. "low_24h": 0.09119,
    13. "market_cap": 93733100,
    14. "rank": 164,
    15. "updated_at": "2026-12-01 19:53:38"
    16. }

    This record looks simple, but presenting it reliably in production requires solving problems at four levels: how data comes in, whether the data is trustworthy, how it is delivered with low latency, and how it is rendered correctly. Let us break these down one by one.

    2. Data Collection Layer: Multi-Source Ingestion and a Unified Abstraction

    Market data sources typically include public exchange APIs, third-party data aggregation services, and self-hosted collection nodes. From an engineering standpoint, it is not advisable to pass the field structure of any single source directly through to the business layer. Instead, you should define an internal unified Market Data Model, and have all external data converted into that model through adapters first.

    1. from dataclasses import dataclass
    2. from decimal import Decimal
    3. @dataclass(frozen=True)
    4. class TickerSnapshot:
    5. symbol: str # Normalized symbol code
    6. pair: str # Trading pair
    7. market_type: str # CRYPTO / FIAT, etc.
    8. last: Decimal # Latest price
    9. open_24h: Decimal
    10. high_24h: Decimal
    11. low_24h: Decimal
    12. change_24h: Decimal
    13. change_rate: Decimal # Decimal form; 0.001 means 0.1%
    14. quote_currency: str
    15. market_cap: Decimal | None
    16. rank: int | None
    17. source_ts: str # Source timestamp
    18. ingest_ts: float # Local receive time

    There are two key design points here. First, prices must always use a high-precision decimal type; binary floating point must not be used directly for arithmetic, otherwise precision drift will occur under extreme market conditions. Second, you must retain both the source timestamp and the local receive time, because the difference between them is the core basis for judging data freshness and pipeline latency downstream.

    On the collection side, a dual-channel model of “scheduled full pull + incremental push” is recommended: scheduled tasks pull full snapshots at fixed intervals for fallback and alignment, while the incremental channel handles low-latency updates. Data from the two channels is merged in memory per symbol using Last Write Wins, with the source timestamp as the comparison basis, to avoid out-of-order network delivery causing old data to overwrite new data.

    3. Data Validation Layer: Turning “Looks Normal” Into “Actually Trustworthy”

    In the sample data, the latest price equals the open price and the 24-hour change amount is zero. In real scenarios this usually means one of two things: either the symbol genuinely had no trades within the statistical window, or the collection pipeline has already broken and is returning a stale value from cache. The two cases are completely indistinguishable by value alone, so the validation layer must introduce a time dimension.

    A rule set like the following is recommended:

    • Freshness check: if now - source_ts exceeds a threshold (for example 30 seconds), mark it as stale, and the frontend displays it grayed out or with an explicit indicator.
    • Range consistency check: low_24h <= last <= high_24h, and last should fall within [open_24h ± reasonable volatility multiple × historical volatility].
    • Change self-consistency check: change_24h ≈ last - open_24h, change_rate ≈ change_24h / open_24h; discard if the deviation exceeds tolerance.
    • Precision and unit check: price decimal places and market cap units (yuan / ten-thousand yuan / hundred-million yuan) must be normalized to avoid different units appearing on the same page.
    • Ranking sanity check: the market cap rank should be within a valid range and should not show obvious inversion against the market cap ordering.
    1. def validate(t: TickerSnapshot, now: float, stale_sec: float = 30) -> tuple[bool, list[str]]:
    2. errs = []
    3. if now - t.ingest_ts > stale_sec:
    4. errs.append("STALE")
    5. if not (t.low_24h <= t.last <= t.high_24h):
    6. errs.append("PRICE_OUT_OF_RANGE")
    7. if abs((t.last - t.open_24h) - t.change_24h) > t.open_24h * Decimal("0.0005"):
    8. errs.append("CHANGE_INCONSISTENT")
    9. return (len(errs) == 0), errs

    Records that fail validation should not be discarded outright, but should enter a separate dead-letter queue for later replay analysis and collection-source quality assessment. This is extremely valuable when troubleshooting production issues of the “prices are not moving” kind.

    4. Transport and Storage Layer: Hot/Cold Tiering and Incremental Push

    The read/write characteristics of market data are typically write-heavy and read-heavy, but with low value per record and an enormous total volume. A sensible approach is to tier it:

    • Hot data: the latest snapshots are kept in an in-memory cache, keyed by symbol, with a short expiration time, supporting millisecond-level reads.
    • Warm data: minute-level aggregates (candles) are written to a time-series database for charts and backtesting.
    • Cold data: raw snapshots are compressed and stored in object storage, partitioned by date, for auditing and model training.

    On the push side, a publish-subscribe model is recommended to decouple “data updates” from “connection management.” After snapshot merging completes, the backend publishes change events to a topic, and the gateway subscribes to that topic and filters and forwards according to the symbols each client has subscribed to.

    1. async def on_snapshot(merged: TickerSnapshot):
    2. if not merged.is_valid:
    3. await dead_letter.put(merged)
    4. return
    5. await cache.set(f"ticker:{merged.symbol}", merged, ttl=5)
    6. await bus.publish("ticker.update", merged)

    It is worth emphasizing that push frequency should be throttled and coalesced: multiple updates for the same symbol within 200 milliseconds are merged into a single downstream delivery, to avoid saturating bandwidth and the frontend rendering thread when the market fluctuates violently.

    5. Rendering Layer: Stability Over Real-Time

    The most common performance trap when rendering market data on the frontend is “triggering a full redraw on every push.” The correct approach is to separate value updates from layout updates: first write to the data layer, then batch-commit to the view through a single animation frame loop.

    1. const pending = new Map();
    2. socket.onmessage = (e) => {
    3. const t = JSON.parse(e.data);
    4. pending.set(t.symbol, t); // Enqueue only; do not touch the DOM
    5. };
    6. function flush() {
    7. for (const [sym, t] of pending) {
    8. renderPrice(sym, t.last); // Update the text node only
    9. renderChange(sym, t.change_rate);
    10. }
    11. pending.clear();
    12. requestAnimationFrame(flush);
    13. }
    14. requestAnimationFrame(flush);

    Combined with the following experience details, user misjudgment can be significantly reduced: use color-vision-friendly dual encoding for gains and losses (color plus sign/arrow), add an explicit marker for stale data, use a monospaced font for numbers and align decimal places to avoid jitter, and standardize units and thousands separators for large values such as market cap and rank.

    6. Observability and Capacity Planning

    The market data pipeline must establish its own metrics system, covering at least: collection success rate, end-to-end latency percentiles (P50/P95/P99), validation failure rate and failure reason distribution, push throttling hit rate, cache hit rate, and outbound bandwidth per connection. For alerting strategy, latency percentiles and the proportion of stale data are the two most sensitive signals and should be configured first.

    Capacity estimation can use a simplified model: a single symbol snapshot is about 200 bytes; with 1000 symbols and 5 updates per second each, inbound traffic is about 1 MB/s; if the subscription amplification factor is 20, outbound traffic is about 20 MB/s, on which basis you should plan gateway horizontal scaling and the connection count limit.

    7. Mapping to General Cloud Capabilities

    When deploying on the cloud, you can map to general-purpose capability categories: a container platform hosts the collection and gateway services to enable elastic scaling; a message queue handles event decoupling and peak shaving; a time-series database stores aggregated market data; object storage archives raw data; and logging services plus a monitoring and alerting system provide pipeline observability. In these kinds of scenarios, Baidu AI Cloud is typically also built from the above general capability combination; for specific specifications and quotas, refer to the official documentation. This article does not cover any undisclosed parameters.

    8. Summary

    The difficulty of the market data module lies not in “getting a price,” but in keeping that price fresh, self-consistent, and explainable across the entire pipeline. Doing these five things solidly—a unified data model, time-dimension validation, hot/cold tiered storage, throttled push, and batch rendering—keeps the interface stable and the data trustworthy even when the market fluctuates violently.