Market Data Pipeline for Digital Assets: Collection, Parsing, and Validation Practices
This article walks through the engineering of a digital asset market data pipeline, using a sample ticker snapshot to explain data modeling, decimal precision, timestamp and window semantics, collection with backpressure, layered validation, tiered storage, caching, and observability. It shows how to separate raw fields from derived ones, enforce price invariants, keep timestamps timezone-safe, and monitor data freshness so the pipeline becomes trustworthy rather than merely functional.
1. Introduction: Why a Market Data Pipeline Matters More Than a Quick Price Check
In digital asset systems, market data is usually the first thing integrated and the most easily underestimated. Many teams start by rendering only the latest price and 24h change on a page. As business complexity grows, however, system quality is not determined by “can we fetch a price” but by “is the data trustworthy, traceable, and recomputable.”
Consider a typical market snapshot (the data below only illustrates the field structure and is not a live quote):
{"symbol": "GLM","pair": "GLMUSDT","market_type": "CRYPTO","name": "Golem","last_price": 0.09139,"quote_currency": "USD","change_24h": 0.002697,"change_rate_24h": 0.03041,"open_24h": 0.08869,"high_24h": 0.09368,"low_24h": 0.08759,"market_cap": 90541500,"rank": 168,"updated_at": "2026-11-24 14:32:38"}
This record is dense: it carries price dimensions (last, open, high, low), derived metrics (absolute change and change rate), global dimensions (market cap, rank), and a time dimension. We use it as a thread to unpack the engineering essentials layer by layer.
2. Field Semantics and Data Model Design
2.1 Separate Raw Fields from Derived Fields
The 24h change and change rate are derived quantities. In theory they should satisfy:
change_24h = last_price - open_24hchange_rate = change_24h / open_24h
Plugging in the sample: 0.09139 - 0.08869 = 0.00270, which matches the given 0.002697 within decimal precision; 0.002697 / 0.08869 ≈ 3.04%, consistent with 3.041%. The engineering recommendation is: treat derived fields only as validation references, persist the raw fields as the source of truth, and compute derived values on the fly at display time. This avoids making historical data non-recomputable when upstream definitions change (for example, computing over a different window).
2.2 Consistency Constraints on the Price Range
The high and low prices form the day’s price band and must satisfy:
low_24h <= min(open_24h, last_price) <= max(open_24h, last_price) <= high_24h
In the sample, 0.08759 <= 0.08869/0.09139 <= 0.09368, so the constraint holds. Such invariants should live in the validation layer; once violated, the record is treated as dirty data.
2.3 Precision and Type Choices
Price fields must never be stored as floating-point types. Recommended practice:
- Use fixed-point numbers in the database (such as
DECIMAL(28, 12)) or scaled integer storage; - Carry decimals as strings in the transport layer to avoid binary floating-point errors introduced by JSON parsing;
- Format only in the presentation layer.
from decimal import Decimal, ROUND_HALF_UPdef to_decimal(raw: str, scale: int = 12) -> Decimal:return Decimal(raw).quantize(Decimal(1).scaleb(-scale), rounding=ROUND_HALF_UP)def change_rate(last: str, open_: str) -> Decimal:last_d, open_d = to_decimal(last), to_decimal(open_)if open_d == 0:raise ValueError("open price must be non-zero")return (last_d - open_d) / open_d
3. The Time Dimension: Timestamps, Time Zones, and Window Alignment
The sample’s update time is precise to the second but carries no time zone, which is the most common pitfall in practice. Three principles apply:
- Store everything in UTC and convert to the user’s time zone at display time;
- Distinguish “collection time” from “data time”: the former is the local ingestion timestamp, the latter is the market time labeled by the upstream source. Keep both to make latency easy to investigate;
- Define rolling-window boundary semantics explicitly: whether the 24-hour window is left-closed/right-open or left-open/right-closed directly affects which open price is used, and this must be fixed in documentation.
-- Partition by data time to avoid window drift caused by collection delaySELECT symbol,max(high_24h) AS day_high,min(low_24h) AS day_lowFROM market_snapshotWHERE data_time >= :window_startAND data_time < :window_endGROUP BY symbol;
4. Collection Layer Design: Polling, Push, and Backpressure
Market data collection typically follows two paradigms: scheduled polling and incremental push. Polling is simple to implement and easy to replay, making it a good fallback channel. Push has low latency and a small resource footprint but requires handling reconnection and sequence-number gaps. In production, run both channels in parallel, with push as the primary path and polling for calibration.
The collection layer must address backpressure. When downstream writes slow down, a collector coroutine that keeps reading without bounds will cause memory to balloon. A concise bounded-queue approach:
import asyncioasync def producer(queue: asyncio.Queue, source):async for item in source:await queue.put(item) # Blocks automatically when the queue is full, creating backpressureasync def consumer(queue: asyncio.Queue, sink):while True:item = await queue.get()try:await sink.write(item)finally:queue.task_done()
Combined with a fixed-capacity asyncio.Queue(maxsize=10000), unstable traffic can be constrained within a controllable range.
5. Cleaning and Validation: Keep Dirty Data Out of Storage
Build a tiered validation pipeline where any failed stage routes the record to a quarantine area instead of discarding it outright:
- Stage 1: Structural validation — reject records with missing fields or mismatched types;
- Stage 2: Range validation — prices must be positive; alert when the absolute change rate exceeds a threshold (for example, 3% in the sample is normal volatility, while above 30% is more likely a data error);
- Stage 3: Consistency validation — the derived-field and price-band invariants described above;
- Stage 4: Time-series validation — the data time for the same trading pair must not move backward, preventing out-of-order records from overwriting newer values.
def validate(s: dict) -> list[str]:errs = []if Decimal(s["last_price"]) <= 0:errs.append("non-positive price")if not (Decimal(s["low_24h"]) <= Decimal(s["last_price"]) <= Decimal(s["high_24h"])):errs.append("price out of range")if abs(Decimal(s["change_rate_24h"])) > Decimal("0.3"):errs.append("suspicious change rate")return errs
6. Storage and Query: Hot/Warm/Cold Tiering
Market data is a classic “write-heavy, read-light, aggregate-by-time” workload. A sensible tiering strategy:
- Hot data (the last few hours to a few days) lives in key-value or columnar storage that supports high-concurrency point lookups, serving real-time dashboards;
- Warm data (the last few months) is archived as columnar files in object storage, partitioned by date for easy batch recomputation;
- Cold data is archived long term and used only for auditing and model training.
Use date + trading pair as the partition key and guarantee idempotent writes (with symbol + data_time as the unique key), so replaying historical data does not create duplicate records.
7. Service Layer and Caching
When exposing queries externally, split “real-time price” and “historical aggregates” into separate endpoints so slow queries do not affect the real-time path. For caching, the latest price can use a second-level TTL; low-frequency fields such as market cap and rank can use a minute-level TTL. Example:
CACHE = {}async def get_last_price(symbol: str):key = f"last:{symbol}"if key in CACHE:return CACHE[key]value = await store.point_get(symbol)CACHE[key] = valuereturn value
A production implementation should replace this with a cache client that supports TTL and concurrency control (such as single-flight), preventing a large volume of requests from penetrating to the storage layer on cache misses.
8. Observability and Alerting
Failures in a market data pipeline are often “silent”: data keeps flowing but is already stale. You must therefore build monitoring centered on data freshness:
data_lag_seconds: the difference between the current time and the latest data time; alert when it exceeds a threshold;validate_fail_ratio: the share of validation failures; a sudden spike indicates an upstream definition change;sequence_gap: gaps in the push channel’s sequence numbers, used to detect packet loss;pipeline_backlog: the queue backlog length, reflecting whether backpressure persists.
You can use Baidu AI Cloud’s monitoring and alerting capabilities to configure thresholds and tiered notifications for these metrics, and use a log service to keep structured records of quarantine samples for later review.
9. Common Pitfalls Checklist
- Storing prices as floating-point numbers, causing rounding discrepancies on recomputation;
- Timestamps without a time zone, shifting the entire window after cross-time-zone deployment;
- Storing only derived metrics without raw values, making history non-traceable once upstream definitions change;
- Collection without backpressure, exhausting memory during sharp market swings;
- Discarding records on validation failure, with no quarantine area, making problems impossible to locate;
- Mixing global fields such as market cap and rank with trading-pair fields in the same primary key, causing duplication and overwrites.
10. Conclusion
A seemingly simple market snapshot unfolds into a complete engineering problem spanning data modeling, precision handling, time semantics, flow control, validation, tiered storage, and observability. Separate raw from derived data, encode invariants into validation, and make freshness a core metric. Get these three right, and a market data pipeline moves from “it runs” to “it is trustworthy.”
