Real-Time Market Data Ingestion and Processing: A Practical Guide
A reliable market data pipeline must deliver fresh prices and make them easy to verify. This guide covers how to define a data contract, combine streaming subscriptions with polling, compute rolling metrics, and organize storage by access needs. It also explains how to monitor data quality and use replay and reconciliation to recover from gaps.
1. Start With a Market Data Snapshot
A typical market data snapshot includes an instrument symbol, trading pair, market type, display name, latest price, quote currency, 24-hour price change and percentage change, open, high, low, market capitalization, market-cap rank, and a last-updated timestamp.
For example, a trading pair might show a latest price of 0.09359 USD, a 24-hour change of 0.00009989 USD (0.107%), an open of 0.09349 USD, a high of 0.09539 USD, and a low of 0.09119 USD. The snapshot might also report a market cap of approximately 93.7331 million, a rank of 164, and an update timestamp recorded to the second.
These fields expose four requirements for the entire pipeline:
- Timeliness: The update timestamp tells downstream consumers how current the snapshot is.
- Consistency: The absolute and percentage changes must be reproducible from the latest price and the corresponding opening price, using the underlying precision.
- Precision: Low-priced instruments can require many decimal places, especially when measuring small price changes.
- Aggregation: Highs, lows, and market-cap rankings depend on combining data across sources or instruments.
A failure in any of these areas can skew downstream strategies, risk controls, or user-facing displays.
2. Define Field Semantics and the Data Contract
Establish the data contract before writing ingestion code:
- Instrument identity: Use the combination of symbol, trading pair, and market type as the instrument key. A display name alone is not a reliable identifier.
- Price and precision: Low-priced assets can trade at a few hundredths of a unit, with changes as small as 1e-5. Use fixed-point numbers or high-precision decimal types for core calculations rather than binary floating-point.
- Timestamp semantics: Keep the time the source produced the data separate from the time it was written to storage. The difference is the end-to-end latency.
- Derived fields: The absolute change is the latest price minus the opening price. Divide that change by the opening price and multiply by 100 to get the percentage change. Recompute these values to validate upstream data instead of accepting it unchecked.
from decimal import Decimal, ROUND_HALF_UPdef derive(price: Decimal, open_price: Decimal) -> dict:if open_price == 0:return {"change": Decimal(0), "change_pct": Decimal(0)}change = price - open_pricepct = (change / open_price * 100).quantize(Decimal("0.001"), ROUND_HALF_UP)return {"change": change, "change_pct": pct}
3. Combine Streaming Subscriptions With Polling
Polling is simple and stateless, but sampling intervals can vary, and frequent requests can hit upstream rate limits. Push-based subscriptions over persistent connections offer lower latency and lower resource usage, but require connection lifecycle management. In production, use streaming as the primary feed and polling as a fallback and reconciliation check.
A streaming ingestion service needs to handle four things:
- Reconnection: Use exponential backoff with jitter so that instances do not all reconnect at once after an outage.
- Heartbeats and half-open connections: Use application-level heartbeats rather than relying on the transport layer alone. Rebuild the connection when a heartbeat times out.
- Sequencing and deduplication: Use the instrument, timestamp, and price as an idempotency key. Overwrite duplicate snapshots rather than appending them.
- Backpressure: Bound the local queue. If it fills up, drop the oldest snapshots and count the drops. For a current-price feed, a fresh snapshot with gaps is more useful than a complete but stale backlog.
import random, timedef backoff(attempt: int, base: float = 0.5, cap: float = 30.0) -> float:delay = min(cap, base * (2 ** attempt))return delay * (0.5 + random.random() / 2) # Jitter
4. Decouple Ingestion From Real-Time Processing
Publish incoming data to a message queue instead of writing it directly to the database. This separates ingestion from processing, lets consumers scale independently, and buffers fluctuations in the upstream feed. Retained raw messages can also be replayed during incident investigations.
The real-time processing layer has three responsibilities:
- Maintain per-pair state: Track the latest and opening prices, along with the high and low within the rolling window.
- Compute derived metrics: Calculate absolute and percentage price changes as updates arrive. Produce 1-minute, 5-minute, or 1-hour aggregates as needed.
- Aggregate across instruments: Compute market-cap totals and rankings. At scale, bucket instruments by market cap for an approximate ordering, then sort the highest-value buckets precisely to reduce the amount of sorting required.
Use at-least-once delivery with idempotent writes. Periodically reconcile the stream-derived state against full snapshots to correct highs or lows missed by the streaming path.
5. Organize Storage Into Hot, Warm, and Cold Tiers
- Hot data: Keep individual snapshots from the past few hours to a few days in a time-series database for real-time queries and alerts.
- Warm data: Retain minute-level aggregates for longer periods. They compress well and are quick to query.
- Cold data: Archive raw messages and full snapshots in partitioned object storage for historical analysis and model training.
- Metadata: Store and version relatively static instrument attributes, such as display name, quote currency, and market type, separately from high-frequency updates.
A partition key that combines the date with an instrument hash helps limit partition size and avoid hotspots.
6. Monitor Data Quality, Not Just Service Uptime
A running service can still deliver stale or incorrect prices. Monitor the data itself:
- Latency: Track P99 latency from source event time to the storage write, and alert when it exceeds the threshold.
- Freshness: Flag an instrument’s feed as stalled if it has not updated within the configured number of seconds.
- Price plausibility: If a price deviates from the median in the same window by more than a configured factor, flag it as an anomaly before writing it as normal data.
- Reconciliation differences: Track how often polled snapshots disagree with streamed snapshots.
- Market data behavior: Monitor abrupt changes in percentage returns and how often new highs or lows are recorded.
Collect metrics, logs, and traces together. Send logs to the logging service and metrics to the monitoring and alerting system so operators can trace an alert back to the raw message.
7. Plan for Deployment, Scaling, and Security
Run stateless ingestion and processing instances on a container platform, and scale them based on the number of subscribed instruments. Deploy the stateful time-series store separately and maintain multiple replicas.
Distribute settings and secrets through configuration and secrets management systems rather than hardcoding credentials. Require authentication and rate limiting on externally exposed APIs.
When using cloud services, choose components by role: containers for compute, a message queue for buffering, a time-series database and object storage for tiered retention, and logging and monitoring services for observability. Keep those components replaceable rather than tying the pipeline to a single implementation.
8. Implementation Checklist
- Is the data contract defined, including numeric precision and validation rules?
- Do the streaming and polling paths both handle retries with backoff and process updates idempotently?
- Is the backpressure policy in place, and are dropped snapshots counted and monitored?
- Have you estimated capacity for each storage tier and checked the partition key against those estimates?
- Are alerts in place for latency, stale data, and implausible prices?
- Can you replay raw messages and reconcile against full snapshots?
The goal is not simply to fetch a price. It is to be able to answer, at any point, how fresh the data is and how you know it is accurate. Designing for timeliness, precision, and verifiability from the start makes the pipeline more reliable and its output easier to trust.
