Building a Reliable Market Data Pipeline: Collection, Parsing, and Validation Practices for Digital Assets
This article presents a practical engineering approach to building market data pipelines for digital asset applications. Using a typical ticker snapshot as a sample, it defines a general-purpose field model, then walks through collection, parsing, validation, time alignment, deduplication, storage tiering, and monitoring. Key takeaways include separating raw fields from derived fields, prioritizing collection stability over frequency, filtering dirty data before writes with layered validation, using event time for idempotent writes, and tracking data quality metrics to ensure trustworthy, alignable, and traceable market data.
1. Introduction: Why Market Data Pipelines Need Engineering Design
In the development of digital asset applications, market data is the most fundamental and most frequently underestimated component. Many teams start by simply polling an API on a timer and writing the returned JSON directly to a database. Problems only surface as the business scales: inconsistent timestamps, missing fields, unvalidated extreme prices, duplicate records that cannot be deduplicated, and alert storms downstream caused by upstream jitter. Market data may look simple, but it is a classic case of high-frequency, time-series data with strong consistency requirements, and it must be designed to engineering standards.
This article uses a typical market snapshot as a sample, abstracts a general-purpose field model, and provides a practical approach to collection, parsing, validation, storage, and monitoring. The core information in the sample data includes: symbol, trading pair, market type, asset name, latest traded price, quote currency, 24-hour price change and change percentage, open price, high price, low price, market capitalization, market cap ranking, and data update time.
2. Field Modeling for Market Snapshots
Converting raw payloads into a structured model is the first gate in the entire pipeline. Fields are best divided into four categories:
- Identity fields: symbol, trading pair, market type, asset name. These uniquely determine “what asset this is and which market it is in.”
- Price fields: latest price, open price, high price, low price. Together they form the semantics of a complete candlestick.
- Derived fields: 24-hour change amount and change percentage. These are results computed upstream and should not be recomputed and overwritten downstream.
- Scale and ranking fields: market capitalization and market cap ranking. These are low-frequency fields and need an update cadence separate from high-frequency price fields.
A recommended intermediate model definition is shown below (illustrative):
from dataclasses import dataclassfrom datetime import datetime@dataclassclass TickerSnapshot:symbol: str # Symbolpair: str # Trading pairmarket_type: str # Market typename: str # Asset namelast: float # Latest pricequote_currency: str # Quote currencychange_amount: float # 24h change amountchange_pct: float # 24h change percentageopen: float # Open pricehigh: float # High pricelow: float # Low pricemarket_cap: float # Market capitalizationrank: int # Market cap rankingupdate_time: datetime# Data update time
The key modeling principle is to separate raw fields from derived fields. Change amount and change percentage are provided by the upstream; downstream only performs consistency checks and does not rewrite them, avoiding conflicting definitions.
3. Collection Layer: Stability Over Frequency
The most common mistake in the collection layer is assuming that “more frequent polling is always better.” In practice, too short a polling interval causes three problems: triggering upstream rate limits, amplifying redundant duplicate data, and increasing downstream write pressure. The following practices are recommended:
- Fixed interval plus jitter: Add random jitter on top of the base interval to avoid multiple instances sending concentrated requests at the same moment.
- Incremental first: Use
update_timeas the basis for version comparison; if the time has not advanced, discard the record to reduce ineffective writes. - Separate timeouts from retries: Set connection timeout and read timeout separately, use exponential backoff for retries, and set a maximum retry count.
- Circuit breaking and degradation: After consecutive failures reach a threshold, enter a circuit-broken state and use half-open probing during recovery to avoid continuously overwhelming the upstream.
Illustrative pseudocode:
def poll_with_backoff(fetch, base=5.0, max_retry=5):delay = basefor attempt in range(max_retry):try:return fetch()except TimeoutError:sleep(delay + random.uniform(0, 0.5))delay = min(delay * 2, 30)raise RuntimeError("upstream unavailable")
4. Parsing and Validation: Stopping Dirty Data Before Writes
The parsing stage must assume that “the upstream can return anything abnormal.” Layered validation is recommended:
- Structural validation: Whether required fields exist and whether types can be converted. Records missing key identity fields are discarded and counted.
- Range validation: Prices must be positive; the high price must not be lower than the low price; the latest price should fall between the low and high prices (a very small tolerance is allowed).
- Consistency validation: When the change percentage derived from the open price and latest price deviates from the upstream-provided change percentage beyond a threshold, the record is flagged as suspicious rather than written directly.
- Time validation:
update_timemust not be significantly ahead of local time, nor too old; data beyond the tolerance window goes to a quarantine area.
def validate(t: TickerSnapshot) -> str:if t.last <= 0 or t.high < t.low:return "invalid_price"if not (t.low * 0.999 <= t.last <= t.high * 1.001):return "last_out_of_range"derived = (t.last - t.open) / t.open * 100 if t.open else 0if abs(derived - t.change_pct) > 1.0:return "change_mismatch"return "ok"
Validation results should not just mean “discard”; they should output data quality metrics: discard rate, suspicious rate, and latency distribution. These metrics are the only basis for subsequent optimization.
5. Time Alignment and Deduplication
The core difficulty of market data is time semantics. The same snapshot may appear repeatedly due to retries or message redelivery. Handling strategies:
- Business time first: Use the data’s own update time as the event time; collection time is only an auxiliary field.
- Idempotent writes: Use “symbol + trading pair + update time” as the unique key; duplicate writes are directly overwritten or ignored.
- Out-of-order handling: Allow a certain window of out-of-order data; older data arriving outside the window goes to a late-arrival queue and does not participate in real-time computation.
- Alignment granularity: If downstream performs minute-level aggregation, it must be clear that alignment is “by event time” rather than “by arrival time”; otherwise incorrect price-volume relationships will occur during peak periods.
6. Storage Selection: Tiering by Access Pattern
Access frequency varies greatly across fields, so tiered storage is recommended:
- Hot data: High-frequency read fields such as latest price and change percentage go into an in-memory cache with a short expiration, actively refreshed by the collection task.
- Warm data: Minute-level aggregation results are written to a time-series database or time-series tables in a relational store, partitioned by time.
- Cold data: Raw snapshots are archived to object storage in a compressed columnar format for backtracking and auditing.
Low-frequency fields such as market capitalization and ranking should be stored in a separate table to avoid lock contention caused by mixing them with high-frequency price fields in the same write path.
7. Monitoring and Alerting: Focus on Data Quality Itself
Traditional monitoring only checks whether a service is alive, which is far from enough for a market data pipeline. At least the following metrics are needed:
- Collection success rate, average latency, and latency percentiles;
- Validation discard rate and suspicious data rate;
- Latest price unchanged for a long time (possibly upstream stagnation, or genuinely no trades);
- Change percentage spikes while the price is unchanged (indicating an anomaly in upstream derived fields);
- Data freshness: the difference between the current time and the asset’s update time.
Alerts need grading and suppression: similar anomalies for the same symbol are merged within a window to avoid storm-style notifications.
8. Common Pitfalls Checklist
- Using collection time instead of event time, causing data misalignment during peak periods.
- Recomputing change percentage downstream, resulting in a definition inconsistent with the upstream.
- Treating market cap ranking as a high-frequency field and updating it in real time, causing pointless writes.
- Lacking idempotent design, so retries produce duplicate records.
- Validating by discarding only without counting, allowing problems to remain hidden for a long time.
- Ignoring the distinction between quote currency and market type, causing dimensional errors when aggregating across markets.
9. Conclusion
The value of a market data pipeline lies not in “having obtained the data” but in “having obtained trustworthy, alignable, and traceable data.” Doing these five things solidly—field modeling, layered validation, time semantics, tiered storage, and quality monitoring—provides a reliable foundation for subsequent dashboards, metric computation, and strategy backtesting. For elastic scaling, container platforms can host collection and computation tasks, message queues can handle peak shaving and decoupling, and logging and monitoring/alerting systems can ensure observability, so a general cloud architecture can support stable market data capabilities.
