Design a Real-Time Streaming VWAP Computation Service
System DesignModel answerLast updated
Design a sub-5ms latency pipeline that ingests multi-exchange trade ticks, maintains running VWAP aggregates with correction support, and fans out to tens of thousands of subscribers.
Background
A trading analytics platform needs to compute Volume-Weighted Average Price (VWAP) continuously across every actively traded equity symbol, sourcing raw trade data from dozens of global exchanges simultaneously.
VWAP is defined as:
VWAP = Σ(Pᵢ × Vᵢ) / Σ(Vᵢ)
where Pᵢ and Vᵢ are the price and volume of each individual trade.
The service must compute two flavors of VWAP in parallel:
- Session VWAP — accumulates from the opening print of each trading day through the current moment, resetting at each market open.
- Rolling-window VWAP — covers a sliding lookback period (for example, the trailing 5 minutes or trailing 1 hour), using the exchange's own execution timestamp as the event clock.
Downstream clients range from latency-sensitive algorithmic trading desks that need raw, unconflated streams to external portals that need throttled WebSocket feeds and on-demand historical lookups.
Requirements
Functional
- Ingestion and normalization: Accept raw trade data from 50+ exchanges using a variety of wire protocols (binary multicast, FIX session, proprietary ITCH-style feeds). Normalize every incoming trade into a single internal canonical format before processing.
- Continuous aggregation: Maintain and publish session VWAP and rolling-window VWAP per symbol, updating with each new eligible trade.
- Trade corrections: Exchanges periodically issue cancellations ("busts") and amended prints. The running aggregates must adjust immediately and accurately when corrections arrive.
- Delivery and querying: Stream live VWAP updates to subscribers and expose an API for point-in-time lookups and end-of-day figures.
Non-Functional
- Latency: p99 end-to-end time from tick arrival to published update must stay under 5 milliseconds.
- Recovery: If an aggregation node fails, the service must restore correct state within 5 seconds — without replaying an entire day's worth of ticks from scratch.
- Availability: 99.99% uptime during active market hours.
Scale
| Dimension | Figure |
|---|---|
| Active symbols | 20,000 |
| Sustained tick rate | 100,000 ticks/second |
| Peak tick rate | 1,000,000 ticks/second |
| Concurrent downstream sessions | 50,000 |
| Raw tick retention | 7 years |
| VWAP snapshot retention | 90 days |
What to Cover
- Overall architecture — how components from feed handler through fan-out tier connect and interact.
- State representation — what data structure holds running cumulative sums, and how rolling windows are maintained efficiently.
- Correction handling — how a bust or amended trade propagates through session and rolling accumulators without reprocessing history.
- Pub/Sub and API design — protocols, conflation strategy, and the query interface for historical access.
- Key trade-offs — highlight at least two design decisions where you chose one approach over a reasonable alternative and explain why.
Hints
Hint 1
Start by sizing the problem: compute canonical tick size, daily byte volume, and session-state footprint. The 5ms p99 constraint rules out certain off-the-shelf components on the hot path — figure out which ones and why before picking your transport layer.
Hint 2
VWAP accumulators are additive: the only state you need per symbol is cumulative notional (Σ P×V) and cumulative volume (ΣV). Think about what data structure makes rolling windows O(1) amortized without storing every individual tick, and what data type prevents floating-point drift when busts subtract back out.
Hint 3
A bust is just a subtraction — you need to look up the original trade's price and quantity in O(1) to reverse it. Think about how you keep that lookup table, what key you use, and how it fits into your snapshot/recovery strategy.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Scope and Back-of-Envelope Sizing
Before drawing any boxes, lock in a few assumptions:
- Session VWAP resets per exchange at each market open. Consolidated VWAP across venues for the same symbol is derived by combining their accumulators.
- Not every print counts. Each exchange publishes condition codes marking certain trades — odd-lots, out-of-hours prints, derivatively priced crosses — as VWAP-ineligible. Normalization must carry an
eligibleboolean so the aggregator can skip them. - Rolling windows are driven by event time (the exchange's execution timestamp), not arrival time. This is essential for correctness when network jitter or line-B failover causes late delivery.
| Quantity | Estimate |
|---|---|
| Canonical tick size | ~64 bytes (symbol ID, venue, trade ID, price, qty, timestamp, flags, sequence) |
| Peak ingestion bandwidth | 1M ticks/s × 64 B ≈ 64 MB/s |
| Ticks per trading day | 100k/s × 23,400 s ≈ 2.3B ticks ≈ 150 GB raw |
| 7-year raw archive | 150 GB × 252 days × 7 ≈ 265 TB raw; ~30–50 TB compressed columnar |
| Session accumulator state | 20k symbols × ~64 B ≈ 1.3 MB (fits in L3 cache) |
| 1-hour rolling window state | 3,600 one-second buckets × 16 B × 20k symbols ≈ 1.2 GB RAM |
The 5ms p99 constraint immediately eliminates any component that does synchronous disk writes or runs a stop-the-world GC on the hot path — that shapes everything that follows.
2. API Design
Streaming (internal desks) Use Aeron or a similar kernel-bypass UDP transport for unconflated multicast. External clients connect via WebSocket or gRPC bidirectional streams.
subscribe(
symbols: string[],
metrics: enum[SESSION, ROLLING_5M, ROLLING_1H],
max_rate_hz: int // 0 = unconflated
)
→ stream VwapUpdate {
symbol, venue_or_CONSOLIDATED, metric,
vwap, cum_volume, cum_notional,
as_of_event_ts_ns, sequence, is_correction
}
Historical query (REST or gRPC)
GET /vwap/{symbol}?at={ts}&metric=SESSION # point-in-time
GET /vwap/{symbol}/eod?date=YYYY-MM-DD # official end-of-day figure
GET /vwap/{symbol}/range?start={ts}&end={ts} # arbitrary interval
3. Data Model
CanonicalTick fields: symbol_id, venue, trade_id, exec_ts_ns, price_fixed, qty, conditions, eligible, venue_seq_no.
Use fixed-point integers for price (e.g., price × 10⁸) and accumulate notional in int128 or scaled int64. Floating-point accumulators drift noticeably when busts repeatedly subtract values — fixed-point arithmetic is exact.
Session accumulator (per symbol, per venue, per day): (cum_notional, cum_volume, last_offset).
Rolling window: a fixed-size ring buffer of (bucket_notional, bucket_volume) slots at a chosen granularity (100ms buckets for the 5-minute window; 1s buckets for the 1-hour window), plus a running sum across the active window. Updates and expirations are both O(1) amortized.
Trade index (in-memory, current day): (venue, trade_id) → (exec_ts, price, qty). This is required for O(1) bust reversal.
4. Architecture
Exchanges (multicast, FIX, ITCH, ...)
│
[Feed Handlers] kernel-bypass NICs, A/B line arbitration,
│ gap detection, normalization → CanonicalTick
│ partition = hash(symbol_id) mod P
▼
[In-memory sequenced log] Aeron / Chronicle ring buffer
│ replicated synchronously to replica
│
├──async──► [Durable archive] Kafka → columnar tick store
│ (kdb+, ClickHouse, or Parquet on object storage)
▼
[Aggregator nodes] P partitions, single-threaded per partition
│ update session acc + rolling ring buffer
│ emit VwapUpdate on every eligible tick
├──► [Checkpoint store] snapshot every 1s (Redis or local file)
└──► [Snapshot writer] VWAP time-series DB (90-day retention)
▼
[Fan-out gateways] latest-value cache per (subscriber × symbol),
│ flush at subscriber's max_rate_hz
▼
50,000 subscribers [Query service] ← tick store + snapshots + prefix sums
Partitioning: consistent hashing on symbol_id with ~256 partitions. Because every venue's ticks for a given symbol land in the same partition, consolidated VWAP is computed by the same single thread that owns the symbol — no cross-partition coordination needed, no locks.
5. State Management and Rolling Windows
Session update on each eligible tick is O(1):
cum_notional += price * qty
cum_volume += qty
vwap = cum_notional / cum_volume
Rolling window update (also O(1) amortized):
- Compute the tick's target bucket index from its event timestamp.
- Walk forward from the last-seen bucket index, subtracting expired buckets from the running window sums and zeroing them.
- Add the tick's values to the target bucket and to the running window sums.
The 100ms bucket granularity for the 5-minute window means window boundaries are accurate to 100ms. Exact tick-level precision is possible with a deque but costs more memory and pointer chasing — only worthwhile if the product requires it.
6. Fault Tolerance: Recovery Under 5 Seconds
Two complementary mechanisms keep recovery fast:
Hot-hot replication: each partition is consumed by two aggregator instances in separate availability zones. Processing is fully deterministic, so both hold identical state. On failure, the fan-out tier switches to the surviving replica (deduplicated by sequence number) in milliseconds — no state transfer needed.
Checkpoint plus log replay, to rebuild the failed replica: every second, snapshot the session accumulator, rolling ring buffer, and trade index to a fast checkpoint store, tagged with the input log offset. A replacement node loads the latest snapshot and replays only the ticks since that offset. At 100k ticks/s sustained across 256 partitions, each partition sees roughly 400 ticks/s, so a 1-second replay window is a few hundred ticks — milliseconds of work. The full day's log is never replayed.
7. Handling Busts and Out-of-Order Ticks
Because the accumulator is purely additive, reversal is exact:
- Look up the original trade in the in-memory trade index using
(venue, trade_id)as the key. - Subtract
price × qtyfromcum_notionalandqtyfromcum_volumefor the session accumulator. - If the original trade's
exec_tsfalls within the current rolling window, subtract from its bucket and the running window sum. - A correction (amend) is a bust of the original followed by insertion of the revised print.
For out-of-order ticks: if the event timestamp falls inside the current window, it goes into the correct bucket. If it predates the window entirely, it updates only the session value. Per-venue sequence numbers detect gaps; trade_id makes ingestion idempotent against duplicate delivery.
Every correction emits a VwapUpdate with is_correction=true, and appends a correction record to the archive so historical point-in-time queries can be restated correctly.
8. Fan-out to 50,000 Subscribers
At peak, the system generates up to ~1M VWAP updates/second. Broadcasting every update to every subscriber is not feasible. Each fan-out gateway maintains a latest-value cache keyed by (subscriber, symbol). On each flush tick (driven by the subscriber's max_rate_hz), the gateway sends whatever the latest value is for each subscribed symbol.
Slow or rate-limited consumers lose intermediate updates through conflation, but never correctness — every VwapUpdate carries the full cumulative state, so the next message always reflects the true current value. Latency-sensitive internal desks subscribe to the unconflated Aeron multicast channel directly.
Gateways subscribe only to partitions their connected clients care about, which bounds the fanout compute per gateway instance.
9. Key Trade-offs
Custom in-memory log vs. Kafka on the hot path: Kafka with acks=all and replication rarely sustains p99 < 5ms at 1M messages/second under real market conditions. The hot path uses an Aeron-style in-memory ring buffer replicated synchronously to a single standby. Kafka sits downstream as the durable asynchronous archive — you get durability without paying for it in latency.
Hot-hot vs. hot-standby replication: hot-standby cuts resource cost roughly in half but adds seconds to failover while the standby catches up. Given the 5-second recovery SLA and the fact that session-VWAP state is tiny (~1.3 MB), the cost of running a second aggregator per partition is low and the latency benefit is large. Hot-hot is the right call here.
Fixed-point vs. floating-point arithmetic: a double has ~15 significant digits. After tens of millions of bust-and-correct cycles across a full day, floating-point error can accumulate into visible drift in published VWAP figures. Fixed-point integers at 10⁸ precision are exact and the performance difference on modern hardware is negligible.
Common mistakes to avoid: using wall-clock time rather than event time for rolling windows (causes incorrect VWAP under any latency jitter); storing every raw tick in the aggregator process rather than just the ring buffer (blows up memory); and forgetting that not all prints are VWAP-eligible (produces systematically incorrect figures without any obvious error signal).