Design a Stock Trading App
How a stock trading app streams live prices to millions of screens, keeps orders correct with an outside exchange, and copes with the market open.
On this page
A retail trading app, meaning the broker's app and not the exchange, shows live prices for the stocks a user is watching and lets the user place, cancel and track orders. The broker does not match trades itself; it records the order and sends it to an exchange it does not control.
The design is hard because the two halves have opposite requirements. Live prices are a fan-out problem in which a price that is one second old is acceptable, but millions of screens need it. Orders involve real money, so an order must never be lost or executed twice, even though the call to the exchange can fail after the exchange has already acted on it. The steps below follow A Framework for Any Design.
Clarify the problem
Design a stock trading app.
Are we the broker, which sends orders to outside exchanges, or the exchange that matches them?
You are the broker. Orders go to an external exchange.
I assume the app shows live prices, lets users place and cancel orders, and shows the status of each order. Which order types do we support?
Market and limit orders, for stocks only.
How many people use the app at the busiest moment, and how many orders do they place in a day?
About 2 million people have the app open right after the open, and there are about 5 million orders a day.
Then there are two paths with different rules. Prices can be a second old, but they must reach 2 million screens. Orders must never be lost or duplicated, even if a server crashes in the middle of a call to the exchange. I will design for the open.
- Functional requirements: users see live quotes for the symbols on their screen, place market and limit orders, cancel open orders, and see each order's status change as it happens.
- Non-functional requirements: quotes arrive within about 1 second of the exchange, an accepted order is never lost and never sent twice, the order status always ends up matching the exchange, and the order path survives the open, when the order rate is about 20 times the daily average.
- Out of scope: the matching engine, options, crypto, charts, account opening and tax reports.
Estimate the scale
The price path and the order path are estimated separately. The figures are scenario assumptions, not those of a real broker.
- Connections: if one push server holds 50,000 WebSocket connections, 2 million clients need 40 servers. Running 80 leaves each server half full, so it can absorb the clients of a dead one.
- Market data coming in: the exchange feed delivers up to 200,000 quote updates a second across 10,000 symbols. Nobody can read a price that changes dozens of times a second, so each symbol is sent at most once a second, which is 10,000 updates.
- Updates going out: a screen shows about 10 symbols, so 2 million screens need 20 million symbol updates a second. Sent as one frame per client per second, that is 2 million frames, or 25,000 per push server, and about 800 MB/s in total at 40 bytes per symbol.
- Orders: a trading day is 6.5 hours, or 23,400 seconds, so 5 million orders a day is about 214 orders a second on average.
- Storage: an order with its history takes about 2 KB, so 5 million orders add about 10 GB a day.
How many orders a second arrive in the first minute after the open?
- 5 million orders a day
- The first minute carries 5% of the day's orders
Show the working
- 5% of 5,000,000 = 250,000 orders
- 250,000 ÷ 60 s ≈ 4,200 a second, about 20 times the average of 214
Estimate 4.2 thousand/s (anything from 1.5 thousand/s to 12 thousand/s is a good answer)
A relational database partitioned by account can handle 4,200 writes a second, provided it is scaled up before 9:30.
Write the calls for quotes, for placing an order and for cancelling one. Decide which calls return a final answer immediately and which answers arrive later.
Compare with a model answer
Quotes and order updates share one WebSocket. Placing an order returns "pending", with an app-generated id so that a retry cannot create a duplicate, and cancelling returns "cancel requested". The real results arrive later as events.
Define the API Optional
Optional in the interview. Sketch the API only if the interviewer asks, if an API choice shapes the design, or if time permits. Otherwise say "I'll skip the detailed API unless you want it" and go to the data model.
WebSocket /stream one per open app
client → { "op": "subscribe", "symbols": ["ACME", "ZETA"] }
client → { "op": "unsubscribe", "symbols": ["ZETA"] }
server → { "type": "quotes", "q": [ { "s": "ACME", "bid": 4997, "ask": 4999,
"last": 4998, "ts": "09:30:01.200" } ] }
server → { "type": "order", "id": "o-551", "status": "filled",
"filled_qty": 10, "avg_price": 4998 }
POST /orders
body: { "client_order_id": "c-7f3a", "symbol": "ACME", "side": "buy",
"type": "limit", "qty": 10, "limit_price": 5000 }
201 { "order_id": "o-551", "status": "pending" }
200 the same body again a retry with the same client_order_id
422 { "reason": "insufficient buying power" | "market closed" | ... }
DELETE /orders/{id}
202 { "status": "cancel_requested" }
409 the order is already filled, cancelled or rejected
GET /orders/{id} GET /orders?status=open
GET /quotes?symbols=ACME,ZETA a snapshot for the first paintPrices are integer cents, because floating-point dollars cause rounding errors.
The API decision worth discussing is what POST and DELETE promise. Because the exchange decides later, POST returns 201 as soon as the order is durably recorded, DELETE returns 202 because the cancel has only been requested, and the result arrives as an event on the stream. An app that showed "Cancelled" on the 202 would eventually show a cancelled order that had already filled.
The app creates client_order_id once and reuses it on every retry. It is the order's idempotency key, which lets the server tell a retry from a new order.
Sketch the tables for orders and fills. Decide how a retried order and a repeated fill are each counted only once.
Compare with a model answer
A unique key on the account and the client order id rejects a retried order, and fills keyed by the exchange's execution id reject a repeated fill. The order and the cash reservation for it are committed in one transaction.
Model the data
orders
order_id BIGINT PRIMARY KEY
account_id BIGINT
client_order_id VARCHAR(40)
symbol VARCHAR(8)
side VARCHAR(4) -- buy | sell
type VARCHAR(6) -- market | limit
qty INT
limit_cents BIGINT NULL
status VARCHAR(16) -- pending | sent | accepted | partly_filled
-- | filled | cancel_pending | cancelled | rejected
filled_qty INT
reserved_cents BIGINT -- cash held back for this order
updated_at TIMESTAMP
UNIQUE (account_id, client_order_id)
fills
exec_id VARCHAR(40) PRIMARY KEY -- from the exchange
order_id BIGINT
qty INT
price_cents BIGINT
executed_at TIMESTAMP
accounts
account_id BIGINT PRIMARY KEY
cash_cents BIGINT
reserved_cents BIGINT -- spendable = cash - reserved
positions
account_id BIGINT
symbol VARCHAR(8)
qty INT
reserved_qty INT -- shares held back for open sells
PRIMARY KEY (account_id, symbol)Placing an order, updating it, listing a user's orders and recording a fill are each a transaction that touches only one account. That access pattern fits a relational database partitioned by account_id, which gives real transactions without cross-partition coordination. Quotes are not stored; the feed handler keeps the latest one per symbol in memory.
Unique keys do the deduplication, so two servers cannot race past it. A retried order violates UNIQUE (account_id, client_order_id), and a repeated fill violates the primary key on exec_id.
Sketch how a price reaches 2 million screens, and how an order reaches the exchange and its status comes back to the user.
Compare with a model answer
A feed handler publishes each symbol's latest quote once a second to pub/sub, and push servers forward it over WebSockets. An order service records each order before calling the exchange and publishes status events back through pub/sub.
High-level design
request and replyasynchronous message
- ACME last
- $49.97
1Ana opens the ACME stock. Her push server subscribes to the ACME topic and sends her a snapshot of the current quote.
- ACME last
- $49.98
- messages sent
- 1, not 40
2The exchange sends 40 ACME updates in one second. The feed handler keeps only the latest and publishes it once, and each push server adds it to the next frame of every client watching ACME.
- client_order_id
- c-7f3a
- order
- none yet
3Ana taps Buy for 10 shares at a $50.00 limit. The app first creates the client order id c-7f3a, so that every retry carries the same id.
- client_order_id
- c-7f3a
- order
- pending
- reserved
- $500.00
4One transaction inserts order o-551 as
pendingand reserves 10 × $50.00 = $500. It is committed on a synchronous replica too before anything is sent.- client_order_id
- c-7f3a
- order
- pending
- reserved
- $500.00
5The order service sends the order to the exchange with id c-7f3a and then crashes before it records the status
sent, so the exchange has it.- client_order_id
- c-7f3a
- order
- pending
- orders created
- 1
6Ana's app times out and retries with c-7f3a. Another order server finds the existing row through the unique key and returns o-551.
- client_order_id
- c-7f3a
- order
- accepted
- orders at exchange
- 1
7A reconciler finds o-551 still
pendingafter 5 seconds. It does not resend. It asks the exchange about c-7f3a, learns the order was accepted, and updates the row.- order
- filled
- cost
- $499.80
- released
- $0.20
8A fill arrives for 10 shares at $49.98 with execution id E-90. One transaction inserts the fill, marks the order filled and releases the $0.20 that was reserved but not spent.
- order
- filled
- shares
- 10
9After a reconnect the exchange sends the same fill again. The insert fails on the primary key E-90, so Ana does not receive 20 shares.
- order
- filled
- shares
- 10
10The order service publishes the status change to Ana's account topic, and her push server forwards it to the app, which shows "Filled at $49.98".
Deep dives
Fanning out live prices
Sending every tick to every watcher is far more than any system can sustain, so the design uses three techniques.
The first technique is conflation at the source: the feed handler publishes only the latest quote per symbol once a second, so pub/sub carries 10,000 messages a second instead of 200,000. Each message is a full quote, so the next one repairs a lost one.
The second technique is subscribing per server instead of per client. A symbol shown on 1 million screens costs the pub/sub system 80 messages a second, one for each push server, and each push server then copies the quote to its roughly 12,500 watchers.
The third technique is batching per client: each client receives one frame a second containing all of its symbols.
The remaining choice is how prices reach the app. Polling means each app asks over plain HTTP every second, which produces 2 million requests a second with full headers. Server-sent events keep one HTTP response open, but the stream is one-way, so every subscription change is a separate call that must reach the right server. A WebSocket is two-way, so subscriptions and order updates share one connection, at the cost of stateful servers that must be drained during deploys. This design uses WebSockets because subscriptions change constantly as the user scrolls.
After a reconnect the app subscribes again and calls GET /orders?status=open so that it does not miss a status change. Real-time communication covers holding this many connections.
A market order fills at the exchange's current price, not the price on the screen, which can be a second old. The system therefore reserves cash with a margin, for example 5% extra for a market buy, and settles on the fill price.
Keeping orders correct with an outside exchange
The broker's database and the exchange cannot take part in one transaction, so there is always a moment when only one of them knows about the order. The design must decide which one knows first. There are three orderings.
Calling the exchange first and writing afterwards looks natural, but a crash between the two steps leaves a live order at the exchange with no row in the database and no cash reserved. The customer could own shares that the broker has no record of.
Writing first and then calling the exchange reverses the order. The service commits the order as pending, with the cash reserved, and only then sends it. A crash now leaves a pending row, and some of those rows were never sent, but no order can exist at the exchange without a record at the broker. The remaining work is to find out, for each stuck row, whether the exchange received it.
Writing with an outbox commits the order and a row in an outbox table in the same transaction, and a separate sender process reads the outbox and calls the exchange. It is the right choice when sending must continue while the order service is down, at the cost of another component.
| Option | Good at | Bad at | Pick it when |
|---|---|---|---|
| Call the exchange, then write | The database never holds an order that was not sent. | A crash after the call leaves a live order with no row and no reserved cash. | Do not use it when real money is involved. |
| Write first, then call Usual default | Every order the exchange can know about has a row first, and a crash leaves a pending row that can be resolved by asking the exchange. | Some pending rows were never sent, so a reconciler has to settle them. | Use it when the same service writes the row and sends the order, which is the usual case. |
| Write with an outbox | The order and the outbox row commit together, and a separate sender handles the exchange. | It adds a component, and the sender must still check the status before any resend. | Use it when sending is a separate service that must keep working while the order service is down. |
The rule is that the row holding the client order id must be durable, which means committed on a synchronous replica as well, before the exchange can hear about the order. Three practices follow.
The first is never to resend a pending order blindly, since it may have reached the exchange. Exchange protocols such as FIX carry the client order id on every message, so the reconciler asks the exchange whether it knows that id and sends the order only if the answer is no. It asks only after the crashed server's session is closed, so the original message cannot still be in transit.
The second is to apply exchange reports idempotently and only forward: fills are keyed by execution id, and a late "accepted" after "filled" changes nothing. The third is to reconcile continuously for stuck pending or cancel_pending orders, and daily against the clearing firm's trade report.
Cancels race with fills. If Ana taps Cancel and the exchange fills her order 10 ms later, the exchange answers the cancel with "too late". The order therefore stays cancel_pending, shown as "Cancelling", until the exchange reports the final state.
Surviving the market open
The spike comes at the same time every trading day, and autoscaling that reacts to load is too slow, so the system scales the push servers, order servers and database on a schedule so that they are ready by 9:15. Clients add jitter to their reconnect delay, and snapshots are served from memory.
Bottlenecks and failures
At 10 times the load, the price path needs about 800 push servers and 8 GB/s of outgoing bandwidth, while the pub/sub system barely grows because it carries one message per symbol per server. The order path would reach 42,000 orders a second, which needs more database partitions and more exchange connections, and those take time to arrange. The table shows what happens when each component fails.
| When this fails | What happens | What you do |
|---|---|---|
| A push server | Its 25,000 clients lose their stream. | Clients reconnect to other servers with jitter. |
| The feed handler | Prices stop updating on every screen. | A standby takes over, and the app greys out quotes older than 5 seconds. |
| The pub/sub system | Quotes and order events stop, although the apps stay connected. | Run it replicated; after recovery apps refetch open orders. |
| An order server during a send | Some orders are left pending with an unknown outcome. | The reconciler asks the exchange about each. |
| The orders database primary | No new orders can be recorded. | Fail over to the synchronous replica, returning 503 meanwhile. |
| The exchange connection | Orders in flight have an unknown result. | Stop sending, reconnect, query every open order, then resume. |
What a strong answer sounds like
| Level | What the answer does |
|---|---|
| Junior | Polls for prices and calls the exchange directly from the order endpoint. |
| Mid | Uses a pub/sub topic per symbol with WebSockets, and makes orders idempotent with a client order id. |
| Senior | Separates the price path from the order path, conflates ticks, writes the order before calling the exchange and resolves crashes by asking the exchange, and scales for the open before it happens. |
Your order server crashes right after sending an order to the exchange. What happens?
The order was committed as pending with its client order id before it was sent, so the row survives the crash and the app's retry gets the same order back. A reconciler then asks the exchange about that id and records the answer, and it resends the order only if the exchange has never heard of it.
Follow-up questions
How would you add stop orders?
A trigger service sends a market order when the stop price is crossed. It reads the full feed rather than the conflated stream, because a brief cross within one second could be missed, and a conditional status update from "waiting" to "triggered" makes the order fire only once.
How do you stop a user from spending the same cash twice?
The reservation is a conditional update in the same transaction as the order insert: SET reserved_cents = reserved_cents + 50000 WHERE account_id = :a AND cash_cents - reserved_cents >= 50000. If two orders compete for the last $500, only one update matches the condition, because the database processes updates to the same account row one transaction at a time. The other order is rejected with "insufficient buying power".
An order fills 4 of 10 shares and then the user cancels. What happens?
The exchange cancels the remaining 6 shares, so the order ends as cancelled with filled_qty of 4, and the cash reserved for the 6 unfilled shares is released. A late fill and the cancel confirmation can arrive in either order, so the service must never let a report lower filled_qty.
What do you do when the market is closed or the exchange is down?
The order service knows the trading calendar, so outside market hours it either rejects market orders with a "market closed" error or queues orders the user chose to place for the next open. If the exchange connection drops during the day, the service stops sending, marks every order in flight as unknown, and reconnects. After reconnecting it queries the exchange for each open order before it resumes sending, which is the same reconciliation used after a crash.
After your attempt, tick what you really did. Be strict: "I thought about it" is not "I said it out loud".