The Problem#
A stock trading platform lets people see live stock prices and buy or sell shares. There are two very different systems behind that sentence, and the first step in the interview is to be clear which one you are building:
- A broker (Robinhood, Charles Schwab, Zerodha) is the app the customer uses. It shows prices, takes orders, checks that the customer can afford them, sends them on, and tracks what happened. It holds the customer's cash and shares.
- An exchange (Nasdaq, the New York Stock Exchange, the London Stock Exchange, or a crypto exchange such as Binance) is where buy and sell orders from many brokers actually meet. Its core is a matching engine that pairs buyers with sellers, at microsecond speeds, and publishes every trade to the world.
Robinhood is a broker, not an exchange. It routes customers' orders to other firms that execute them (mostly market makers), and it has been paid by those firms for the order flow. The usual interview version ("design Robinhood") asks for the broker, with the exchange given as an external API. A harder version ("design a stock exchange") asks for the matching engine itself. This page covers both: the broker in full, and then the exchange in depth, because a staff-level answer to either needs to understand the other.
Analogy. Think of an auction house and the agents who bid there. The exchange is the auction floor: a single, fair place where every bid is heard in strict order, and the auctioneer (the matching engine) announces each sale. The broker is your agent: you tell them "buy 10 shares of Apple, but pay no more than $190", they check you have the money, walk the order to the floor, and phone you when it is done. The agent must never lose your instruction or claim a sale that did not happen. The auctioneer must be fast and perfectly fair.
Background: a few market terms#
- Symbol (ticker): the short name of a listed company's stock, such as AAPL or META.
- Order: an instruction to buy or sell a number of shares of one symbol.
- Market order: buy or sell now, at the best available price. It specifies only the quantity. It fills almost always, but the price is not guaranteed.
- Limit order: buy or sell at a specified price or better. A buy limit at $190 fills only at $190 or less. If it cannot fill now, it rests on the exchange's order book until it fills, expires or is cancelled.
- Stop order: becomes a market order once the price crosses a trigger (for example "sell if the price falls to $180"). A stop-limit becomes a limit order instead.
- Time in force: how long an order lives. Day orders expire at the close. Good-til-cancelled (GTC) orders persist across days. Immediate-or-cancel (IOC) fills what it can now and cancels the rest. Fill-or-kill (FOK) fills completely now, or not at all.
- Bid and ask: the highest price a buyer is currently offering (bid) and the lowest price a seller is asking (ask). The gap between them is the spread.
- Order book: the list of all resting limit orders for one symbol, bids on one side and asks on the other, sorted by price.
- Fill (execution): a trade that happened. A 100-share order can fill in several partial fills at different prices.
- Market maker: a firm that continuously quotes both a bid and an ask, earning the spread and providing liquidity.
- Clearing and settlement: after a trade, a clearing house guarantees it, and settlement moves the shares and cash. US equities moved from settling two business days after the trade (T+2) to one (T+1) in May 2024.
Clarifying Questions#
| Question | Why it matters | Assumed answer |
|---|---|---|
| Are we building the broker or the exchange? | Completely different components and latency targets | Broker first (the common interview), with the exchange as an external API. Then the exchange internals as a deep dive |
| What does the exchange interface offer? | Our design depends on it | Synchronous place and cancel order requests, and a pushed trade feed per symbol with symbol, price, shares and the exchange's order id |
| Which instruments? | Options, crypto and fractional shares add rules | US stocks, market and limit orders. ETFs, options and crypto are out of scope |
| Extended-hours trading? | Changes order routing and validation | Out of scope. Regular market hours only |
| Do users see the full order book? | Book data is far heavier than price ticks | Out of scope. Users see the latest price (and best bid and ask) |
| How fresh must prices be? | Drives the fan-out design | Under about one second from the exchange to the screen |
| How many users? | Drives fan-out and order volume | About 20M users, a few million active at market open |
| Do we need history, charts and portfolios? | Separate read-heavy systems | Brief coverage only. The focus is live prices and orders |
Requirements#
Functional#
Core requirements (broker):
- Users can see live prices of stocks.
- Users can manage orders: create market and limit orders, cancel open orders, and see each order's status (pending, open, partially filled, filled, cancelled, rejected).
Below the line (out of scope):
- trading outside market hours;
- ETFs, options and crypto;
- a live, full order book view;
- historical charts and portfolio analytics (covered briefly in the Deep Dive blocks).
Exchange requirements (for the exchange deep dives): accept orders from member brokers, match them by price-time priority, publish executions to the brokers involved, and publish market data (trades and book changes) to everyone fairly.
Non-Functional#
- Order correctness and consistency: an order the user placed must never be lost, duplicated or shown in the wrong state. Fills and cancels must be reflected exactly once. This outranks availability.
- Low latency for prices: under about 1 second from exchange to the user's screen, and smooth updates at market open.
- Low latency for orders (broker): under about 200 ms from tap to the order reaching the exchange, in normal conditions.
- Scale: about 20M users, millions of concurrent price subscriptions at peak, and order bursts of 10 times the average at the open.
- High availability during market hours (9:30 to 16:00 US Eastern). Planned maintenance happens outside them.
- Auditability: every order, change and fill is recorded immutably, for regulators and disputes.
- Exchange-specific: matching latency in microseconds (tens of microseconds end to end within the exchange), determinism (the same inputs always give the same trades), fairness (strict ordering, and all participants receive market data at the same time), and recovery without losing an acknowledged order.
Capacity Estimation#
Users and price subscriptions (broker).
- 20M users, and about 3M concurrently connected at the busiest moments (the open, and big news days).
- Each active user watches about 10 symbols (a watchlist, plus the stock they are viewing): about 30M symbol subscriptions.
- About 8,000–10,000 US-listed stocks and ETFs, but interest is very skewed: the top 100 symbols get most of the views.
Price updates.
- A busy symbol trades many times a second. Across all US equities, the consolidated trade and quote feeds carry millions of messages per second at peaks.
- Users do not need every tick. A screen redraw several times a second is the limit of what a person can read. So we conflate: send each symbol to each client at most about 1–4 times per second, with the latest price.
- Worst case at 2 updates per second per subscription: 30M × 2 = 60M messages per second leaving our edge. At about 100 bytes each (symbol, price, change, time), that is about 6 GB/s, or 48 Gbit/s, of outbound traffic. This is the dominant cost and the main scaling problem. In practice, only a fraction of subscribed symbols change in any second, and mobile apps in the background are unsubscribed, so the real figure is several times lower.
Connections. 3M persistent connections (SSE or WebSocket). At about 50k–100k connections per well-tuned server, that is 30–60 push servers, plus headroom.
Orders (broker).
- Assume about 5M orders per day. The US regular session is 6.5 hours, or 23,400 seconds: about 210 orders per second on average.
- The open and big news events concentrate activity: plan for 5,000 orders per second peak, with short spikes above that.
- Each order generates a few status changes and one or more fills: about 5 writes per order, so peak writes are around 25k per second.
- Storage: about 1 KB per order with its events, so 5 GB per day, and about 1.3 TB per year. Brokers must keep records for years, so this grows into tens of TB, which is manageable.
Exchange (for the exchange deep dives).
- A major exchange handles hundreds of millions to billions of messages per day (orders, cancels and modifications) across thousands of symbols. Most orders are cancelled before they fill: cancel-to-trade ratios of 10 or more to 1 are common, because market makers constantly update their quotes.
- Peak rates reach hundreds of thousands to millions of messages per second for the whole exchange, very unevenly across symbols.
- Latency budget: from an order arriving at the exchange's gateway to its acknowledgement and market-data update, tens of microseconds. The matching step itself takes well under 10 microseconds on modern engines.
| Quantity | Estimate |
|---|---|
| Concurrent users at peak | ~3M |
| Symbol subscriptions | ~30M |
| Outbound price messages (worst case) | ~60M/s, ~6 GB/s |
| Push servers | 30–60 |
| Broker orders per day / peak per second | ~5M / ~5,000 |
| Broker order storage per year | ~1.3 TB |
| Exchange messages per second (peak) | 10^5–10^6 |
| Exchange internal latency target | tens of microseconds |
Core Entities#
- User / Account: a customer, their cash balance and their buying power (cash available for new orders).
- Symbol: a tradable instrument, with its trading status (open, halted) and tick size.
- Order: user, symbol, side (buy or sell), type (market, limit), quantity, limit price, time in force, status, our order id, the client's idempotency id, and the exchange's order id once it is known.
- Execution (fill): one trade against an order: quantity, price, time, the exchange's trade id.
- Position: how many shares of each symbol a user holds, and their average cost.
- Price (quote): the latest trade price, and the best bid and ask, for a symbol. It is ephemeral, and lives in memory and in streams.
- Exchange-side: the order book per symbol (price levels and the resting orders at each), the sequenced input log, and trades.
API Design#
Live prices (server push). Server-Sent Events are a good fit: the data flows one way, from server to client, over plain HTTP, with automatic reconnection.
GET /v1/prices/stream?symbols=AAPL,META,TSLA (Accept: text/event-stream)
-> event: price
data: {"symbol":"AAPL","price":"189.42","bid":"189.41","ask":"189.43","ts":1733238000123}
POST /v1/prices/subscriptions { "add": ["NVDA"], "remove": ["TSLA"] } (or reconnect with a new list)
Orders.
POST /v1/orders
{ "clientOrderId": "c2f1…", "symbol": "AAPL", "side": "buy",
"type": "limit", "quantity": 10, "limitPrice": "190.00", "timeInForce": "day" }
-> 201 { "orderId": "ord_81", "status": "pending" }
DELETE /v1/orders/{orderId} -> 202 { "status": "pending_cancel" }
GET /v1/orders?status=open&cursor=… -> list with fills
GET /v1/orders/{orderId} -> order with fills
Notes:
clientOrderIdis generated by the app per order. A retried POST with the same id returns the same order instead of placing a second one. It is the idempotency key, as in Idempotency and Safe Retries.- Prices are decimal strings, never floating point. Internally, prices are integers in a fixed unit (for example 1/10,000 of a dollar), and US stocks priced at $1 or more trade in ticks of one cent.
- Order status changes are pushed over the same event stream (
event: order), and also delivered by mobile push notification when the app is in the background. - The user id comes from the authentication token, never from the body.
The exchange's interface, as given:
placeOrder(symbol, side, type, qty, price, clientOrderId) -> exchangeOrderId, synchronous;cancelOrder(exchangeOrderId) -> ok or too late, synchronous;- a trade feed per symbol, pushed to us, with symbol, price, shares and the exchange's order id for each trade involving our orders.
Real exchanges use the FIX protocol (Financial Information eXchange, a tag-value text protocol from the 1990s) or faster binary protocols (such as Nasdaq's OUCH for orders and ITCH for market data) over dedicated network links, but the logical operations are the same.
High-Level Design#
We build the broker requirement by requirement, then look at the full picture. The exchange's internals follow in the Deep Dives.
1) Users can see live prices of stocks#
The naive approach. Each client polls GET /prices?symbols=… every second. For 3M clients, that is 3M requests per second, most returning unchanged prices, and every response is at least a second stale. Polling the exchange directly from each client is worse still: exchanges do not serve consumers, and one connection per user is impossible.
The better approach: ingest once, fan out many times.
- A Price Ingestor holds one connection to the exchange's market-data feed (or to a market-data vendor), receives every trade and quote, and keeps the latest price per symbol in memory.
- It conflates updates: for each symbol, it publishes at most a few updates per second, always the latest.
- It publishes to a pub/sub channel per symbol (Redis Pub/Sub, or a purpose-built broker).
- Push servers hold the clients' SSE connections. Each push server subscribes to the channels for the symbols its connected clients care about, and forwards each update to those clients.
- The latest price per symbol is also written to a cache (a Redis hash), so a client that connects or opens a new stock page gets the current price immediately, without waiting for the next tick.
The key property is that the work grows with symbols × push servers, not with users. A push server with 50,000 clients watching AAPL receives each AAPL update once, then loops over its local list of 50,000 connections.
2) Users can manage orders for stocks#
Placing an order:
- The client sends
POST /orderswith aclientOrderId. - The Order Service validates the order (symbol open for trading, quantity, price within tick size) and runs pre-trade risk checks: for a buy, enough buying power. It reserves the cash, so two orders cannot spend the same money.
- It writes the order to the Order DB with status
pending, before contacting the exchange. - It sends the order to the exchange through the Exchange Gateway, which holds the connections, credentials and protocol details.
- The exchange returns its order id. The service stores it and moves the order to
open. - The client gets the order id at step 3 or 5, depending on whether we return before or after the exchange's acknowledgement (we return after, within about 200 ms, unless the exchange is slow).
Cancelling marks the order pending_cancel first, then calls cancelOrder. The exchange may reply "too late", if it has already filled.
The Exchange Gateway is a separate component because exchange connectivity is special: long-lived sessions with sequence numbers, a small number of allow-listed IP addresses, rate limits per session, and a protocol (FIX or binary) that the rest of the system should not need to know.
3) Users see order status and fills#
The exchange reports fills through its trade feed, keyed by its order id, not ours.
- A Trade Processor consumes the feed. For each execution, it looks up our order by the exchange order id (an index on
orders.exchange_order_id, or a key-value map from exchange id to our id), and records the fill. - In one database transaction, it inserts the execution, updates the order's filled quantity and status (
partially_filledorfilled), updates the user's position, and releases or consumes the reserved cash. - It then publishes an order event to the user's push channel, so the app updates live, and triggers a push notification if the app is in the background.
Fills must be processed exactly once in effect: the feed may redeliver after a reconnect, so each execution is stored with the exchange's unique trade id, and a duplicate insert is ignored (Deep Dive 3).
The full high-level design#
Components:
- API gateway: authenticates users (short-lived tokens, device binding and multi-factor authentication for a money app), rate-limits per user, and routes REST and streaming traffic.
- Price Ingestor: one or a few redundant instances per feed. Parses the exchange or vendor feed, maintains the latest price per symbol, conflates, and publishes. Two instances run active-active, and subscribers ignore duplicates by sequence number.
- Per-symbol pub/sub: Redis Pub/Sub, or a fan-out tier built for the purpose. Channels are keyed by symbol.
- Latest-price cache: a Redis hash of symbol → latest quote, for the first paint of a screen.
- Push servers: hold SSE (or WebSocket) connections. They track which local connections want which symbols, subscribe to those channels, and forward updates. They also carry per-user order events.
- Order Service: validates orders, checks and reserves buying power, writes orders in
pendingstate first, calls the Exchange Gateway, and drives the order state machine. - Order DB: a relational database (PostgreSQL or MySQL), sharded by account id, holding accounts, orders, executions, positions and cash reservations. Strong consistency within a user's shard.
- Exchange Gateway: maintains sessions with exchanges or market makers. In the US, a broker also has to choose where to send each order, subject to its best-execution duty, so the gateway includes a smart order router.
- Trade Processor: consumes execution reports, maps them to our orders, and applies fills exactly once.
- Reconciliation and cleanup jobs: find orders stuck in
pendingorpending_cancel, query the exchange byclientOrderId, and fix their state. At the end of each day, they compare our executions with the clearing firm's records.
The exchange, in one picture. If the interviewer asks for the exchange instead, the shape is different: everything funnels into a single sequenced stream per symbol group, processed by a deterministic, in-memory matching engine.
The matching core is replicated by replaying the same sequenced input: backup engines process the identical journal and hold identical books, ready to take over (Deep Dive 7).
Key Flows#
Flow 1: place a limit order, then it fills in two parts#
Points to note:
- The order exists in our database before the exchange hears of it. If anything fails after that, we have a record to reconcile.
- The reservation is the limit price × quantity (plus an allowance for fees). When the order fills at a better price, the unused cash goes back to buying power.
- Fills are applied by the exchange's trade id, so a repeated execution message is a no-op.
Flow 2: the Order Service crashes after sending the order#
The clientOrderId is what makes this safe. It is sent to the exchange with the order, so we can ask "did you receive c2?" without knowing the exchange's id. If the exchange's API had no lookup by client id, the fallback would be to wait for the trade feed or for the end-of-day report, and to keep the reservation until then.
Flow 3: a cancel races with a fill#
The exchange, not the broker, decides which arrived first. The broker's job is to show the truth: pending_cancel means "we asked", and only the exchange's answer (cancelled, or a fill) moves the order to a final state. A partially filled order that is then cancelled ends as cancelled with a non-zero filled quantity.
Flow 4: inside the exchange (summary)#
- A broker's order arrives at a client gateway over a FIX or binary session. The gateway checks the message format and the session's throttle.
- Pre-trade risk checks the member's limits (maximum order size, price collars around the last trade, credit limits).
- The sequencer gives the order the next sequence number and appends it to the journal (durably, and to replicas).
- The matching engine applies it to the symbol's in-memory order book: it matches against resting orders on the other side, or rests on the book.
- Outputs are emitted in sequence: execution reports to both parties, a market-data update to everyone, and records for clearing and surveillance.
The whole path takes tens of microseconds. Deep Dives 6–9 explain how.
Data Model#
CREATE TABLE orders (
id BIGINT PRIMARY KEY, -- globally unique, embeds shard id
account_id BIGINT NOT NULL,
client_order_id TEXT NOT NULL,
exchange_order_id TEXT, -- NULL until acknowledged
symbol TEXT NOT NULL,
side TEXT NOT NULL CHECK (side IN ('buy','sell')),
order_type TEXT NOT NULL CHECK (order_type IN ('market','limit')),
quantity INT NOT NULL CHECK (quantity > 0),
limit_price BIGINT, -- 1/10000 dollar units
filled_qty INT NOT NULL DEFAULT 0 CHECK (filled_qty <= quantity),
status TEXT NOT NULL,
version BIGINT NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE (account_id, client_order_id) -- idempotent placement
);
CREATE UNIQUE INDEX ON orders (exchange_order_id) WHERE exchange_order_id IS NOT NULL;
CREATE INDEX ON orders (status, created_at)
WHERE status IN ('pending','pending_cancel'); -- cleanup job scan
CREATE TABLE executions (
trade_id TEXT PRIMARY KEY, -- exchange's id: dedupes fills
order_id BIGINT NOT NULL REFERENCES orders(id),
quantity INT NOT NULL CHECK (quantity > 0),
price BIGINT NOT NULL,
executed_at TIMESTAMPTZ NOT NULL
);Design notes:
- Shard by account id. Every write path for an order (reservation, order, fills, position) touches one account, so it stays in one shard and one local transaction. The order id embeds the shard id, so the Trade Processor can route a fill once it knows our order id.
- Mapping exchange ids to our orders. The trade feed carries the exchange's order id. A global lookup table (or key-value store) from
exchange_order_idtoorder_idis written when the order is acknowledged. Alternatively, many exchanges echo theclientOrderIdon executions. If ours embeds the shard id, routing needs no lookup at all. executions.trade_idas the primary key makes fill processing idempotent: a duplicate message fails the insert, and the transaction does nothing.filled_qty <= quantityis enforced by the database, as a last line of defence against double-applied fills.- Order events are an append-only history of every state change (received, sent, acknowledged, partially filled, cancel requested, cancelled). This is the user-visible audit trail, and feeds the regulatory one.
- Money and prices are integers. Cash in cents. Prices in 1/10,000 of a dollar, which allows the sub-penny prices that some venues permit for stocks under $1 and for some executions.
Database choice. The order path needs multi-row transactions (reserve cash, insert order, apply fills, update positions atomically), strict constraints and strong consistency, so a relational database is the natural fit: PostgreSQL or MySQL, sharded by account (or a distributed SQL database such as CockroachDB or Spanner, if manual sharding is unwanted). The volume (thousands of writes per second at peak) is modest for a sharded relational cluster. Prices are not stored in this database at all: they are ephemeral, and live in memory, in pub/sub and in a time-series store for charts. See Choosing a Database: A Decision Guide.
| Data | Store | Why |
|---|---|---|
| Accounts, orders, executions, positions, reservations | PostgreSQL or MySQL, sharded by account | Transactions, constraints, strong consistency |
| Exchange order id → our order id | Key-value store (Redis with persistence, or DynamoDB), or an index in the order DB | Fast lookup for the Trade Processor |
| Latest price per symbol | Redis hash | First paint of every screen |
| Live price fan-out | Redis Pub/Sub or a dedicated fan-out tier | Per-symbol channels |
| Price history (candles) | Time-series database (TimescaleDB, kdb+, ClickHouse) | Range scans by symbol and time |
| Order events, audit archive | Kafka, then immutable object storage (WORM) | Replay, regulatory retention |
| Exchange: order books | Memory of the matching engine only | Microsecond access. Rebuilt from the journal |
| Exchange: sequenced journal | Append-only files on local NVMe, replicated | Source of truth, replay and audit |
Deep Dives#
1. How do we scale live price updates to millions of users?#
The fan-out problem: a few thousand symbols, each changing many times a second, delivered to millions of screens, each wanting a different subset.
Step 1: choose the client protocol. Options, from Polling, Long Polling, SSE, WebSockets and Webhooks:
- Polling is simple, but wasteful and stale. It is acceptable only for a low-frequency fallback.
- Server-Sent Events (SSE) are one-way, server to client, over HTTP, with automatic reconnection and a
Last-Event-IDheader for resuming. Price streaming is one-way, so SSE fits well. Subscription changes go through ordinary REST calls. - WebSockets are two-way. They are useful if subscriptions change often and should travel on the same connection, or if the same socket carries other interactive features. Either choice is defensible. On mobile, the app holds the stream only in the foreground. In the background, only important events (fills, price alerts) are sent, as push notifications.
Step 2: reduce the data before fanning it out.
- Conflation: keep only the latest price per symbol in a short window (for example 250 ms), and publish that. A symbol that trades 500 times a second becomes 4 updates a second, with no visible loss to a human.
- Change filtering: skip publishing when the displayed value has not changed (the same price to the cent).
- Tiers: a watchlist row needs the last price and the daily change. A detailed stock page might want the best bid and ask too. Separate channels per tier (
AAPL:summary,AAPL:detail) keep small screens cheap.
Step 3: route updates only to servers that need them.
- Each push server keeps a map: symbol → set of local connections. When the first local client subscribes to a symbol, the server subscribes to that symbol's channel. When the last one leaves, it unsubscribes.
- The pub/sub layer then sends each update to only the push servers with at least one interested client. For a hot symbol like AAPL, that is every server. For an obscure one, maybe one.
- Total pub/sub traffic is about symbols × interested servers × updates per second. With 60 push servers, 5,000 active symbols and 2 updates per second, that is at most 600k messages per second inside the cluster, which a few Redis nodes can handle, compared with tens of millions at the edge.
Step 4: scale the pub/sub layer. One Redis node handles hundreds of thousands of pub/sub messages per second. Shard channels across several Redis nodes by symbol (Redis Cluster's sharded pub/sub, available from Redis 7, keeps a channel's traffic on one shard rather than broadcasting it across the whole cluster). For hot symbols, the cost is in the push servers' per-connection loop, not in Redis. Kafka is an alternative backbone, but its consumer-group model fits "every server needs this symbol" less naturally, and its latency is higher. It is better used for durable streams (order events, history) than for ephemeral ticks.
Step 5: make the push servers efficient.
- Pre-serialise each update once per server, then write the same bytes to every connection.
- Use an event-driven server (Netty, Go, Node, or Rust with async I/O) and tune the kernel (file descriptors, socket buffers) for 50k–100k connections per box.
- Slow consumers: a client on a bad mobile connection cannot keep up. Do not buffer unbounded data for it. Keep only the latest value per symbol for that connection, and overwrite older unsent values. This is conflation again, at the edge.
Step 6: handle connects and reconnects. On connect, the server sends a snapshot of the latest price for each subscribed symbol (from the latest-price cache), then streams deltas. A client that reconnects to a different server simply gets a new snapshot. No per-user state is lost, because prices are not per-user. A load balancer spreads new connections, and draining a server for deployment just causes clients to reconnect elsewhere.
Hot moments. At 9:30 the market opens and millions of users open the app within minutes. Pre-scale push servers before the open, jitter client reconnect timers, and serve the first paint from the cache so that a connection storm does not become a database storm. More detail is in Pattern: Pushing Realtime Updates.
2. How does the system track order updates?#
After the order reaches the exchange, its fate is reported asynchronously on the trade feed (and, at a real exchange, on the session's execution reports). Our job is to connect those reports to our orders, apply them correctly, and tell the user.
Mapping. The feed identifies orders by the exchange's order id. Options:
- Look it up: store
exchange_order_idon our order (and in a global lookup table if orders are sharded), written when the exchange acknowledges. Risk: a fill can arrive before we have saved the acknowledgement (they race), so the lookup misses. The Trade Processor then retries briefly, or parks the fill and replays it when the acknowledgement lands. - Echo our id: if the exchange returns our
clientOrderIdon executions (FIX execution reports carry the client order id), we route directly, with no race. Embedding the shard id in the client order id removes the global lookup.
Applying a fill, in one transaction on the account's shard:
BEGIN;
INSERT INTO executions (trade_id, order_id, quantity, price, executed_at)
VALUES (:tid, :oid, :qty, :px, :ts) ON CONFLICT (trade_id) DO NOTHING;
-- if 0 rows inserted: duplicate, COMMIT and stop
UPDATE orders SET filled_qty = filled_qty + :qty,
status = CASE WHEN filled_qty + :qty = quantity THEN 'filled' ELSE 'partially_filled' END,
version = version + 1
WHERE id = :oid AND filled_qty + :qty <= quantity;
-- buys: positions += qty, cash -= qty * px, reservation reduced; sells: the reverse
COMMIT;Ordering. Fills for one order should be applied in order, but each fill is additive, so the final result is correct even if two fills arrive out of order. Status messages that are not additive (cancelled, rejected) use guarded transitions, so a late "open" never overwrites "filled".
Throughput. Partition the feed processing by account (or by our order id), so all events for one order are handled by one consumer in order, while thousands of accounts are processed in parallel. If the feed is consumed into Kafka first, the topic is keyed by order id, and the Trade Processor is a consumer group.
Telling the user. After commit, the processor publishes an order event to a per-user channel. The push server holding that user's connection forwards it. A user may have several devices: each connection subscribes to the user's channel. If no connection exists, a mobile push notification is sent ("Your order for 10 AAPL filled at $189.98"). The client always re-fetches the order from the API on reconnect, so missed events are harmless.
Missed feed messages. Feeds carry sequence numbers. A gap means lost messages: the processor requests a replay from the exchange (exchanges offer retransmission or recovery services), and the end-of-day reconciliation with the clearing firm is the final backstop.
3. How does the system manage order consistency?#
The broker has two sources of truth that can disagree: its database and the exchange. An order can exist in one but not the other, if a crash, timeout or network split lands at the wrong moment. The design must make every disagreement detectable and fixable, and must never let a user's money or shares be counted twice.
The rules:
- Write before sending. The order is stored as
pending, with itsclientOrderId, before any network call to the exchange. The worst case is then "we have a record, the exchange may not": safe, and detectable. The reverse order (send, then write) risks a live order at the exchange that we know nothing about: unsafe, and invisible. - Use the
clientOrderIdend to end. It is generated by the app (so retries from the app are deduplicated by ourUNIQUE (account_id, client_order_id)constraint), and it is passed to the exchange (so the exchange can deduplicate our retries, and we can look the order up without its id). - Treat a timeout as "unknown", not "failed". If
placeOrdertimes out, the order stayspending. Do not tell the user it failed, and do not release the cash. The cleanup job (or an immediate retry with the sameclientOrderId, which the exchange treats as a duplicate) settles it. - Cancels are requests.
pending_cancelholds until the exchange confirms the cancel, or a fill makes the cancel moot. - A cleanup job scans orders in
pendingorpending_cancelolder than a few seconds, and asks the exchange for their status byclientOrderId. It moves them toopen,filled,cancelledorrejected, and fixes reservations. - End-of-day reconciliation. Every execution in our database must match the clearing firm's records, and vice versa. Breaks are investigated before the next session.
The order state machine:
Every transition is a guarded update (WHERE status IN (…)), and every transition appends an order_events row in the same transaction. A message that tries an invalid transition (a cancel confirmation for a filled order) changes nothing and is logged.
Why not a distributed transaction with the exchange? The exchange does not take part in our transactions. Its interface is request and response plus a feed, so "unknown" states are unavoidable, and must be designed for. This is the same problem as an acquirer timeout in the payment-system case, and the same answer: record intent first, use a unique reference, query or replay to recover, and reconcile.
Buying power consistency. Two orders placed at the same moment from two devices must not both spend the last $1,000. The reservation is a guarded update on the account row (UPDATE accounts SET buying_power = buying_power - :amt WHERE id = :a AND buying_power >= :amt), in the same transaction as the order insert. Market buys reserve the last price × quantity plus a buffer (for example 5 percent), because the fill price is not known in advance. Any unused reservation is released when the order completes.
4. Broker vs exchange: who does what?#
Interviewers often probe whether the candidate knows the real structure of the market, because it changes the design.
| Broker (Robinhood, Schwab) | Exchange (Nasdaq, NYSE) | Market maker (wholesaler) | |
|---|---|---|---|
| Customers | Retail investors | Member firms: brokers, market makers | Brokers that route order flow to it |
| Main job | Accounts, custody, buying power, order entry and routing, statements | Run the order book, match fairly, publish market data | Fill orders from its own inventory, often at or better than the best public price |
| Latency focus | Milliseconds (humans) | Microseconds | Microseconds |
| Regulated as | Broker-dealer (in the US, by the SEC and FINRA) | National securities exchange | Broker-dealer |
How a US retail order actually flows. The broker receives the order and has a best-execution duty: it must seek the most favourable terms reasonably available. US rules (Regulation NMS) define the National Best Bid and Offer (NBBO): the highest bid and lowest offer across all exchanges, published by the securities information processors. Most retail market orders are sent not to an exchange but to wholesale market makers (firms such as Citadel Securities and Virtu), which fill them internally, typically at or slightly better than the NBBO. Brokers like Robinhood have been paid by those firms for routing the orders, a practice called payment for order flow (PFOF). It funds commission-free trading, and it is controversial, because it creates a potential conflict of interest. PFOF is banned in some jurisdictions, such as the UK.
Smart order routing. A broker connected to many venues chooses, per order, where to send it: an exchange, a market maker or an alternative trading system. It considers the price, the probability of a fill and the fees. Routing reports (Rule 606 reports in the US) disclose where brokers send orders and what they are paid.
After the trade: clearing and settlement. In the US, trades are cleared through the National Securities Clearing Corporation (NSCC), part of DTCC, which becomes the counterparty to both sides and guarantees completion. Settlement happens one business day after the trade (T+1, since May 2024). Shares are held electronically by a central depository (DTC), and brokers keep customer records of ownership on their own books. This is why a broker's internal ledger of cash and positions must be reconciled daily against the clearing firm and the depository.
Collateral and the clearing house. Because trades settle a day later, the clearing house demands deposits from brokers to cover the risk that a broker fails before settlement. The deposits grow when volatility and concentrated buying grow. In January 2021, during the GameStop surge, Robinhood temporarily restricted purchases of some stocks after a sharp jump in its clearing-house deposit requirement. It is a good real-world reminder that a broker's capacity limits include capital, not just servers.
Design implications for the broker:
- the exchange gateway is really a routing layer to many venues, each with its own protocol and session;
- execution reports can come from many venues for one order (if it is split);
- risk checks protect both the customer (buying power) and the broker (concentration, margin and clearing-deposit exposure);
- the authoritative record of positions is shared with the clearing firm, so reconciliation is daily and mandatory.
5. What risk checks run before an order is sent?#
A broker is liable for its customers' orders: if a customer buys shares they cannot pay for, the broker still has to settle the trade. So pre-trade checks run synchronously on the order path, in a few milliseconds.
Customer checks:
- Buying power. Cash available minus open reservations, plus margin for margin accounts. Buys reserve funds (Deep Dive 3). Sells reserve shares: a sell order must not exceed the shares held minus shares already committed to other open sell orders, or the customer could sell the same shares twice.
- Pattern day trader (PDT) rule. FINRA rules have treated margin accounts with four or more day trades in five business days as pattern day traders, which requires at least $25,000 of equity in the account. The broker must count day trades and block or warn. (Regulators have been reviewing this rule. Check the current rule for a real design.)
- Instrument checks: the symbol is tradable and not halted, the price is within the tick size, and restricted or hard-to-borrow securities are handled.
- Fat-finger checks: reject a limit price far from the last trade (for example more than 10 percent away), or an order value far above the customer's usual size, unless confirmed.
Broker-level checks:
- Concentration and exposure across all customers, which drive clearing-house deposits (Deep Dive 4).
- Rate limits per customer and globally, to protect exchange sessions, which have message limits.
- Market-access controls. US rules (the SEC's Market Access Rule, 15c3-5) require brokers with market access to have pre-trade risk controls such as credit and capital thresholds and erroneous-order checks. Exchanges add their own price collars and throttles.
Fractional shares and dollar-based orders. "Buy $10 of Amazon" is not an exchange order: exchanges trade whole shares. The broker aggregates fractional orders, buys or sells whole shares in its own account, and allocates fractions to customers in its ledger. This is a ledger problem inside the broker, with rounding and allocation rules, much like the payment-system ledger.
Latency. These checks need the account's balances, reservations and positions. Keep them in the account's database shard (read within the same transaction as the reservation), or in an in-memory risk cache updated by the same events. A risk check that reads stale data is not a risk check.
6. How does a matching engine work?#
This is the heart of an exchange. The core idea is simple. Making it fast and deterministic is where the engineering goes.
The order book. For each symbol, there are two sides:
- Bids (buy orders), sorted by price descending: the highest bid is the best.
- Asks (sell orders), sorted by price ascending: the lowest ask is the best.
- At each price level, orders queue in time order (first in, first out).
Price-time priority. An incoming order matches against the best price on the other side first. Among orders at the same price, the earliest one fills first. This is the rule on most equity exchanges. Some markets (certain futures, for example) use pro-rata matching instead, where orders at the best price share each fill in proportion to their size.
Matching an incoming order:
- A buy limit at P matches while the best ask ≤ P: fill against the first order at the best ask, up to the smaller of the two quantities. Remove a fully filled resting order. Move to the next order, then the next level.
- When no ask ≤ P remains, any remaining quantity rests on the bid side at P (for a day or GTC order), or is cancelled (for IOC). A FOK order checks first whether the full quantity can fill, and does nothing if not.
- A market buy matches against asks at any price until it is filled. Exchanges protect against "walking the book" too far with price collars, or by converting market orders to aggressive limit orders.
- Each fill produces a trade at the resting order's price (the passive side sets the price), and execution reports for both parties.
Worked example. The AAPL book holds asks of 100 shares @ 190.01 (order A, 09:30:01) and 50 @ 190.01 (order B, 09:30:02), and 200 @ 190.03 (order C). A buy limit arrives for 180 @ 190.02.
- It fills 100 @ 190.01 against A (A is removed), then 50 @ 190.01 against B (B is removed).
- 30 shares remain. The next ask is 190.03, above the limit of 190.02, so matching stops.
- 30 rest as a new bid @ 190.02, which is now the best bid. The spread is 190.02 to 190.03.
- Market data publishes two trades (100 and 50 @ 190.01), the removal of the 190.01 level, and a new bid level at 190.02.
Data structures. Operations that must be fast: add an order, cancel an order by id, find the best price, and walk orders at the best price.
- Price levels in a sorted structure: a balanced tree (red-black tree) or skip list gives O(log n) insert of a new level. Many production engines instead use an array indexed by price in ticks around the current price, which makes finding a level a direct index, and keeps the best price in a variable that moves as levels empty.
- Orders within a level in a doubly linked list: append at the tail, fill from the head, and remove any node in O(1) given a pointer to it.
- A hash map from order id to node: cancels are the most common message, and they must find the order instantly.
- Each level also keeps its total quantity, so market data (the quantity at each price) is a read, not a sum.
With these, add, cancel and the fill of each order are all constant time, apart from the occasional new price level, and the whole book for an active symbol fits easily in the CPU caches and memory of one machine.
7. Why a sequencer, and how does event sourcing make the exchange fault-tolerant?#
The problem. The matching engine must be fast (no disk or network waits per order), fair (a strict order of arrival), and must never lose an acknowledged order, even if its machine dies.
The answer: a sequenced, replicated input log, and a deterministic state machine.
- Every input (new order, cancel, modification, and even timer events such as the market close) goes through the sequencer, which gives it the next number in a single sequence per matching shard. This defines the order of events. Fairness becomes "process in sequence order".
- The sequenced input is journalled (appended to a log on fast local storage) and replicated to one or more backup machines before its result is released to the outside world.
- The matching engine is a deterministic function: given the same starting state and the same sequence of inputs, it always produces the same book and the same trades. No wall-clock reads (timestamps come from the sequenced event), no random numbers, no iteration over unordered hash maps where the order matters, and no dependence on thread timing.
- Backup engines consume the same journal and run the same logic. They hold an identical book at every sequence number. If the primary fails, a backup takes over from the last sequence number, without losing a confirmed order.
This is event sourcing: the log of inputs is the source of truth, and the order books are a derived state that can be rebuilt by replay (see Event Sourcing and CQRS). The same journal feeds the audit trail, regulatory reporting and the market-data publisher.
Snapshots. Replaying a whole day of inputs from the start can take minutes. The engine periodically writes a snapshot of its books, tagged with a sequence number. Recovery loads the latest snapshot and replays only the inputs after it.
Outputs are also sequenced. Execution reports and market-data messages carry the output sequence number. Downstream consumers (brokers, market-data subscribers) detect gaps, and can request retransmission. Because outputs are derived deterministically from inputs, a backup engine can regenerate any output after a failover, and duplicates are recognisable by sequence number.
Leader election. Who is primary must be decided safely, so two engines never both publish results. Exchanges have long used custom primary and backup schemes with careful fencing. A consensus protocol such as Raft is a clean modern way to replicate the sequenced log and elect the leader (see Consensus: Raft and Paxos), at the cost of a network round trip to a majority before an input is committed, which is a few to tens of microseconds within a data centre on fast networks.
Partitioning. One sequence for the whole exchange would be a bottleneck. Symbols are independent (an AAPL order never matches against a TSLA order), so the exchange shards symbols across matching engines, each with its own sequence. Multi-leg orders spanning several symbols (common in options) are harder, and need either co-location of the related symbols on one shard, or special handling.
Determinism traps that real systems hit: floating-point differences between CPUs (use integer prices), hash-map iteration order, garbage-collection pauses affecting timer events (timers must be sequenced inputs), and code version skew between primary and backup (deploy both together, and never change logic mid-session).
8. How do exchanges get latency down to microseconds?#
For a broker, 100 ms is fine: a human is on the other end. For an exchange and its professional participants, a few microseconds decide who trades first, so the exchange's design is about predictable, very low latency, at the median and especially at the tail.
Typical numbers to reason with (orders of magnitude, see Numbers Every Engineer Should Know):
| Operation | Approximate time |
|---|---|
| L1 cache reference | ~1 ns |
| Main memory reference | ~100 ns |
| Kernel network stack, one direction | ~5–20 μs |
| Kernel-bypass networking, one direction | ~1–2 μs |
| Round trip in a data centre (standard networking) | tens to hundreds of μs |
| NVMe write | ~10–100 μs |
| A context switch | a few μs |
| A garbage-collection pause (untuned) | milliseconds |
At these scales, a single disk write, lock contention, a context switch or a GC pause is larger than the whole matching step. So:
1. Single-threaded business logic. The matching engine for a shard runs on one thread, processing events one at a time from an in-memory queue. There are no locks, because there is nothing to share. This sounds slow, but it avoids all coordination costs, and keeps data hot in the CPU cache. The LMAX exchange in London became well known for this: Martin Fowler's 2011 article "The LMAX Architecture" describes a single-threaded business logic processor handling about 6 million orders per second.
2. Ring buffers instead of queues. The LMAX Disruptor (described in a 2011 technical paper by Martin Thompson and colleagues at LMAX) is a pre-allocated ring buffer through which events pass between threads: the input reader, the journaller, the replicator and the business logic. Each consumer tracks its own sequence number. Producers and consumers coordinate with memory barriers rather than locks, entries are reused (no allocation, so no garbage), and stages can run in parallel on the same entries (journalling and replication happen side by side). The business logic processes an event only once the journaller and replicator have handled it.
3. Keep everything in memory. The books live in RAM. The only I/O on the critical path is the sequential journal write (or replication to a backup's memory), and some designs consider an event durable once it is in the memory of two machines, writing to disk asynchronously.
4. Mechanical sympathy.
- Pin threads to CPU cores, and isolate those cores from the operating system's scheduler, so the matching thread is never descheduled.
- Busy-spin rather than block: a waiting thread loops on the ring buffer's sequence instead of sleeping, trading CPU for microseconds of wake-up time.
- Avoid allocation in the hot path (object pools, pre-allocated arrays). In Java, this keeps the garbage collector quiet. Many engines use C++, Rust or carefully written "garbage-free" Java.
- Cache-friendly layouts: arrays of primitive fields rather than pointer-heavy objects. False sharing (two cores writing different variables on the same 64-byte cache line) is avoided by padding.
- Memory-mapped files for the journal, so writing is a memory copy, and the OS flushes pages.
5. Network. Kernel bypass (for example DPDK, or vendor stacks such as Solarflare's OpenOnload) moves packet processing into user space, avoiding system calls and interrupts. Specialised network cards, and even FPGAs that parse and filter feeds in hardware, are used by both exchanges and trading firms. Binary protocols with fixed layouts (such as ITCH and OUCH, or SBE, Simple Binary Encoding) avoid parsing costs that text protocols like FIX incur.
6. Co-location. Trading firms rent rack space in the exchange's own data centre, to cut the distance (light in fibre covers about 200 m per microsecond, so 1 km is about 5 μs). Exchanges equalise cable lengths for co-located customers, so no one gets an edge from rack position.
7. Measure the tail. Track p99, p99.9 and the maximum, not the average. One GC pause a minute ruins an exchange's reputation even with a great median. Timestamp every stage with hardware clocks, and alert on jitter.
9. How does an exchange publish market data fairly?#
Market data is the exchange's other big output: every change to every book, to thousands of subscribers, at the same time for everyone.
Levels of detail:
- Level 1 (top of book): the best bid and ask, with their sizes, and the last trade. Enough for a retail app.
- Level 2 (depth): the total quantity at each of the best N price levels on each side.
- Level 3 (order by order): every add, cancel, modify and execution of individual orders. Professional traders rebuild the full book from this. Nasdaq's TotalView-ITCH feed is an example of an order-by-order feed.
Incremental feed plus snapshots. The feed is a stream of deltas ("order 123 added: buy 100 @ 190.02", "order 123 executed 40"), each with a sequence number. A subscriber builds its own copy of the book by applying them in order. To start, or after losing data, it fetches a snapshot of the book at sequence N, then applies deltas after N.
Multicast for fairness and scale. Sending the same packet separately to 1,000 subscribers over TCP takes 1,000 sends, and the last subscriber receives it later than the first. Exchanges instead publish over UDP multicast: the network switches copy each packet to every subscriber port at the same moment. It is efficient (one send) and fair (no subscriber is first by construction). It is unreliable, so:
- every packet carries a sequence number;
- feeds are often sent twice, on two independent networks (A and B feeds). Subscribers take whichever copy arrives first, and fill gaps from the other;
- a separate retransmission service (over TCP) and snapshot service let subscribers recover lost packets.
Ordering with executions. A participant's private execution report and the public market-data update for the same trade are both outputs of the same sequenced event. Exchanges design their publication order and timing carefully so that the order of information is consistent and predictable for everyone.
Speed bumps. IEX, a US exchange launched in 2016, delays incoming orders and outgoing data by about 350 microseconds using a long coil of fibre optic cable. It is designed to reduce the advantage of the very fastest traders over slower ones. This is a deliberate trade of latency for fairness, and shows that "faster" is a design choice, not a law.
Downstream: from exchange feeds to retail screens. In the US, the securities information processors consolidate all exchanges' top-of-book data into the official NBBO and the consolidated tape. Data vendors and brokers consume these feeds (or direct exchange feeds), and then do exactly what our broker's Price Ingestor does: conflate to human speed, and fan out over the internet. Candlestick charts (open, high, low, close and volume per minute or day) are computed downstream from the trade stream, by a stream processor, and stored in a time-series database (see Time-Series Databases).
10. Consistency and the audit trail#
Financial markets are regulated heavily, and "show us exactly what happened, in what order, and why" is a routine request. The audit trail is a first-class requirement, not a log file.
At the exchange. The sequenced input journal is the audit trail: every order, cancel and modification, in the exact order processed, with timestamps. Because the engine is deterministic, the journal plus the code version reproduce every trade exactly, which makes it possible to investigate a disputed trade by replaying the session. Journals are kept immutably (write-once storage) for years.
At the broker.
- Every order state change appends to
order_events, in the same transaction as the change. Nothing is updated in place without an event that explains it. - Every request from the client is logged with its user, device, IP address and time (who asked for what).
- Every message to and from each venue is archived, with the venue's ids and sequence numbers.
- Cash and positions are kept as a double-entry ledger (each trade debits cash and credits shares, or the reverse), as in the payment-system case, so balances are always explainable.
Regulation shapes the storage. Examples, at a high level: US broker-dealers must keep certain records in a non-rewriteable, non-erasable form or an approved equivalent (SEC Rule 17a-4), and US firms report order events to the Consolidated Audit Trail (CAT), which lets regulators trace an order across every firm and venue that touched it. In the EU, MiFID II requires timestamp accuracy tied to UTC, with very tight tolerances (on the order of 100 microseconds) for high-frequency trading venues and firms. So clock synchronisation (PTP, the Precision Time Protocol, with GPS-disciplined clocks) is part of the architecture (see Time, Clocks and Ordering).
Consistency across systems.
- Within the broker: strong consistency for orders, cash and positions (one shard, one transaction per change).
- Broker vs exchange: eventual, through acknowledgements, execution reports and the cleanup job (Deep Dive 3), with sequence numbers to detect gaps.
- Broker vs clearing firm: daily reconciliation of trades, positions and cash. Breaks are worked before the next open.
- User-facing views (portfolio value, charts) are read models built from events, and may lag by a second. Order status shown to the user comes from the order database or its events, never from a stale cache.
11. How do we scale the broker and the exchange?#
The broker.
- Order Service: stateless, scaled horizontally. At 5,000 orders per second peak and a few milliseconds of work each, a modest fleet suffices. The constraint is the exchange sessions' message rates and the database.
- Order DB: shard by account id. At 25k writes per second at peak, 8–16 shards with replicas give ample headroom. Hot accounts are rare in retail. Institutional accounts with huge order volume get dedicated shards.
- Trade Processor: partitioned by account or order id, so it scales with the number of partitions.
- Price fan-out: Deep Dive 1. Push servers scale with connections, and the pub/sub layer with symbols × servers.
- The market-open spike: pre-scale everything before 9:30 (the time is known in advance), warm caches, and queue order submissions with admission control if the exchange sessions saturate, telling users "queued" rather than failing. Load test against a recorded open. Robinhood had well-publicised outages on heavy-volume days in March 2020, which shows why this deserves first-class planning.
The exchange.
- Shard by symbol across matching engines. Assign symbols to shards by expected activity, so that each engine's load is balanced, and the busiest symbols get their own engine.
- Gateways scale out by member sessions, and do the stateless work (parsing, validation, session throttles) before the sequencer.
- Market data scales with multicast (one send, any number of subscribers), plus separate snapshot and retransmission services.
- Vertical before horizontal: a single symbol's book is one sequence, so its throughput is the single-thread throughput. That is why the latency work in Deep Dive 8 matters: there is no horizontal scaling for one hot symbol.
12. Market safety controls and failure handling#
Markets need mechanisms that stop trading when something goes badly wrong, and the system must implement them as part of the state machine.
- Trading halts. A symbol can be halted (pending news, or a regulatory halt). The matching engine rejects or queues new orders, and keeps resting orders. Halt and resume are sequenced inputs, like orders, so every replica agrees on exactly when they happened.
- Limit Up-Limit Down (LULD). In US equities, each stock has a price band around its recent average price. Trades outside the band are prevented, and if the price stays at the band edge, trading pauses briefly. The engine computes the bands from its own trade stream.
- Market-wide circuit breakers. In the US, declines in the S&P 500 of 7 percent and 13 percent halt trading for 15 minutes (if they happen before 3:25 pm), and a 20 percent decline halts trading for the rest of the day.
- Auctions. The opening and closing prices are set by auctions, not continuous matching. Orders accumulate, and the engine computes the single price that maximises the executed volume, then executes all matching orders at that price. Re-openings after halts also use auctions. This is a separate matching mode in the engine.
- Kill switches. Exchanges and brokers can cancel all of a member's (or an algorithm's) open orders and block new ones instantly. The Knight Capital incident in August 2012, in which a faulty deployment of trading software sent a flood of unintended orders and lost the firm about $440 million in under an hour, is the standard cautionary tale about deployment discipline and kill switches.
- Failover. The primary matching engine fails over to a backup with an identical state (Deep Dive 7). In-flight orders that were sequenced are not lost. Gateways reconnect to the new primary, and members resend unacknowledged orders with the same client order ids, which are deduplicated.
- Broker-side failures. If an exchange session drops, the gateway reconnects and uses session sequence numbers to recover missed messages. If a venue is down, the router stops sending to it. If the broker itself goes down, resting orders stay live at the exchange: users must be able to cancel them once the broker is back, and the system must never assume that an order is dead because the broker lost contact with it.
Bottlenecks and Failure Modes#
| Failure / hotspot | Impact | Mitigation |
|---|---|---|
| Market-open connection and order storm | Push servers and Order Service overloaded, app outages on the busiest days | Pre-scale before 9:30, jittered reconnects, first paint from cache, admission control and queued orders |
| Hot symbol fan-out (a meme stock) | Every push server busy forwarding one symbol | Conflation, serialise once per server, slow-consumer overwrite, more push servers |
| Order Service crashes after sending to the exchange | Order live at the exchange but PENDING with no id at the broker | Write PENDING first, clientOrderId sent to the exchange, cleanup job queries by clientOrderId |
| Exchange call times out | Unknown order state, risk of a duplicate order on retry | Treat as unknown, retry with the same clientOrderId, never with a new one |
| Fill arrives before the ack is saved | Trade Processor cannot map the fill | Echo clientOrderId on executions, or park and retry the fill |
| Duplicate execution messages | Position and cash double-counted | executions.trade_id primary key, guarded filled_qty update |
| Two devices spend the same buying power | Customer overspends, broker liable | Guarded reservation update in the same transaction as the order insert |
| Trade-feed gap (lost messages) | Missed fills, wrong positions | Sequence numbers, retransmission requests, daily reconciliation with clearing |
| Matching engine primary dies | Trading stops on its symbols | Hot backup replaying the same sequenced journal, fenced failover, members resend with the same ids |
| GC pause or OS jitter in the matching engine | Latency spikes, unfairness | Garbage-free code, pinned and isolated cores, busy-spin, tail-latency monitoring |
| Single hot symbol on one engine | One sequence saturates | Dedicated engine for the busiest symbols, optimise the single-thread path |
| Faulty algorithm or deployment floods orders | Huge unintended positions and losses | Pre-trade risk limits, rate limits, kill switches, staged rollouts |
What Interviewers Expect#
Mid-level. Clarifies that Robinhood is a broker and the exchange is external. Designs live prices with SSE or WebSockets fed by a service that consumes the exchange feed, and an Order Service that stores orders and calls the exchange. Handles fills from the trade feed and maps them to orders. Mentions idempotency for order submission.
Senior. Explains the fan-out math, and the "ingest once, per-symbol pub/sub, push servers" design, with conflation and snapshots on connect. Writes orders as pending before sending, uses a client order id end to end, and runs a cleanup job for stuck orders. Defines the order state machine with partial fills and the cancel-versus-fill race. Makes fill processing idempotent by trade id. Reserves buying power atomically. Shards the order database by account.
Staff and above. Moves comfortably between broker and exchange. Explains the matching engine: price-time priority, book data structures, a worked match. Explains why exchanges use a sequencer, a deterministic single-threaded engine and event sourcing for replication, recovery and audit. Discusses low-latency techniques (ring buffers, core pinning, kernel bypass, multicast market data with gap recovery) and fairness. Knows the market structure (best execution, NBBO, payment for order flow, clearing, T+1, clearing deposits) and safety controls (halts, LULD, circuit breakers, kill switches), and how each shapes the design.
Deep Dive: a minimal price-time matching engineShow
TypeScript-style pseudo-code for matching an incoming limit order. Prices are integers in ticks. Levels are kept in sorted maps, and each level holds a FIFO queue.
type Order = { id: string; side: "buy" | "sell"; price: number; qty: number; seq: number };
type Trade = { buyId: string; sellId: string; price: number; qty: number; seq: number };
class Book {
bids = new SortedMap<number, Deque<Order>>((a, b) => b - a); // best = highest
asks = new SortedMap<number, Deque<Order>>((a, b) => a - b); // best = lowest
index = new Map<string, Order>(); // for O(1) cancel lookup
submit(o: Order, tif: "day" | "ioc"): Trade[] {
const trades: Trade[] = [];
const opp = o.side === "buy" ? this.asks : this.bids;
const crosses = (p: number) => (o.side === "buy" ? p <= o.price : p >= o.price);
while (o.qty > 0 && !opp.isEmpty() && crosses(opp.firstKey())) {
const level = opp.first();
const rest = level.peekFront();
const q = Math.min(o.qty, rest.qty);
trades.push({
buyId: o.side === "buy" ? o.id : rest.id,
sellId: o.side === "sell" ? o.id : rest.id,
price: rest.price, qty: q, seq: o.seq, // the resting order sets the price
});
o.qty -= q; rest.qty -= q;
if (rest.qty === 0) { level.popFront(); this.index.delete(rest.id); }
if (level.isEmpty()) opp.deleteFirst();
}
if (o.qty > 0 && tif === "day") { // rest the remainder on our side
const own = o.side === "buy" ? this.bids : this.asks;
own.getOrCreate(o.price, () => new Deque()).pushBack(o);
this.index.set(o.id, o);
}
return trades; // ioc remainder is simply dropped
}
}Notes:
- The loop is deterministic: it depends only on the book and the input, with no clock, randomness or thread timing. That is what makes replay and hot backups possible.
seqis the sequencer's number, carried into the trades, so outputs can be ordered and deduplicated downstream.- A real engine also handles cancels (
indexlookup, then removal from the level's linked list in constant time), modifications (a price change or a quantity increase loses time priority, while a quantity decrease usually keeps it), FOK (check the available quantity first), market orders with price collars, self-trade prevention (a firm's buy order should not trade with its own sell order), and halts. - Production engines avoid the allocation shown here (
new Deque, trade objects) by using pre-allocated pools, and often use price-indexed arrays instead of sorted maps.
Deep Dive: the LMAX Disruptor, in more detailShow
The Disruptor replaces a chain of queues between threads with one shared ring buffer and a set of sequence counters.
Structure.
- A ring buffer of N slots (N a power of two, such as 2^20), pre-allocated at start-up. A slot is found by
sequence & (N − 1), a bit mask instead of a modulo. - A producer sequence: the highest slot claimed by the producer (for example, the network reader that receives orders).
- One sequence per consumer: the highest slot that consumer has finished.
- A dependency graph between consumers, through sequence barriers. For example, the journaller and the replicator both depend on the producer, and the business-logic processor depends on both of them.
How an event flows.
- The producer claims the next sequence, say 1,000,001, after checking that the slowest consumer has passed slot 1,000,001 − N (otherwise the ring is full, and it waits). This is back-pressure without a lock.
- It writes the order's fields into the pre-allocated slot (no allocation), then publishes by advancing the producer sequence with a memory barrier, which guarantees that the slot's contents are visible to other cores before the new sequence is.
- The journaller and replicator see the producer sequence advance, process slots up to it, and advance their own sequences.
- The business-logic processor waits until both have passed the slot (its barrier is the minimum of their sequences), then processes it. So an order is matched only after it is durable and replicated.
- Output events go into a second ring buffer, consumed by the publishers of execution reports and market data.
Batching for free. If a consumer falls behind and the producer is 50 slots ahead, the consumer processes all 50 in one tight loop, with a single barrier read. Under load, the per-event cost goes down, which is the opposite of lock-based queues, where contention makes things worse as load rises.
Wait strategies. A consumer with nothing to do can busy-spin (lowest latency, burns a core), yield (gives the core to other threads briefly), or block on a lock and condition (lowest CPU, highest latency). Exchanges spin on isolated cores. Less critical stages can block.
Why it is fast:
- no locks, only single-writer sequences and memory barriers;
- no allocation, so no garbage collection pressure;
- sequential access to a contiguous array, which CPU prefetchers handle very well;
- padding around sequence counters to avoid false sharing between cores.
The pattern is a general one, and it has spread well beyond exchanges: logging libraries (such as Log4j 2's asynchronous loggers) and messaging systems use the Disruptor or similar ring-buffer designs.
Deep Dive: computing an opening auction priceShow
At the open (and the close, and when a halt ends), orders accumulate without matching. Then the engine finds the single clearing price that executes the most shares, and fills every crossing order at that one price.
Example. Orders collected for one stock before the open:
| Buy orders (limit, qty) | Sell orders (limit, qty) |
|---|---|
| 10.05 × 300 | 9.98 × 200 |
| 10.02 × 200 | 10.00 × 300 |
| 10.00 × 400 | 10.02 × 300 |
| 9.98 × 500 | 10.05 × 400 |
For each candidate price P, the demand is the total quantity of buy orders with limit ≥ P, the supply is the total of sell orders with limit ≤ P, and the executable volume is the smaller of the two.
| Candidate P | Buy qty at ≥ P | Sell qty at ≤ P | Executable |
|---|---|---|---|
| 9.98 | 1,400 | 200 | 200 |
| 10.00 | 900 | 500 | 500 |
| 10.02 | 500 | 800 | 500 |
| 10.05 | 300 | 1,200 | 300 |
Two prices (10.00 and 10.02) tie at 500 shares. Exchanges break ties with further rules, such as the smallest imbalance (at 10.00, 900 − 500 = 400 extra buy shares; at 10.02, 800 − 500 = 300 extra sell shares, so 10.02 has the smaller imbalance), and then a reference price such as the previous close. With the imbalance rule, the auction prints 500 shares at 10.02. All buyers at 10.05 and 10.02 (500 shares) are filled at 10.02, and sellers are filled in price-time order up to 500 shares: the 200 at 9.98 and the 300 at 10.00, all at 10.02. The remaining orders become the opening book for continuous trading.
Why auctions? They concentrate liquidity at moments of high uncertainty, produce a single fair reference price (closing prices drive index values and fund valuations), and reduce the advantage of speed, because everyone's order counts the same regardless of arrival time within the collection window. Exchanges publish indicative prices and imbalances during the collection period, so participants can respond. The exact rules vary by exchange.
Deep Dive: two latency budgets, broker and exchangeShow
Broker: from tap to "order received", target about 200 ms in normal conditions.
| Stage | Typical time |
|---|---|
| Mobile network to our edge (varies hugely) | 20–100 ms |
| TLS, API gateway, auth | 1–5 ms |
| Order Service validation and risk checks | 1–5 ms |
| Database transaction: reserve and insert PENDING | 2–10 ms |
| Exchange Gateway to venue and back (co-located or nearby) | 0.1–5 ms |
| Save the acknowledgement | 2–10 ms |
| Response back to the device | 20–100 ms |
The user's own network dominates. Our part is around 10–30 ms, so a broker does not need exchange-style techniques. It needs reliability at these latencies under 10 times the normal load.
Exchange: from packet in to execution report out, target tens of microseconds.
| Stage | Typical time |
|---|---|
| Network card to user-space gateway (kernel bypass) | ~1–2 μs |
| Parse a binary message, session checks, risk checks | ~1–5 μs |
| Sequencer: number and hand to the journaller and replicator | ~1 μs |
| Replicate to a backup (one hop on a low-latency network) | ~5–20 μs |
| Matching (book update and trades) | ~1 μs or less |
| Build and send the execution report and market data | ~1–5 μs |
Replication to a second machine is often the biggest item. That is a deliberate price for not losing acknowledged orders. Designs differ on whether to wait for a disk write, or to treat "in the memory of two machines in different racks" as durable enough, with disk writes following within microseconds. These numbers are rough orders of magnitude, chosen to show where the time goes. Real venues publish their own figures, which vary.
Deep Dive: surviving 9:30 am, step by stepShow
9:00. Push servers and Order Service instances are scaled to the forecast peak (3–5 times the midday level), based on the previous days and on news (earnings, an index rebalance, a meme-stock frenzy). Exchange sessions are connected and warmed. Caches hold the previous close and pre-market prices for every symbol.
9:15–9:29. Users open the app. Their clients connect with randomised delays (for example 0–5 seconds) and receive snapshots from the latest-price cache. Orders entered before the open are accepted and stored as PENDING with an "at open" flag, then sent to the venue's opening auction, or queued until 9:30, according to the order type.
9:30:00. The opening auctions print. The price feed spikes: thousands of symbols move at once. The Price Ingestor conflates, so the pub/sub load rises only in proportion to the number of active symbols, not to trade counts.
9:30–9:35. Order submissions peak. If exchange sessions approach their message-rate limits, the gateway applies admission control: orders queue in a durable queue in arrival order, and users see "queued". This is better than timeouts, which cause retries and duplicate risk. Trade Processor partitions absorb a burst of fills, and push notifications are batched per user.
Afterwards. Autoscaling scales down gradually, never during the first 30 minutes. The team reviews tail latencies, queue depths and any reconciliation breaks from the burst.
What breaks if you skip this? Reactive autoscaling takes minutes, and the open's burst lasts seconds. The service saturates, clients retry, retries multiply the load, and the database falls over. Capacity for known peaks must be scheduled, not reactive. See Capacity Planning and Load Testing.
Deep Dive: portfolio value, P&L and price chartsShow
Portfolio value = cash + Σ (shares held × latest price). It changes with every tick of every held symbol, so computing it on the server for every user and pushing it would multiply the fan-out. The usual approach:
- the server sends positions (symbol, quantity, average cost) once, and on each change;
- the client already receives live prices for those symbols, and computes the portfolio value and the daily change locally;
- the server computes the authoritative value only for snapshots (end of day, statements, margin checks), from closing prices.
Profit and loss (P&L). Unrealised P&L = (current price − average cost) × quantity. Realised P&L is recorded when shares are sold, using the broker's cost-basis method (for example first-in, first-out, or specific lots chosen by the customer), which also drives tax reporting. Corporate actions (splits, dividends, mergers) adjust positions and cost basis through ledger entries, so history stays explainable.
Price charts.
- A stream processor (for example Flink or Kafka Streams) consumes trades and computes candles (open, high, low, close, volume) per symbol, per minute.
- One-minute candles are stored in a time-series store, and coarser candles (5 minutes, 1 hour, 1 day) are rolled up from them.
- Size: 10,000 symbols × 390 minutes per session ≈ 4M one-minute candles per day, at about 50 bytes each, about 200 MB per day. That is small, so years of minute data fit comfortably, and charts can be served from a cache in front of the store.
- The live candle (the current minute) is computed on the client from the price stream, and replaced by the server's candle when the minute closes.
Price alerts ("tell me if TSLA drops below $200") are a matching problem at the broker: millions of alert thresholds, checked against each price update. Store alerts per symbol in a sorted structure by threshold (two sorted sets, one for "above" and one for "below"), so each price update finds triggered alerts with a range query instead of a scan. Fire each alert once (delete or mark it in the same step), and deliver it by push notification.
Deep Dive: stop orders, GTC orders and other order types at the brokerShow
Not every order type is an exchange order. Brokers implement several themselves.
- Stop and stop-limit orders. Many brokers hold stop orders internally and monitor the price. When the trigger is hit (for example the last trade at or below $180 for a sell stop), the broker sends a market order (stop) or a limit order (stop-limit) to the venue. This is a broker-side matching problem, like price alerts: per symbol, keep stops sorted by trigger price, and check each price update with a range query. Trigger semantics must be precise (last trade price, or the bid for sells, and whether odd-lot trades count), documented and consistent.
- Trailing stops. The trigger follows the price at a fixed distance (for example 5 percent below the highest price since the order was placed). Each update may move the trigger, so it is a per-order computation on each tick of its symbol. That is fine for thousands of orders per symbol, if the updates are conflated.
- Good-til-cancelled (GTC). Venues may not hold orders overnight. The broker stores GTC orders and re-submits them each morning, with new exchange order ids, keeping our order id stable. Corporate actions (a 2-for-1 split) require adjusting the price and quantity of open GTC orders.
- Fractional and dollar-based orders are aggregated and filled from the broker's own inventory (Deep Dive 5).
- Extended hours (out of scope here) use different venues and allow only limit orders, so the order type validation depends on the session.
Design point. Triggered orders are dangerous during fast markets: a sharp drop can trigger thousands of stop orders at once, creating a burst of market sell orders that pushes the price down further. Brokers rate-limit trigger processing per symbol, respect venue halts and LULD pauses, and make sure that a trigger is processed exactly once (a guarded state change from waiting to triggered before sending).
Deep Dive: variant, a crypto exchangeShow
A crypto exchange (Coinbase, Kraken, Binance) combines the broker and the exchange in one company, and runs 24 hours a day, 7 days a week. The matching engine is the same idea, but the surroundings differ.
- No closing bell. There is no overnight window for maintenance, snapshots or batch reconciliation. Upgrades need hot failover to a backup engine running the new version, after it has replayed the journal to the current sequence. Some exchanges still schedule short maintenance windows.
- Self-clearing and custody. Trades settle on the exchange's internal ledger instantly: the exchange holds both sides' balances. Customer funds sit in hot wallets (online, for withdrawals) and cold wallets (offline keys, for most reserves). Withdrawals move funds from the internal ledger to the blockchain, after risk checks.
- Deposits are credited after a number of block confirmations that depends on the chain and the amount, because a chain reorganisation can reverse a recent transaction.
- Pre-funded trading. Orders are checked against balances that are already on the exchange, so pre-trade risk is a balance check in the matching path (some engines integrate the balance check into the engine itself to avoid a race between risk and matching).
- No NBBO. Prices differ between exchanges, and arbitrageurs keep them close. Market data goes to the public over WebSockets, so the fan-out problem looks like the broker's, at a huge scale.
- Proof of reserves. After high-profile exchange failures, some exchanges publish cryptographic proofs (for example Merkle-tree commitments over customer balances) that their on-chain holdings cover customer liabilities.
The core design lessons still apply: a sequenced journal, a deterministic engine, a double-entry ledger, idempotent deposits and withdrawals, and daily (or continuous) reconciliation, here against blockchains instead of clearing houses.
Deep Dive: testing a matching engineShow
Bugs in matching are expensive and public. Determinism makes the engine unusually testable.
- Replay testing. Record the full sequenced input of real sessions (or a test venue's), replay it through a new engine version, and compare every output byte for byte with the recorded output. Any difference must be explained by an intended change.
- Property-based tests. Generate random streams of orders and cancels, and assert invariants after each event: the best bid is below the best ask (the book is never crossed after matching), quantities never go negative, every trade has a buyer and a seller at a price both accepted, price-time priority holds (no later order at the same price filled before an earlier one), and total traded quantity on each side is equal.
- Reference model. Compare the optimised engine against a slow, obviously correct implementation (a sorted list scanned each time) on the same random inputs.
- Latency regression tests. Run a fixed workload on production-like hardware for each build, and fail the build if p99 or maximum latency regresses.
- Failover drills. Kill the primary during a replayed session, and verify that the backup's outputs continue with no gap and no duplicate sequence numbers.
Deep Dive: a 45-minute interview planShow
| Minutes | What to do |
|---|---|
| 0–5 | Clarify: broker or exchange? The exchange's interface (sync place and cancel, trade feed)? Order types, market hours, scale |
| 5–9 | Requirements: live prices and order management. Non-functional: order consistency first, price latency under a second, the open spike, audit |
| 9–12 | Capacity: subscriptions, fan-out messages per second, connections, orders per second at the open |
| 12–16 | Entities and API: SSE price stream, POST and DELETE orders with clientOrderId, order events |
| 16–26 | High-level design: Price Ingestor, per-symbol pub/sub, push servers; Order Service, Order DB, Exchange Gateway, Trade Processor, cleanup job |
| 26–40 | Deep dives: fan-out scaling and conflation; order consistency (pending first, clientOrderId, state machine, cancel race); fill tracking; then, if asked, the matching engine and low latency |
| 40–45 | Failure modes, the market open, reconciliation, and what you would add next (stops, GTC, charts) |
Signals of seniority: "the broker must not lose an order the exchange knows about", "a timeout is unknown, not failed", "ingest once, fan out per symbol", "the exchange is a deterministic state machine over a sequenced log", and "fairness is a design requirement".
Deep Dive: real-world notesShow
These are publicly reported facts and descriptions, summarised briefly. Treat them as illustrations, not specifications, because systems change.
- Robinhood is a broker that routes most customer equity orders to market makers, and has disclosed receiving payment for order flow. It experienced widely reported outages on several heavy-trading days in March 2020, and restricted buying of some stocks in January 2021 after a jump in clearing-house deposit requirements.
- LMAX published its architecture (Martin Fowler's 2011 article "The LMAX Architecture") and open-sourced the Disruptor, making the single-threaded, in-memory, event-sourced design widely known.
- Nasdaq publishes the specifications of its ITCH (market data) and OUCH (order entry) binary protocols, which show what order-by-order feeds and lean order messages look like.
- IEX introduced a 350-microsecond speed bump using coiled fibre, as a deliberate trade of speed for fairness.
- Knight Capital lost about $440 million in under an hour in August 2012 after a faulty software deployment, a lasting lesson about deployment discipline and kill switches.
- US settlement moved from T+2 to T+1 in May 2024, which reduced the period of counterparty risk, and with it the collateral that brokers must post.
Deep Dive: common follow-up questions, with short answersShow
"Why not let clients connect to the exchange feed directly?" Exchanges serve member firms over dedicated links, with licensing fees per user for real-time data. They do not serve consumer devices, and millions of connections would be impossible. The broker ingests once and fans out.
"Kafka or Redis for price fan-out?" Redis Pub/Sub (or a dedicated fan-out tier) for ephemeral, latest-value ticks: fast, with no retention needed. Kafka for durable streams that must be replayed: order events, trades for candles, audit. Many systems use both.
"How do you show the order book (Level 2) if it is in scope?" Same fan-out design, but the data is heavier. Publish top-N levels per symbol with conflation, send a snapshot on subscribe, then deltas with sequence numbers, and resync on a gap.
"What if the cleanup job finds an order at the exchange that the user believes failed?" By design, it cannot happen: the app showed pending, never failed, during the unknown period, and the reservation was held. The cleanup job moves it to open or filled, and the user is notified.
"How would the exchange support thousands of symbols on one engine?" Shard symbols across engine instances by load. Within an instance, one thread can process many symbols' books, because each event touches only its own symbol's book. The busiest symbols get dedicated instances.
"How do you guarantee fairness between members?" One sequence per shard, assigned at a single point. Equal network paths for co-located members, multicast market data, published rules for priority, and audit by replay.
Deep Dive: the broker's ledger, settlement and unsettled fundsShow
A broker owes each customer cash and shares. Like the payment system, it keeps them in a double-entry ledger, so every balance can be explained by entries.
Buying 10 AAPL at $190.00, filled today (T), settling tomorrow (T+1):
| When | Debit | Credit | Amount |
|---|---|---|---|
| Order placed | customer_cash_available | customer_cash_reserved | $1,900.00 |
| Fill at T | customer_cash_reserved | payable_to_clearing | $1,900.00 |
| Fill at T | customer_securities: AAPL (10 shares) | securities_to_receive: AAPL | 10 shares |
| Settlement at T+1 | payable_to_clearing | broker_bank_cash | $1,900.00 |
| Settlement at T+1 | securities_to_receive: AAPL | depository_position: AAPL | 10 shares |
Securities are tracked in share units in their own accounts, never mixed with cash. Each journal balances in its own unit.
Unsettled funds. When a customer sells shares, the cash is not settled until T+1. Brokers handle this differently by account type:
- in a cash account, buying with unsettled sale proceeds and then selling those new shares before the proceeds settle can count as a good-faith violation under US rules, and repeated violations lead to restrictions. The ledger must track settled and unsettled cash separately, and the risk check must know which is which;
- in a margin account, the broker can lend against the unsettled amount, subject to margin rules.
Daily reconciliation compares, per customer and per symbol, the broker's ledger with the clearing firm's position and cash reports, and the depository's totals. Any difference (a missed fill, a corporate action applied on one side only) is a break, worked before the next session. Customer statements are generated from the ledger, so a correct ledger is also a regulatory obligation.
Deep Dive: margin accounts and liquidationShow
A margin account lets a customer borrow from the broker to buy more shares than their cash would allow, with the shares as collateral.
The rules (US, simplified).
- Initial margin: under the Federal Reserve's Regulation T, a customer can generally borrow up to 50 percent of the purchase price of marginable stock. With $10,000 of cash, they can buy up to $20,000 of stock.
- Maintenance margin: FINRA rules require equity of at least 25 percent of the market value of the positions, and brokers often set higher house requirements (30–40 percent, more for volatile stocks).
- Equity = market value of positions − loan.
Worked example. A customer buys $20,000 of stock with $10,000 of cash and a $10,000 loan. The equity is $10,000, which is 50 percent. If the stock falls 30 percent, the positions are worth $14,000, the loan is still $10,000, the equity is $4,000, and the ratio is 4,000 / 14,000 ≈ 28.6 percent. That is above 25 percent but below a 30 percent house requirement, so the broker issues a margin call: deposit cash, or sell shares to restore the ratio.
System design.
- A margin engine recomputes every margin account's equity as prices move. With millions of accounts and thousands of symbols, it is driven by price updates: for each symbol that moved, recompute the accounts that hold it (an index from symbol to accounts), not every account on every tick.
- Accounts are bucketed by how close they are to their requirement, so the riskiest are rechecked most often.
- Liquidation: if a call is not met (or equity falls below a hard threshold), the broker may sell positions without asking, according to the account agreement. Liquidation orders are generated by the system, with a priority order of which positions to sell, and pass through the same risk checks, rate limits and state machine as customer orders. They must be idempotent: a liquidation must not be triggered twice for the same shortfall.
- Concentration: if many customers hold the same volatile stock on margin, a sharp drop can trigger a wave of liquidations that pushes the price down further. Brokers raise margin requirements on such stocks in advance, which is a risk decision supported by the same data.
Deep Dive: exchange order types beyond market and limitShow
Exchanges support order types that serve professional participants. Each changes the matching engine.
- Iceberg (reserve) orders show only part of their size on the book (for example 100 of 10,000 shares). When the displayed part fills, the next slice is displayed, usually with new time priority, so it goes to the back of the queue at that price. The engine keeps the hidden remainder attached to the order.
- Hidden orders rest on the book without being displayed in market data. They typically have lower priority than displayed orders at the same price, as a reward for showing liquidity.
- Post-only orders must add liquidity: if they would match immediately, they are rejected (or repriced one tick away) instead of executing. Market makers use them to make sure they earn the maker rebate rather than pay the taker fee.
- Pegged orders have a price tied to a reference, such as the NBBO midpoint or the best bid. When the reference moves, the engine reprices them, which is an internal event that must also be deterministic and sequenced.
- Self-trade prevention: a firm's buy order matching against its own sell order is usually unwanted (it can look like wash trading). The engine checks a member or account identifier, and cancels the newer order, the older one or both, depending on the instruction.
Maker-taker pricing. Many exchanges pay a small rebate to the order that rested on the book (the maker) and charge a fee to the order that took liquidity (the taker). In the US, access fees for taking protected quotes have been capped by regulation (historically at 30 cents per 100 shares). This pricing affects how brokers and market makers route, and is why the broker's smart order router models fees and rebates.
Deep Dive: FIX sessions and the exchange gatewayShow
Brokers connect to venues through sessions, and the session layer is where many real outages happen.
FIX session basics. FIX messages are tag=value pairs (for example 35=D marks a new order, 11= is the client order id, 55= the symbol, 54= the side, 38= the quantity, 44= the price). A session:
- starts with a Logon, and is kept alive with heartbeats at an agreed interval;
- numbers every message in each direction with a sequence number;
- on reconnect, compares sequence numbers. If messages were missed, the receiver sends a resend request for the missing range, and the sender replays them (or sends a sequence reset for administrative messages that need not be repeated);
- ends with a Logout.
Because of the sequence numbers, a reconnect after a short network drop loses nothing: execution reports sent while disconnected are replayed. Our gateway must persist its session sequence numbers and the messages it sent, so that it can answer the venue's resend requests after its own restart.
Cancel on disconnect. Many venues offer an option to cancel all of a session's resting orders automatically if the session drops. It protects a firm whose systems have failed from fills it cannot see. The broker must then mark those orders as cancelled on reconnect, from the venue's reports, never by assumption.
Throttles. Each session has a message-rate limit (orders and cancels per second). The gateway enforces it locally (a token bucket per session, as in Rate Limiting and Throttling), and spreads traffic across several sessions per venue for throughput and redundancy. Orders for the same symbol and account should go to the same session, so their relative order is preserved.
Redundancy. Sessions run from two data centres or at least two gateway hosts. Failing over a session means resuming with the correct sequence numbers, so session state is replicated, or recovered from the venue with a resend request.
Deep Dive: market surveillanceShow
Exchanges and brokers must detect market abuse. Surveillance runs on the same event streams, as a stream processing problem over orders and trades.
Examples of patterns to detect:
- Spoofing and layering: placing large orders on one side with no intention of trading, to move the price, then cancelling them after trading on the other side. Signals: large orders cancelled within milliseconds, repeatedly, and correlated with fills on the opposite side.
- Wash trading: trades where the same beneficial owner is on both sides, creating fake volume. Signals: matched buy and sell orders from related accounts.
- Front-running and insider trading: trading ahead of client orders or ahead of news. Signals: unusual trading by an account just before material announcements.
- Marking the close: trading near the closing auction to move the closing price.
Architecture.
- The sequenced journal (exchange) or the order events stream (broker) feeds a stream processor that keeps per-account and per-symbol windows (orders placed, cancelled and filled in the last N seconds).
- Rules and models emit alerts to a case-management system, where analysts investigate, with the ability to replay the full order book around the event from the journal.
- Because the journal is complete and ordered, an investigation can reconstruct exactly what each participant saw and did, which is the audit trail of Deep Dive 10 put to work.
Deep Dive: why one thread beats many, in numbersShow
It seems backwards that a single thread is the fastest way to match orders. A small model shows why.
The cost of sharing. Suppose that matching an order touches the book for about 0.5 μs of pure work, if the data is in cache. With several threads sharing one book:
- each operation needs a lock or an atomic compare-and-swap. An uncontended atomic costs tens of nanoseconds, but a contended cache line bounces between cores, at roughly 100 ns or more per transfer;
- the book's data migrates between cores' caches, turning cache hits (~1 ns) into memory or cross-core fetches (~100 ns);
- a thread that loses a lock may be descheduled, which costs microseconds.
Since orders for one symbol must be processed in sequence anyway (price-time priority depends on the exact order), threads cannot do useful work on the same book in parallel. They can only take turns, so locking adds cost without adding throughput.
Throughput of one thread. At 0.5–1 μs per event, one thread handles 1–2 million events per second for its books, which exceeds the peak message rate of even very active symbols. The LMAX figure of about 6 million orders per second on one thread (from Martin Fowler's article) reflects very lean event processing.
Where parallelism does help:
- across shards: different symbols on different threads or machines, with no shared state;
- across pipeline stages: network parsing, journalling, replication and market-data encoding run on their own threads, connected by ring buffers. Each stage is single-writer, so there are still no locks;
- before the sequencer: gateways validate and parse in parallel per session.
The general lesson (which applies far outside exchanges): when work on some state must be serialised anyway, give that state to one owner thread, feed it through a queue, and spend the effort on making each step cheap. Redis's single-threaded command execution follows the same reasoning (see Redis in Practice), and so does the actor model.
Deep Dive: failover timeline for a matching engineShow
Setup. One primary and two backups per shard, in different racks (and a disaster-recovery copy in another data centre, replicated asynchronously). An input is committed when it is in the memory of the primary and at least one backup.
Timeline of a primary crash:
- t = 0. The primary's process dies after sequencing input 5,000,123 and replicating it, but before publishing its outputs.
- t ≈ 50–500 ms. Backups miss several heartbeats. With a consensus protocol, the backups hold an election. With a simpler scheme, an arbiter promotes the most up-to-date backup and fences the old primary (for example by revoking its network access to the output multicast groups), so it cannot publish if it is only frozen, not dead.
- Next. The new primary checks its journal: the last committed input is 5,000,123. It has already applied it to its own books (it processes the same inputs), so it publishes the outputs for 5,000,123, with the same output sequence numbers the old primary would have used.
- Gateways reconnect to the new primary and resend any inputs that were never acknowledged. Inputs carry the member's client order ids and session sequence numbers, so anything already sequenced is recognised as a duplicate and ignored.
- Subscribers of market data see a short pause, then continue with the next sequence number. A subscriber that missed packets uses retransmission, as usual.
Trade-offs.
- A shorter heartbeat timeout fails over faster, but risks false failovers during a brief hiccup, which is disruptive in itself.
- Waiting for a disk write in addition to a backup's memory protects against a whole-site power loss, at the cost of more microseconds per input.
- Failing over to the remote data centre is a much bigger event: asynchronous replication means the last few inputs may be missing, so many exchanges halt trading, reconcile with members, and resume rather than continuing silently.
Deep Dive: variant, options tradingShow
If the interviewer extends the scope to options, several things change.
- Many more instruments. Each stock has options across many strike prices and expiry dates, so the number of instruments is in the millions rather than thousands. Market makers update quotes on all of them whenever the underlying stock moves, so options market data rates are much higher than equity rates. The US options feed (OPRA) is one of the highest-volume market-data feeds in the world.
- Fan-out for retail. No user watches all strikes. Clients subscribe to an option chain (one expiry of one stock) when they open it, and the broker conflates heavily. The per-symbol pub/sub design still works, with channels per option or per chain.
- Multi-leg orders. Spreads (buy one option, sell another) should execute together or not at all. Exchanges have complex-order books that match multi-leg orders as a unit, and a broker must handle partial fills of multi-leg orders carefully, or a customer can be left with one leg and an unintended risk.
- Risk and margin. The risk of an options position depends on the stock price, volatility and time. Margin requirements are computed with models across scenarios, rather than a single percentage. The margin engine becomes a significant computing workload on every price move.
- Exercise and assignment. At expiry, options in the money may be exercised automatically, creating stock positions and cash movements in the ledger. Assignments to customers who sold options arrive from the clearing house (in the US, the Options Clearing Corporation), and must be processed overnight before the next open.
Deep Dive: keeping a local order book in sync with snapshots and deltasShow
Any consumer of book data (a broker's Level 2 screen, a market maker, a surveillance system) faces the same problem: build a correct copy of a book that changes thousands of times a second, from a stream that can drop messages.
The protocol.
- Subscribe to the delta stream first, and buffer the messages that arrive.
- Request a snapshot, which says "the book as of sequence S".
- Discard buffered deltas with sequence ≤ S. Apply those with sequence S + 1, S + 2 and so on, in order.
- For every new delta, check that its sequence is exactly the previous one + 1. If it is not, there is a gap: mark the book stale (the user interface greys it out), and go back to step 1 or request a retransmission of the missing range.
Why subscribe before taking the snapshot? If the snapshot came first, deltas between the snapshot and the subscription would be lost. Buffering first means the consumer always holds every delta after S.
At the broker's edge, the same idea applies to clients: the push server sends a snapshot of the top N levels on subscribe, then conflated deltas with a per-symbol version number. A client that sees a version jump it cannot explain asks for a new snapshot. Conflation is safe for books as long as each published delta carries the full new state of each changed level (price, total quantity), not an increment, so skipping intermediate updates still leaves the client correct.
Idempotent application. Level updates that carry absolute values ("190.02 now has 3,400 shares") can be applied twice without harm. Order-by-order feeds carry events (add, execute, cancel), which are not idempotent, so they rely strictly on sequence numbers.
Deep Dive: security and fraud at a retail brokerShow
A brokerage account is a bank account with extra ways to lose money, so its threat model goes beyond the order path.
- Account takeover. Stolen passwords are the main risk. Use multi-factor authentication (authenticator apps or passkeys rather than SMS where possible), device binding, and step-up authentication for sensitive actions: changing the linked bank account, large withdrawals, or disabling MFA. Add a cooling-off period for withdrawals after a bank account change, so a takeover cannot drain the account instantly.
- Instant deposits and returns. Many brokers let customers trade immediately with deposits that will take days to arrive by ACH. If the ACH transfer is returned (insufficient funds, or a fraudulent account), the broker has already extended credit. Limit instant buying power by account history, and hold the proceeds of trades made with uncollected funds until the deposit settles. This is the same "submitted is not final" lesson as in the payment-system case.
- API and session security. Short-lived access tokens, refresh tokens bound to the device, and server-side session revocation. Order endpoints are rate-limited per user and per device, to blunt scripted abuse.
- Insider and operational risk. Support staff can see sensitive data and act on accounts. Use least privilege, four-eyes approval for manual adjustments to cash or positions, and complete audit logs of staff actions.
- Data protection. Personal data (tax ids, addresses, bank details) is encrypted at rest with managed keys, kept out of logs, and separated from the order and ledger stores, which reference customers by id. See Security Fundamentals for System Design.
Key Takeaways#
- Know which system you are designing. Robinhood is a broker that routes orders to exchanges and market makers. An exchange runs the order books and matching. They have very different latency, scale and correctness concerns.
- Live prices: ingest once, fan out per symbol. A Price Ingestor conflates the feed, per-symbol pub/sub routes updates only to interested push servers, and SSE (or WebSockets) delivers them, with snapshots on connect.
- Order consistency: write before sending. Store the order as pending with a client order id, send that id to the exchange, treat timeouts as unknown, and let a cleanup job and daily reconciliation resolve disagreements.
- An explicit order state machine (pending, open, partially filled, pending cancel, filled, cancelled, rejected, expired) with guarded transitions handles partial fills and the cancel-versus-fill race.
- Idempotent fills keyed by the exchange's trade id, and atomic buying-power reservations, keep cash and positions exactly right.
- The matching engine keeps price-time priority with sorted price levels, FIFO queues per level, and a hash map for cancels. The resting order sets the trade price.
- Exchanges are deterministic state machines over a sequenced log. The sequencer defines fairness. Event sourcing gives replication, recovery by replay, and a perfect audit trail.
- Low latency comes from removing work: single-threaded logic, ring buffers, no locks or garbage, pinned cores, kernel bypass, binary protocols and co-location. Measure the tail, not the average.
- Market data is published fairly with multicast, sequence numbers, A and B feeds, snapshots and retransmission.
- Safety controls are part of the design: pre-trade risk checks, halts, LULD bands, circuit breakers, auctions and kill switches.