Prompt
How do I set up a market data engine for real-time price feeds on a 24/7 exchange?
Latest observation
Setting up a market data engine for a 24/7 exchange is mostly about building a low-latency, highly available, replayable event pipeline that can ingest exchange updates, normalize them, persist them, and distribute them to consumers in real time.
Here’s a practical blueprint.
1) Define the data model first
Decide what you need to publish:
- Trades
- Top-of-book quotes
- Full order book deltas
- Candles / OHLCV
- Funding / index / mark price if applicable
- Reference metadata
- instruments
- tick size
- lot size
- trading status
A strong pattern is to represent everything as events with:
exchangesymbolevent_typeexchange_timestampingest_timestampsequence_number- payload fields
For order books, define:
- snapshot
- delta/update
- checksum if the exchange provides one
2) Build the ingestion layer
This connects to the exchange and pulls real-time data.
Common sources
- WebSocket for real-time streams
- REST for snapshots, metadata, and recovery
- FIX / proprietary protocols if the venue supports them
Ingestion responsibilities
- Maintain persistent connections
- Reconnect automatically
- Detect gaps in sequence numbers
- Request snapshots on recovery
- Normalize incoming messages into a common schema
- Timestamp immediately upon receipt
Important practices
- Run one consumer per feed shard or symbol group
- Keep the ingestion process lightweight
- Separate network I/O from message processing
- Use backpressure and buffering so a burst doesn’t drop data
3) Use a canonical normalization layer
Different exchanges name fields differently and may have different semantics.
Normalize to:
- consistent symbols
- side as
bid/ask - price and size as decimals or integer ticks
- timestamps in UTC
- standardized event types
Example normalized trade:
{
"exchange": "X",
"symbol": "BTC-USD",
"event_type": "trade",
"trade_id": "12345",
"price": 65234.5,
"size": 0.12,
"side": "buy",
"exchange_timestamp": "2026-01-01T00:00:00.123Z",
"ingest_timestamp": "2026-01-01T00:00:00.130Z"
}
4) Choose a transport/event backbone
For a real-time exchange engine, you usually want a streaming bus between ingestion and consumers.
Common options
- Kafka: great for durability, replay, multiple consumers
- Redpanda: Kafka-compatible, simpler operationally
- NATS / NATS JetStream: lower latency, simpler pub/sub
- Redis Streams: simpler, but less ideal at high scale
- Custom in-memory pub/sub: very fast, but less durable
Typical partitioning strategy
Partition by:
symbol- or
exchange + symbol - or
instrument_id
This ensures ordering within a symbol stream.
5) Handle order book reconstruction correctly
If you provide books, you need a robust state machine.
Standard approach
- Load initial snapshot
- Subscribe to incremental updates
- Apply updates in sequence
- Validate sequence continuity
- On gap/out-of-order:
- mark book stale
- reload snapshot
- replay buffered deltas if possible
Keep in-memory book state
- best bid/ask
- full depth levels
- sequence number
- last update timestamp
For performance:
- use price-level maps
- use sorted structures or arrays for top N levels
- avoid heavy object churn in hot paths
6) Design for 24/7 availability
Because the exchange never closes, your system should assume continuous operation.
High availability requirements
- multiple instances of ingestion
- failover for WebSocket connections
- health checks and watchdogs
- rolling deploys without downtime
- automated resubscription after outages
- persistent checkpointing
Recommended architecture
- Active-active ingestion where possible, or active-standby
- Stateless consumers that can restart easily
- Stateful book builders with checkpointing or replay
- Store offsets/sequence checkpoints in durable storage
7) Add persistence and replay
You need both:
- hot path for live consumers
- cold path for historical analysis and recovery
Persist:
- raw exchange messages
- normalized events
- derived outputs like candles or analytics
Storage options
- Kafka/Redpanda for short-to-medium replay
- Object storage (S3/GCS/etc.) for long-term archival
- Time-series DB for queryable recent history
- Relational DB for metadata
A good rule: never rely only on in-memory state.
8) Build a distribution API
Consumers usually need:
- WebSocket feeds
- gRPC streams
- REST endpoints for snapshots/history
- internal pub/sub for microservices
API patterns
- WebSocket for clients needing live ticks/books
- gRPC streaming for internal low-latency consumers
- REST for snapshots and metadata
Offer:
- current top of book
- depth snapshots
- recent trades
- candles
- server status / lag metrics
9) Time handling is critical
For market data, timestamps matter a lot.
Use at least:
- exchange timestamp
- receive timestamp
- optionally process timestamp
Requirements:
- UTC everywhere
- monotonic clock for latency measurement
- NTP or PTP sync on servers
- measure:
- feed lag
- processing lag
- publish lag
10) Monitor everything
You should monitor:
- connection status per feed
- message rate per symbol
- dropped messages / sequence gaps
- consumer lag
- reconnect counts
- book staleness
- end-to-end latency
- CPU/memory/network usage
Alerts
- feed disconnected
- sequence gap detected
- no messages for active symbol
- latency above threshold
- backlog growing
11) Optimize for low latency without sacrificing correctness
Performance tips
- use async I/O
- minimize serialization overhead
- use binary formats if needed: Protobuf / Avro / FlatBuffers
- avoid blocking calls in hot path
- preallocate buffers where possible
- batch writes to downstream systems
- pin critical workers if ultra-low latency matters
Correctness tips
- idempotent event handling
- deterministic ordering per symbol
- strict validation of updates
- clear recovery logic
12) Recommended reference architecture
A solid production setup looks like:
- Exchange connectors
- WebSocket/FIX clients
- snapshot fetchers
- Normalizer
- transforms feed-specific messages into canonical events
- Event bus
- Kafka/Redpanda/NATS
- Stateful processors
- order book builders
- candle aggregators
- analytics
- Storage
- raw archive
- normalized history
- metadata DB
- Serving layer
- WebSocket/gRPC/REST APIs
- Observability
- metrics, logs, tracing, alerts
13) Minimal implementation plan
If you want to start small:
Phase 1
- connect to one exchange
- ingest trades + top-of-book
- normalize messages
- publish to Kafka or NATS
- expose a simple WebSocket API
Phase 2
- add full order book support
- add snapshot + recovery logic
- add persistence and replay
Phase 3
- multi-exchange support
- candles, funding, reference data
- high availability, metrics, alerts
- load testing and failover
14) Technology stack suggestions
A practical stack could be:
- Language: Go, Rust, or Java for the hot path
- Streaming: Kafka or Redpanda
- API: gRPC + WebSocket
- Persistence: S3 + Postgres + ClickHouse or TimescaleDB
- Observability: Prometheus + Grafana + OpenTelemetry
- Deployment: Kubernetes or bare metal for latency-sensitive parts
15) Key pitfalls to avoid
- relying only on WebSockets without snapshot recovery
- ignoring sequence gaps
- building order books from trades only
- not separating ingest from serve path
- storing everything in one database
- using non-monotonic timestamps for latency metrics
- no backpressure handling
- no replay capability
- no symbol-level ordering guarantees
16) A good “first production” design
If I were building this from scratch, I’d do:
- Go or Rust ingestion services
- Redpanda/Kafka as the event backbone
- Canonical event schema with sequence/timestamps
- Snapshot + delta order book builder
- ClickHouse for analytical history
- S3 for raw archival
- WebSocket API for clients
- Prometheus/Grafana for observability
If you want, I can also give you:
- a sample system architecture diagram,
- a database/schema design, or
- a starter code example for a market data WebSocket ingester.