When you walk into a system‑design interview for a stock exchange, the first thing the interviewer wants is a clear picture of the problem space. They’ll test how you balance ultra‑low latency, consistency, and regulatory constraints while keeping the design understandable. Below is a practical walk‑through you can use as a mental checklist.
1. Clarify the Scope and Requirements
Start by asking clarifying questions. Typical functional requirements include:
- Order lifecycle: submit, modify, cancel, and execute orders.
- Matching logic: price‑time priority, support for market, limit, and stop orders.
- Market data feed: real‑time best‑bid/best‑ask (BBO), depth of book, trade ticks.
- User accounts: authentication, balances, margin checks.
- Regulatory reporting: audit logs, trade confirmations.
Non‑functional requirements often dominate the conversation:
| Requirement | Typical Target | Why It Matters |
|---|---|---|
| Latency | Sub‑millisecond for matching, <10 ms for market‑data broadcast | Traders lose money on delays |
| Availability | 99.99 % uptime for order entry, higher for market data | Continuous trading sessions |
| Consistency | Strong consistency for order book, eventual for market data | Prevents double‑fills |
| Scalability | Handle peak order spikes (e.g., IPOs) without degradation | Market volatility spikes |
| Security | End‑to‑end encryption, role‑based access | Protects financial data |
2. Identify Core Entities
A minimal data model revolves around four entities:
- Order: id, userId, side (buy/sell), type (limit/market/stop), price, quantity, timestamp, status.
- Trade: id, buyOrderId, sellOrderId, price, quantity, timestamp.
- OrderBook: per‑symbol collection of limit orders sorted by price and time.
- MarketDataSnapshot: best bid/ask, depth levels, last trade.
These entities drive the API surface and the internal flow.
3. Sketch the High‑Level Architecture
Client (Trader UI) -> API Gateway -> Order Service -> Matching Engine
| ^ |
v | v
Auth Service Persistence Layer Market‑Data Service
- API Gateway: throttles requests, validates schema, and routes to services.
- Auth Service: OAuth2/JWT, enforces role‑based permissions.
- Order Service: receives order commands, performs quick validation (balance, margin), and forwards to the Matching Engine.
- Matching Engine: the latency‑critical component, usually in‑process, lock‑free, using a priority queue for each side of the book.
- Persistence Layer: write‑ahead log (WAL) and a durable store (e.g., distributed log like Apache Pulsar or a replicated KV store) for recovery.
- Market‑Data Service: subscribes to trade events, builds BBO/depth snapshots, and pushes via a low‑latency multicast protocol (e.g., UDP or RDMA).
4. Deep Dive: The Matching Engine
4.1 Data Structures
- Bid side: max‑heap keyed by price, then FIFO queue per price level.
- Ask side: min‑heap keyed by price, then FIFO queue per price level.
- Order map: hash map from orderId to its position for O(1) cancel/modify.
4.2 Flow
- New order arrives.
- Engine checks the opposite side for price crossing.
- While price matches and quantity remains, pop the earliest opposite order, generate a Trade record, adjust quantities.
- If any quantity left, insert the remainder into the appropriate heap.
- Emit trade event to Market‑Data Service and write to WAL.
4.3 Fault Tolerance
- Keep the WAL in memory with periodic flush to SSD; on crash, replay logs to rebuild the order book.
- Replicate the WAL to a secondary node using a consensus protocol (Raft) for high availability.
5. Trade‑offs and Alternatives
| Aspect | Simple Approach | More Complex Approach |
|---|---|---|
| Matching latency | Single‑threaded lock‑free engine | Multi‑core sharding by symbol, lock‑free ring buffers |
| Persistence | Single‑node log file | Distributed log with partitioning |
| Market‑data delivery | HTTP long‑polling | UDP multicast with sequence numbers |
| Consistency | Strong for order book only | Strong across all services via two‑phase commit |
- Latency vs. scalability: Adding sharding improves throughput but introduces cross‑shard coordination for orders that span symbols (e.g., basket orders).
- Strong consistency: Guarantees no double‑fills but can hurt latency; many exchanges accept eventual consistency for market data to keep the feed fast.
- Regulatory audit: Storing immutable logs is non‑negotiable; you can use append‑only storage with cryptographic hashes for tamper evidence.
6. Sample API Sketch
POST /orders
{
"userId": "u123",
"symbol": "AAPL",
"side": "buy",
"type": "limit",
"price": 172.35,
"quantity": 100
}
Responses return an orderId and current status. Cancel and modify follow a similar pattern, using the same orderId.
7. Follow‑up Questions Interviewers Love
- How would you handle a sudden surge of orders (e.g., during an IPO)?
- Discuss dynamic scaling of the matching engine, back‑pressure at the API gateway, and pre‑warming of order‑book structures.
- What if you need to support multiple asset classes (stocks, options, futures)?
- Explain a modular design where each asset class plugs in its own matching rules while sharing the same persistence and market‑data pipelines.
- How do you guarantee exactly‑once delivery of trades to downstream systems?
- Use idempotent consumer design, sequence numbers, and persistent offsets.
- What monitoring and alerting would you put in place?
- Latency histograms per component, error rates, order‑book depth anomalies, and audit‑log integrity checks.
- How would you test this system?
- Unit tests for matching logic, property‑based tests for order‑book invariants, load‑testing with realistic order bursts, and chaos experiments on the persistence layer.
8. Putting It All Together
When you present your design, walk the interviewer through the flow: from a trader’s request, through authentication, order validation, matching, persistence, and finally market‑data broadcast. Highlight where you make trade‑offs (e.g., choosing a lock‑free single‑threaded engine for latency, then adding sharding for scalability). Keep the diagram simple; the goal is to show you understand the moving parts and can reason about their interactions.
How to practice this
- Sketch the diagram on paper without looking at any reference. Time yourself to stay under ten minutes.
- Explain the matching engine out loud as if you were teaching a colleague. Use Call Assistant to record yourself and verify you stay within a 90‑second window.
- Run a mock interview with a peer: ask them the follow‑up questions above and practice pivoting your answer while keeping the core story grounded in your own experience.
FAQ
- Q: Do I need to implement every component in the interview? A: No. Focus on the parts the interviewer probes—typically the matching engine and trade‑offs. Mention other components at a high level.
- Q: How much detail should I give about persistence? A: Explain the write‑ahead log concept and why replication matters; you don’t need to name a specific database unless asked.
- Q: What if the interviewer asks about latency numbers? A: Respond with typical industry targets (sub‑millisecond for matching, <10 ms for market‑data) and discuss how design choices affect them.
- Q: Should I talk about regulatory compliance? A: Yes, briefly note audit logs, trade confirmations, and how immutable storage helps meet reporting requirements.
Frequently asked questions
Do I need to implement every component in the interview?
No. Prioritize the core matching engine and order flow. Mention other services at a high level and be ready to dive deeper if the interviewer asks.
How much detail should I give about persistence?
Explain the write‑ahead log idea and why replication is needed for recovery. Specific database choices are optional unless the interviewer probes.
What if the interviewer asks about latency numbers?
State typical industry targets—sub‑millisecond for order matching and under ten milliseconds for market‑data dissemination—and relate them to your design decisions.
Should I talk about regulatory compliance?
Yes, briefly note immutable audit logs, trade confirmations, and how they fit into the persistence layer to satisfy reporting rules.
#system design#stock exchange#architecture#interview#matching engine#a stock exchange