Digital Asset Market Data Pipelines: Design and Governance
Learn how to build a maintainable, observable, and traceable digital asset market data service. This article covers field semantics, consistent window calculations, real-time pipeline architecture, deduplication, data quality controls, API design, operational testing, and compliance considerations.
A seemingly simple market snapshot can contain an asset code, trading pair, market type, display name, latest price, quote currency, price change and percentage change over a defined period, opening price, high, low, market capitalization, market cap rank, and update time.
To users, these are just numbers. To developers, they represent a real-time data product built from ingestion, normalization, window calculations, cache distribution, quality checks, monitoring, and compliance disclosures. Treating market data as merely “a frontend polling an API” can lead to problems with latency, duplicate events, inconsistent time windows, anomalous prices, and discrepancies between sources.
This article uses a general digital asset market data scenario to explain how to build a maintainable, observable, and traceable service. All values and code are illustrative. They do not constitute investment advice or represent the actual APIs or capabilities of any specific platform.
1. Define the Data Model: Field Semantics Matter More Than Field Count
The first task is not choosing a cache or messaging component. It is defining what each field means.
A “24-hour percentage change” might use a rolling 24-hour window or a fixed calendar-day window. An “opening price” might refer to the start of the trading day, the beginning of a reporting interval, or the previous settlement price. Without consistent definitions, calculations and presentation will require repeated rework.
An internal model should distinguish at least the following fields:
| Field | Recommended semantics | Implementation considerations |
|---|---|---|
asset_code |
Unique asset code | Standardize casing and mapping rules; retain historical aliases. |
trading_pair |
Trading pair identifier | Explicitly identify the base asset, quote asset, and market type. |
market_type |
Market type | Use a controlled enumeration rather than free text. |
display_name |
Display name | Support localization; do not use it as a unique identifier. |
last_price |
Latest trade price or latest quote | Specify the source and update trigger. |
quote_currency |
Quote currency | Keep it consistent with the trading pair’s quote asset. |
change_amount_24h |
Price change over the interval | Define the reference price and time window. |
change_pct_24h |
Percentage change over the interval | Return null when the reference price is zero or missing. |
open_24h / high_24h / low_24h |
Opening, highest, and lowest prices within the interval | Bind all three to the same window definition. |
market_cap |
Market capitalization | Specify the circulating supply source and price timestamp. |
market_cap_rank |
Market capitalization rank | Treat it as a cross-sectional aggregate, not an immediate calculation within a single-asset pipeline. |
updated_at |
Market data update time | Distinguish event time, ingestion time, and publication time. |
stale / quality |
Data quality status | Enable frontends and downstream systems to make fallback decisions. |
Represent prices and monetary amounts as decimal strings or integers in the smallest unit to avoid binary floating-point errors. Preserve event time, ingestion time, and external publication time so operators can distinguish late-arriving data from slow processing.
Keep trading pairs, asset codes, and display names separate. A name change should not affect primary keys or historical data relationships.
2. Calculate Key Metrics Consistently
For an individual trading pair, price change and percentage change are easy to underestimate. Common definitions are:
Price change = Latest price - Interval reference pricePercentage change = (Latest price - Interval reference price) / Interval reference price × 100%Market capitalization = Circulating supply × Latest price
The formulas are straightforward. The critical issue is the definition of the interval reference price.
For a rolling 24-hour window, the reference price should represent the price at the start of the window, 24 hours before the current time. The high and low must be aggregated over that same window. For a fixed reporting period, the definition must remain consistent across frontend explanations, API documentation, and monitoring metrics.
Do not combine a latest-price snapshot based on a rolling window with calendar-day highs and a percentage change from another source.
Handle these edge cases explicitly:
- Zero or missing reference prices: Return null or a quality flag for percentage change rather than dividing by zero.
- Multiple trading pairs across markets: Specify whether the API returns a single trading pair’s market data or a global reference price for the asset.
- Market cap rankings: Periodically sort the complete asset set and record the calculation time.
- Quote currency conversion: Use an explicit exchange rate and timestamp. Do not combine prices and exchange rates from different times without a defined policy.
- Late-arriving events: These can change window aggregates. Streaming calculations need watermarks and a late-data handling policy.
3. Structure the Real-Time Pipeline
A practical market data pipeline can be organized as follows:
Source adapters↓Validation and normalization↓Message buffering↓Streaming window calculations and aggregation↓Hot cache / Time-series storage / Historical snapshots↓Query APIs and real-time delivery↓Monitoring, alerts, audits, and quality dashboards
Each layer has a distinct responsibility:
- Source adapters connect to different data sources and handle reconnection, backoff, full snapshots, and incremental updates.
- Normalization handles asset mapping, trading pair normalization, monetary precision, and enumeration validation.
- Message buffering absorbs traffic spikes and decouples producers from consumers.
- Stream processing performs deduplication, window aggregation, percentage-change calculations, and anomaly marking.
- Hot caches serve the latest snapshots.
- Time-series or columnar storage retains historical sequences.
- Object storage can retain raw messages and periodic snapshots for replay and auditing.
- Query and delivery interfaces provide batch snapshots, single-asset queries, and subscription-based updates, including update times and quality status in responses.
Avoid assembling every display field at ingestion time or scanning the full history for each query. A clearer boundary is to make ingestion responsible for reliably admitting events, the computation layer responsible for consistent calculations, and the API layer responsible for authentication, rate limiting, cache reads, and explicit fallback behavior.
4. Capture Calculation and Deduplication Logic in Pseudocode
The following pseudocode illustrates a simplified flow from event validation to snapshot publication:
function process_tick(tick):if not validate_basic(tick):audit_reject(tick)returnkey = normalize_key(tick.asset_code, tick.pair, tick.market_type)if dedup.exists(tick.event_id):returnstate = window_state.get(key)window_state.update(state, tick.price, tick.event_time)reference = window_state.price_at(state, tick.event_time - 24h)if reference is null or reference <= 0:pct = nullquality = "DEGRADED"else:pct = (tick.price - reference) / reference * 100quality = "OK"snapshot = {asset_code: tick.asset_code,pair: tick.pair,market_type: tick.market_type,last_price: decimal(tick.price),quote_currency: tick.quote_currency,change_amount_24h: reference is null ? null : tick.price - reference,change_pct_24h: pct,open_24h: reference,high_24h: window_state.high(state, 24h),low_24h: window_state.low(state, 24h),updated_at: tick.event_time,stale: false,quality: quality}cache.upsert(key, snapshot)history.append(snapshot)push_channel.publish(key, snapshot)
Production systems must also handle out-of-order and late events. A common approach is to assign each event a unique identifier and use sequence numbers or versions to determine ordering. Recalculate windows for events that arrive within the permitted lateness interval. Route events outside that interval to a correction task and record an audit log.
When publishing a snapshot, update the latest price, price change, percentage change, and update time atomically. Otherwise, downstream consumers may read an intermediate state containing a new price and an old percentage change.
5. Control Data Quality and Fallback Behavior
Availability means more than returning an API response. The response must also be fresh, complete, and explainable.
At a minimum, implement the following checks:
- Freshness: Calculate data age from the update time and current time. Mark the snapshot as
stalewhen it exceeds the threshold. - Price anomalies: Use multi-source medians, historical volatility, and dynamic thresholds to identify unusual spikes and prevent a single erroneous quote from contaminating the display.
- Cross-field consistency: Ensure the high is not below the low, the latest price falls within a reasonable range, and interval fields follow the declared window definition.
- Cross-source consistency: Retain source identifiers for each asset and trading pair. Alert or degrade service when prices diverge substantially between sources.
- Duplicates and gaps: Monitor duplicate rates, missing messages, sequence discontinuities, and prolonged periods without updates.
- Market cap and ranking consistency: Market capitalization depends on circulating supply data and the price timestamp. Rankings may update less frequently than prices, but their calculation time must be returned.
Do not silently mix sources during fallback. Retain the last known snapshot and expose its stale and quality fields. Suspend updates for anomalous trading pairs where necessary, and fall back to read-only or delayed delivery. Provide downstream systems with batch snapshots and recovery interfaces for missed updates.
Record the source, switch time, trigger, and recovery conditions for every automatic source switch.
6. Design APIs for Stability and Observability
External APIs should be stable, support batch queries, and include version and quality information. An illustrative response is:
{"asset_code": "EXAMPLE","pair": "EXAMPLE-USD","market_type": "SPOT","last_price": "123.45","quote_currency": "USD","change_amount_24h": "2.50","change_pct_24h": "2.07","open_24h": "120.95","high_24h": "124.00","low_24h": "119.80","market_cap": "1000000000","market_cap_rank": 10,"updated_at": "YYYY-MM-DDTHH:mm:ssZ","stale": false,"quality": "OK"}
Return prices as strings to reduce parsing errors across programming languages. Limit the number of assets in batch requests and support pagination. Real-time delivery interfaces should support reconnection, sequence-based resumption, and heartbeats.
For observability, collect:
- End-to-end latency
- Message backlog
- Window calculation duration
- Duplicate and late-event rates
- Number of stale snapshots
- API error rates
- API latency distributions
Logs should include the source, event identifier, key fields before and after normalization, and version numbers. Never log keys or sensitive credentials.
7. Deployment, Testing, and Compliance
A deployment can combine object storage, message queues, logging services, monitoring and alerting, caches, and time-series databases. Validate recovery objectives through load testing and failure drills.
Whether using a self-managed environment or Baidu AI Cloud, base design assumptions on the relevant official documentation, security and compliance requirements, and capacity test results. Do not treat unverified parameters as established capabilities.
Before release, perform:
- Unit tests for calculation formulas
- Window boundary tests
- Replay tests for out-of-order and duplicate messages
- Failure drills for cache invalidation, messaging interruptions, and storage unavailability
For compliance, confirm the scope of market data licensing, delayed-data disclosure requirements, and redistribution restrictions. Clearly display necessary notices, such as “Market data may be delayed or inaccurate and does not constitute investment advice.”
Avoid promotional or inducement-oriented language for high-risk assets. Market data presentation should not be framed as a trading recommendation.
A number on a market data page becomes engineering-reliable only when its semantics are consistent, its pipeline is traceable, anomalies trigger explicit fallback behavior, and monitoring can identify the source of failures.
