Real-time Market Data Dispatch System
System DesignModel answerLast updated
Design an in-memory event matching engine that routes incoming market events to registered subscribers based on filtering criteria.
You need to architect the core logic for a real-time market data dispatch system that runs entirely in memory. The system receives a continuous stream of market events and must deliver each event to all interested subscribers based on their registered filters.
Here is a simplified interface in C++:
using HANDLE = int;
struct MarketEvent {
std::string ticker; // security identifier, e.g. "GOOGL"
int volume; // transaction volume
std::string venue; // exchange or venue code
};
class EventDispatcher {
public:
EventDispatcher() {}
// Invoked when a market event arrives from the data feed
void processEvent(const MarketEvent &event);
// Register a subscription with a filter pattern and callback
// Returns a handle for later cancellation
HANDLE registerSubscription(const MarketEvent &pattern,
std::function<void(const MarketEvent &)> handler);
// Remove an active subscription
void cancelSubscription(HANDLE handle);
private:
// Your internal design goes here
};
Matching semantics:
- A
patternacts as a template with optional wildcards - An incoming event matches a pattern when:
tickerfields are identical (exact string match)volume == 0in the pattern means "any volume" (wildcard)venue == ""in the pattern means "any venue" (wildcard)- Non-wildcard fields must match exactly
- When an event matches multiple subscriptions, invoke all corresponding handlers
Functional requirements:
registerSubscription(pattern, handler)— record a new subscription and return a unique handleprocessEvent(event)— find all matching subscriptions and execute their handlerscancelSubscription(handle)— deactivate a subscription so its handler stops receiving events
Constraints and performance targets:
- Up to 100,000 active subscriptions at any time
- 10,000+ events per second arrival rate
processEventmust be efficient: avoid scanning all subscriptions- Multiple threads may call these methods concurrently
- Memory usage should be reasonable for the scale
Your task:
Design the internal architecture of EventDispatcher:
- What data structures will you use to store subscriptions and enable fast lookups?
- How will each of the three operations work with those structures?
- Analyze time and space complexity
- Explain your concurrency strategy: how will you handle simultaneous reads (event processing) and writes (subscription changes) while maintaining correctness and high throughput?
Hints
Hint 1
An event can only match a small number of filter patterns — enumerate them explicitly
Hint 2
Readers far outnumber writers in this workload
Hint 3
After cancellation completes, can an old handler still fire if it's already running on another thread?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Real-time Market Data Dispatch System
Core Insight: Limited Filter Shapes
The critical observation is that each field in the pattern is either a specific value or a wildcard. For an event with (ticker=T, volume=V, venue=X), there are exactly four filter patterns that could match it:
(T, V, X)— all fields specified(T, V, "")— volume specified, venue is wildcard(T, 0, X)— ticker and venue specified, volume is wildcard(T, 0, "")— only ticker specified, both other fields wildcard
This means we can index subscriptions by their filter shape and probe at most four index locations per event, regardless of how many total subscriptions exist.
Data Structure Design
struct Subscription {
HANDLE id;
MarketEvent pattern;
std::function<void(const MarketEvent&)> handler;
std::atomic<bool> isActive{true};
};
using SubPtr = std::shared_ptr<Subscription>;
struct FilterKey {
int volume; // 0 = wildcard
std::string venue; // "" = wildcard
bool operator==(const FilterKey& other) const {
return volume == other.volume && venue == other.venue;
}
};
struct FilterKeyHash {
size_t operator()(const FilterKey& k) const {
return std::hash<int>{}(k.volume) ^
(std::hash<std::string>{}(k.venue) << 1);
}
};
// Immutable snapshot once published
struct TickerIndex {
std::unordered_map<FilterKey, std::vector<SubPtr>,
FilterKeyHash> subscriptionsByFilter;
};
struct Partition {
mutable std::shared_mutex mutex;
std::unordered_map<std::string, std::shared_ptr<TickerIndex>> indices;
};
class EventDispatcher {
static constexpr size_t NUM_PARTITIONS = 64;
std::array<Partition, NUM_PARTITIONS> partitions_;
std::mutex handleMapMutex_;
std::unordered_map<HANDLE, SubPtr> handleToSubscription_;
std::atomic<HANDLE> nextHandle_{1};
Partition& partitionFor(const std::string& ticker);
};
Key design choices:
- Partitioning by ticker hash: Distributes contention across 64 independent partitions. Different tickers never contend for the same lock.
- Copy-on-write snapshots: Each
TickerIndexis immutable once visible to readers. Updates create a new index copy. - Two-level map:
ticker → FilterKey → [subscriptions]. The inner key captures the wildcard pattern. - Active flag: Enables safe cancellation without blocking ongoing dispatches.
Operation Implementations
registerSubscription(pattern, handler)
- Generate unique handle:
h = nextHandle_.fetch_add(1) - Create
SubPtrwrapping the subscription - Store in global handle map under
handleMapMutex_ - Acquire exclusive lock on the appropriate partition
- Copy the existing
TickerIndexfor this ticker (or create empty) - Append subscription to
subscriptionsByFilter[{pattern.volume, pattern.venue}] - Replace the index pointer atomically and release lock
- Return handle
Complexity: O(K) where K is the number of subscriptions on this ticker (due to copy). If K is typically small (dozens), this is acceptable. Alternative: mutate in-place under exclusive lock for O(1) writes but longer critical sections.
processEvent(event)
- Acquire shared lock on partition for
event.ticker - Retrieve
shared_ptr<TickerIndex>and immediately copy it - Release lock (critical: callbacks run lock-free)
- Compute the four possible filter keys:
{event.volume, event.venue}{event.volume, ""}{0, event.venue}{0, ""}
- Deduplication check: if
event.volume == 0orevent.venue == "", some keys coincide — skip duplicates to avoid double-firing handlers - For each key, look up in the index
- For each subscription in the resulting vectors:
- Check
isActive == true(skip if false) - Invoke
handler(event)
- Check
Complexity: O(1) average lookup + O(M) where M is the number of matching active subscriptions. The four hash probes are constant cost regardless of total subscription count.
cancelSubscription(handle)
- Lock
handleMapMutex_and erase handle from map - If not found, return (idempotent)
- Set
subscription->isActive = false(atomic write) - Acquire exclusive lock on partition
- Copy the
TickerIndex, locate the subscription in its vector, and remove it - If the vector becomes empty, erase the
FilterKeyentry - If the ticker has no remaining subscriptions, erase the ticker entry
- Publish updated index and release lock
Complexity: O(K) or O(F) depending on implementation, where F is subscriptions under that specific filter. Typically small.
The isActive flag ensures that even if a thread holds an old snapshot, it will skip cancelled subscriptions. This prevents the race where cancellation returns but a handler still fires.
Complexity Summary
| Operation | Time (average case) | Notes |
|---|---|---|
processEvent | O(1 + M) | 4 hash probes; M = matched subs |
registerSubscription | O(K) | K = subs on ticker (copy-on-write cost) |
cancelSubscription | O(K) | Index copy and vector removal |
| Space | O(N + T) | N subscriptions, T distinct tickers |
Old index snapshots are reference-counted via shared_ptr and freed when no threads reference them.
Concurrency Strategy
Read-heavy workload optimization: With 10,000 events/sec and occasional subscription changes, reads dominate. The design prioritizes read throughput:
- Shared locks for reads: Multiple
processEventcalls can run concurrently on the same partition - Lock-free callback execution: Handlers run outside any lock, preventing slow callbacks from blocking the feed
- Partition independence: 64 partitions mean unrelated tickers have zero contention
Copy-on-write benefits:
- Readers hold locks only for pointer copy (nanoseconds)
- No blocking between readers
- Handlers can safely call
cancelSubscriptionon themselves (reentrancy-safe)
Alternative for even lower latency: Use std::atomic<std::shared_ptr<TickerIndex>> (C++20) to make reads completely lock-free. Writes still need coordination but are rare.
The active flag prevents use-after-cancel: Without it, a thread holding an old snapshot could invoke a cancelled handler after cancelSubscription returned. The atomic boolean provides a lightweight coordination point without reference counting or complex lifetime tracking.
Trade-offs and Alternatives
Global mutex (simplest baseline): One lock protecting all state. Correct but serializes everything. Acceptable only as a starting point before optimization.
In-place mutation vs copy-on-write:
- In-place: Writers take exclusive lock, modify vector directly. O(1) writes, but readers blocked during modification
- Copy-on-write (chosen): O(K) writes, but readers never blocked. Better fit for read-heavy load.
Per-subscription queues: If handlers are slow, dispatch (subscription, event) pairs to per-subscriber worker threads instead of invoking inline. Preserves ordering per subscription and prevents blocking the feed thread. Adds latency and complexity.
Lock-free skiplist or trie: More complex indexing structures can avoid copies, but hash tables are simpler and sufficient at this scale. Premature optimization without measurement is unnecessary.
Edge Cases and Production Considerations
- Handle reuse: Using an atomic counter prevents accidental reuse. In long-running systems, consider wrapping or using 64-bit handles.
- Wildcard-only events: If an incoming event itself has
volume=0orvenue="", carefully deduplicate probe keys to avoid duplicate handler invocations. - Memory growth: Cancelled subscriptions are removed from indices, so memory doesn't grow unbounded with churn.
- Metrics: In production, track per-ticker subscription counts, event latency distribution, and callback execution time to identify hotspots.
- Backpressure: If handler queues fill up (async dispatch), implement backpressure or circuit breakers to prevent unbounded memory growth.
This design balances simplicity, correctness, and performance for the stated requirements. It scales to 100K subscriptions and 10K+ events/sec on modern hardware while remaining maintainable and debuggable.