Design a stock trading platform - retail users place and cancel limit orders, the broker holds their money, and an external exchange executes the trades. An account must never spend money it does not have, while the exchange is slow at times, silent at times, and the only one who knows what was executed. The staff-level signal is separating "accepted" from "executed", reserving buying power in one transaction, and settling every doubt by asking the exchange.
Written by a Staff+ Engineer and an Engineering Manager
12+ years of experience in distributed systems and real-time messaging. Tech lead for large-scale chat applications serving billions of users. Over 12 years of industry experience with 6 years in engineering leadership, building and scaling tech infrastructure teams that deliver end-to-end large-scale distributed systems.
Finished this lesson?
Sign in to save your progress across devices.
Tip: use ← and → to move between lessons.
Was this lesson helpful?
Rehearse this exact question with the author
45-minute mock with a Staff+ engineer who interviews at your target company. Premium members save $20.
What to Design?
Could you answer these today? Tick what you already know.
The happy path is quick to draw: an API, an orders table, a call to the exchange. The interview is decided by four questions about what happens when two things meet at the same moment, or when the exchange stays silent. Each one is a deep dive later on this page, with three designs side by side: the one that sounds right, a better one, and the one that holds.
Swipe to see all columns
| The four questions, and the answer that sounds right | |||
|---|---|---|---|
| # | The interviewer asks | The answer that sounds right | What it misses |
| DD1 | Two buy orders from one account arrive in the same millisecond. The cash covers one. What happens? | Read the balance, check it, then save the order | Both requests read the same balance before either one writes. Both pass, and the account is overdrawn |
| DD2 | The exchange did not answer your call within 2 seconds. Do you send the order again? | Yes, retry on a timeout | |
The same three habits answer all four:
Do not spend your questions on screens and charts. Spend them on what the broker promises.
Swipe to see all columns
| Scope Decisions | ||
|---|---|---|
| Question | Agreed answer | Why it matters |
| What are we building? | The broker's order system: place, cancel, follow, and keep the balances right. The exchange that matches orders is external | The hard part is the border to a system we do not control |
| Which order types? | Limit orders only: buy or sell a number of shares at a given price or better | The most an order can cost is known up front: quantity times limit price |
| May an account go below zero, even for a moment? | Never | |
Out of scope (say this out loud): market orders, stop orders, options and trading on borrowed money; the matching engine inside the exchange; settlement and clearing after the trade; the feed of live prices; several regions; identity checks, tax reports and social features.
FR1 — Place a limit order. POST /v1/orders with symbol, side, quantity and limit price. A buy is accepted only when the account can pay quantity times limit price. A sell is accepted only when the account owns the shares.
FR2 — Send it to the exchange. Every accepted order is forwarded to the external exchange, once and only once.
FR3 — Record fills. The exchange executes an order in one or more parts. Each part is called a fill. Every fill changes the cash, the reserved money, the shares owned and the status of the order.
FR4 — Cancel. DELETE /v1/orders/{order_id} asks to cancel an order that is not fully filled. A fill that got there first stands.
FR5 — Read and follow. GET /v1/orders/{order_id} returns the true state of an order. A WebSocket pushes changes as they happen. GET /v1/accounts/me/balance shows the cash and the buying power.
The key principle behind all five
Swipe to see all columns
| Five facts and the conclusions they do not supportRead each row as: the fact on the left does not, by itself, imply the claim in the middle. | ||
|---|---|---|
| Fact | Does not imply | Why the gap exists |
| The balance check passed | The money is still there at the write | Another request may have passed the same check a millisecond ago |
NFR1 — No overdraft, ever. The money reserved for an account's open orders never exceeds its cash, at any moment, under any number of requests at once.
NFR2 — Nothing lost, nothing counted twice. Every accepted order and every fill is stored durably, exactly once, across crashes and retries.
NFR3 — Availability: 99.95% for placing and cancelling. A slow exchange must not block either.
NFR4 — Speed. An order is accepted in under 500 ms, and a fill is on the user's screen in under 2 s. Both are p95 values: 95 of 100 requests are at least this fast.
NFR5 — Scale. 1 million active users, 5 million orders per trading day, about 2,000 a second at the open.
| Capacity Thought Experiment | |
|---|---|
| Parameter | Value |
| Active users | 1 million |
| Orders per trading day | 5 million. A trading day is 6.5 hours, so about 210 a second on average |
| Peak, when the market opens | About 2,000 a second, ten times the average |
| Fills | About 2 per order: 10 million a day, about 4,000 a second at the peak |
| Delay of a report from the exchange | 50 to 500 ms after the fill |
The number that identifies the real system is not a big one:
peak orders 2,000 / s spread over a million accounts: orders of one account rarely meet
same account 2 in 1 ms rare, and every single time it must come out exactly right
exchange reply 50-500 ms on a good day. On a bad day: nothing at all
The load is modest. The system is hard because money must be exact when requests overlap, and because half the life of every order happens in a system we do not control. Every number above is an illustrative assumption.
Interviewer signal: candidates who draw one "trading service" that checks the balance and calls the exchange inside the user's request have missed both problems. Candidates who say "I accept the order with a reservation in one transaction, answer the user, and talk to the exchange afterwards, with a way to find out what happened when it stays silent" have found the system.
Three ideas shape everything:
"Accepted" is our promise. It is made inside one database transaction and takes milliseconds. "Executed" is the exchange's promise. It arrives later, in pieces, over a network that loses messages. The user waits only for the first one.
When an order is accepted, the broker reserves the money for it. This reservation is called a hold. We create holds and release them as we like. A fill is different: it is a trade that happened, a fact from the exchange. Fills are only ever added, never changed. What an account can still spend is its buying power: the cash minus the open holds. It is computed each time, never stored.
Only the exchange knows what was executed. Its answers can be late or lost. So every order we send carries our own id, and can be sent again. Every fill it reports carries its own id, and is counted once. And when it says nothing, we ask.
The core recognition
This is a small, strict ledger in front of an unreliable external system. Inside, one database transaction keeps the money exact. At the border, every message is idempotent: sending it twice has the same effect as sending it once. A background poller turns every "maybe" into "known".
| Design Decisions | |
|---|---|
| Design choice | Reason |
| Accept first, submit afterwards | The user's answer never waits for the exchange |
| A hold of quantity times limit price, created with the order in one transaction | The account cannot be overdrawn, and every fill is paid from money that is surely there |
Five tables carry the design:
accounts,holds,orders,fillsandpositions. The value to explain is buying power, and it is not a column in any of them.
Swipe to see all columns
| accounts | ||
|---|---|---|
| Field | Type | Comment |
account_id | STRING | Primary key, for example A-1 |
cash_balance | DECIMAL | The account's cash, 20,000.00 for Alice. Changed by a fill |
Buying power is cash_balance minus the remaining amount of every ACTIVE hold of the account. It is computed inside the placement transaction.
One row per order: the money reserved for it.
Swipe to see all columns
| holds | ||
|---|---|---|
| Field | Type | Comment |
hold_id | STRING | Primary key, for example H-1 |
account_id, order_id | STRING | Whose money, and for which order |
Swipe to see all columns
| orders | ||
|---|---|---|
| Field | Type | Comment |
order_id | STRING | Primary key, for example O-1. Also sent to the exchange (DD2) |
account_id, symbol, side | STRING | |
One row per fill reported by the exchange. Rows are added, never updated and never deleted.
Swipe to see all columns
| fills | ||
|---|---|---|
| Field | Type | Comment |
exchange_fill_id | STRING | Primary key: the exchange's id for the fill, for example xf-901. The same fill cannot be stored twice (DD3) |
order_id | STRING | The order it belongs to |
Swipe to see all columns
| positions | ||
|---|---|---|
| Field | Type | Comment |
account_id, symbol | STRING | Primary key together |
quantity | INT | Shares owned. Raised by a buy fill, lowered by a sell fill |
Swipe to see all columns
| Supporting records | ||
|---|---|---|
| Record | What it holds | Why it exists |
| Idempotency key | The key the client sent, the order it created and the stored response. Kept 24 hours | A repeated POST returns the first answer and changes nothing (Phase 1) |
| Outbox | An event such as order.accepted, with its payload | It is written in the same transaction as the change it announces. A relay reads it and publishes it to Kafka, so a change and its event cannot be separated |
Swipe to see all columns
| Who may change the status | ||
|---|---|---|
| Change | Made by | When |
New order to ACCEPTED | Order service | The hold exists (Phase 1) |
ACCEPTED to SUBMITTED | Exchange gateway | The exchange acknowledged the order (Phase 2) |
FILLED, CANCELLED and REJECTED are final: nothing changes an order after them. Three services write the status, and none writes it blindly. Every change is a guarded update: it names the version it read, and it changes nothing if the row has moved since.
Swipe to see all columns
| Storage | ||
|---|---|---|
| Store | Data | Consistency |
| PostgreSQL | accounts, holds, orders, fills, positions, idempotency keys, outbox | Strong, transactional. The source of truth. Placing an order needs one transaction over several of these tables |
| Redis | The buying power of each account, as a hint | Disposable and sometimes old. It may refuse an order early. It can never accept one |
| Kafka | Order events, keyed by account | In order for each account. Feeds the exchange gateway, the notifier and the audit log |
Swipe to see all columns
| What the user calls | ||
|---|---|---|
| Endpoint | Request | Response |
POST /v1/orders | Header Idempotency-Key. Body: symbol, side, quantity, limit price | 201 with the order id, status ACCEPTED and the held amount. The same key again: 200 with the same body. 400 when buying power is short. 429 over the rate limit |
DELETE /v1/orders/{order_id} | No body | |
Swipe to see all columns
| What we exchange with the exchange | ||
|---|---|---|
| Call | We send | It answers |
NewOrder | client_order_id (our order id), symbol, side, quantity, limit price | An acknowledgement with its own reference. The same client_order_id again returns the same acknowledgement |
CancelOrder | The exchange's reference | Received. The result comes later as a report |
A report arrives as a webhook: an HTTP call in the other direction, made by the exchange to our fill processor when it has news.
Two channels, two jobs. The WebSocket is fast and can drop a message. The GET reads PostgreSQL and is always right. The client treats a push as a hint. After a reconnect it first calls GET for its open orders, then listens again.
Present the design as four short stories, each in its own colour on one whiteboard: Phase 1 place (black), Phase 2 submit (blue), Phase 3 fill (green), Phase 4 cancel (purple). Every story has five or six numbered steps. The number on an arrow is the same number in the animation and in the step table.
Swipe to see all columns
| The four phases | |||
|---|---|---|---|
| Phase | Colour | Story | What it leaves behind |
| Phase 1: Place (FR1) | Black | Alice has 20,000 in cash. She buys 100 ACME at a limit of 150.25 | Order O-1 ACCEPTED. A hold of 15,025. Buying power 4,975 |
| Phase 2: Submit (FR2) | Blue | The order goes to the exchange | |
How to read the picture
Each phase below is an interactive walkthrough of the same picture. It plays on its own. You can pause it, step with the arrow keys, and click any component to read its role.
Goal: accept the order only if the money is there, reserve it in the same step, and answer without waiting for the exchange.
/v1/ordersClient → API gateway → Order serviceNothing is written in this step.
Swipe to see all columns
| Phase 1 step by step (black arrows) | ||
|---|---|---|
| Step | What happens | Data written |
| 1 | The client sends POST /v1/orders with the header Idempotency-Key: k-7f3a: buy 100 ACME, limit 150.25. | Nothing yet |
| 2 | The order service reads Alice's buying power from the cache: 20,000. Enough to go on. A clear "not enough" would be a 400 right here. | Nothing |
Why it is built this way
The exchange needs 50 to 500 ms on a good day, and on a bad day it does not answer. The user would wait for a system we do not control. And after a timeout we would have nothing true to tell them: not "placed", not "failed". So the broker answers for its own part only: the money is held and the order is saved. The exchange's part comes later, by push.
Goal: get the order to the exchange once, and remember the exchange's name for it.
order.acceptedEvent bus → Exchange gatewayNothing is written in this step.
Swipe to see all columns
| Phase 2 step by step (blue arrows) | ||
|---|---|---|
| Step | What happens | Data written |
| 1 | The exchange gateway reads order.accepted for O-1 from the event bus. | Nothing |
| 2 | The gateway sends NewOrder to the exchange: client order id O-1, buy 100 ACME, limit 150.25. It waits at most 2 seconds. | Nothing |
Why it is built this way
ACCEPTED. That is what the guarded update checks.REJECTED and closes the hold. The money is free again.A direct call fails when the gateway is down or busy, and then an order is accepted but never sent. With the outbox and Kafka the order waits in the log and is sent when the gateway is back. Kafka also keeps the events of one account in order, because the account id is the key. So the cancel of an order can never overtake the order itself.
Goal: record every fill once, move the money and the shares in the same step, and tell the user.
fill reportExchange → Fill processorNothing is written in this step.
Swipe to see all columns
| Phase 3 step by step (green arrows) | ||
|---|---|---|
| Step | What happens | Data written |
| 1 | The exchange sends a report to the fill processor: fill xf-901 for X-77, 40 shares at 150.10. | Nothing yet |
| 2 | One transaction applies the fill. 40 times 150.10 is 6,004.00. | Fill xf-901. Cash 20,000.00 to 13,996.00. Hold 15,025.00 to 9,021.00. Position ACME 0 to 40. Order PARTIALLY_FILLED, 40 filled, version 3. Outbox: order.fill |
Why it is built this way
FILLED.Because the cash has already dropped. After the first fill Alice has 13,996 in cash. With 15,025 still held, her buying power would be negative: the 6,004 would be counted once as spent and once as reserved. The hold exists to pay for fills. Each fill uses up a part of it, in the same transaction that takes the cash.
Later that morning Alice places a second order, O-2: buy 20 ACME at a limit of 148.00. It holds 2,960 and waits at the exchange as X-78. The price does not come down to 148, and she cancels.
Goal: pass the cancel on to the exchange, and free the money only when the exchange has agreed.
/v1/orders/O-2Client → API gateway → Order serviceNothing is written in this step.
Swipe to see all columns
| Phase 4 step by step (purple arrows) | ||
|---|---|---|
| Step | What happens | Data written |
| 1 | The client sends DELETE /v1/orders/O-2. | Nothing yet |
| 2 | The order service marks the order with a guarded update and answers 200: status CANCEL_REQUESTED. The hold stays. | Order O-2: SUBMITTED |
Why it is built this way
CANCELLED and closes the hold.For the same reason as the POST. The exchange may take long or stay silent, and the user would be waiting on a system we do not control. The 200 says that the request is recorded. The result arrives as a push, and a GET shows it at any time. If no report ever comes, the poller asks.
The deep dives are the four questions from the top of the page. Each one compares three designs for the same scenario: a Bad one, which is usually the answer that sounds right; a Good one, which still leaves a gap; and a Great one, which holds. The answers start covered. Read the scenario, decide what you would build, then click each card.
Swipe to see all columns
| Deep Dive Map | |||
|---|---|---|---|
| Deep Dive | Topic | Scenario | NFR |
Scenario: Alice has 20,000 in cash and no open orders. At 09:30:00 her phone and her laptop send the same buy in the same millisecond: 100 ACME at 150.25, which needs 15,025. Together they need 30,050. What must happen?
Three ways to build it. Decide what you would do first. The answers are covered: click a card to reveal it.
The idea. Read the cash and the open holds. If the money is there, insert the hold and the order.
Where it breaks. Both requests read before either one writes. Both see 20,000 free, both pass, and both insert a hold of 15,025. The account now has 30,050 held against 20,000 in cash. If both orders fill, Alice owes 10,050 that she does not have. A check that is separate from the write protects nothing.
The idea. Start the transaction with SELECT ... FOR UPDATE on the account row. This is a row lock: a second transaction that asks for the same row waits until the first one commits.
What it fixes. The two orders now run one after the other. The second one reads the first one's hold, sees 4,975 free and is refused with a 400.
What it still misses. The lock is a habit in application code. It works only while every piece of code that spends money takes the same lock first. The day someone adds a withdrawal endpoint and forgets it, a withdrawal slips in between an order's check and its commit. Nothing warns you.
The key idea. Let the database guard the rule. At the SERIALIZABLE level PostgreSQL commits only what could also have happened one transaction after the other. When two transactions each read what the other one changes, it refuses one of them.
How it works
SERIALIZABLE: look up the idempotency key, read the cash and the open holds, check, insert the hold, the order and the outbox row.The three designs side by side, in one picture:
Play the three options. Switch between them with the tabs at the top of the figure.
/v1/ordersAlice's phone → Order service (T1)/v1/ordersAlice's laptop → Order service (T2)Nothing is written in this step.
Swipe to see all columns
| DD1 side by side | |||
|---|---|---|---|
| Bad: check, then write | Good: row lock | Great: serializable | |
| Two buys in the same millisecond | Both accepted | One accepted, one refused | One accepted, one refused |
| Held against 20,000 in cash | 30,050 | 15,025 | 15,025 |
Check it against the scenario
| Alice's two orders | |
|---|---|
| Situation | Outcome with the Great option |
| Both requests arrive in the same millisecond | One commits. The database refuses the other, and it runs again |
| The second request, after its retry | It reads holds of 15,025, finds 4,975 free and answers 400 |
| The cache still says 20,000 for a moment | Both pass the pre-check. The transaction decides, not the cache |
| The phone repeats its request after a network error | The idempotency key is found. The first answer is returned, and no second hold is made |
| A withdrawal runs at the same time as an order | |
The trade-off to name. The database plays safe: it sometimes refuses a transaction that would have done no harm. So every caller needs a retry loop, and transactions must stay short. A row lock is an honest answer too, as long as you say what it costs: every writer has to remember it.
One UPDATE that lowers the column only if enough is left is atomic, so it does stop the overdraft. The cost is a second copy of the truth. Every fill, every cancel and every release must change the column and the hold together, and one forgotten case makes the number wrong for good. Cash and holds are needed anyway. Computing the buying power from them leaves nothing to keep in step.
"Placing an order is one database transaction at serializable isolation: look up the idempotency key, read the cash and the open holds, check that the worst-case cost fits, insert the hold and the order. Buying power is computed as cash minus open holds, never stored. If two orders of one account race, the database aborts one with a serialization failure. I retry it, the retry sees the first hold, and the order is refused. A Redis value in front rejects accounts that are clearly short, but it never accepts. I keep the transaction to a few rows, so retries are rare."
Follow-up: "Does this hold at 2,000 orders a second?" — Yes. Transactions collide only when they belong to the same account. A million accounts share those 2,000 orders, so two orders of one account almost never overlap, and when they do, the cost is one retry.
Scenario: At 09:30:00 the exchange gateway sends O-1 to the exchange. Two seconds pass and no answer comes. Maybe the order never arrived. Maybe it arrived and the answer was lost. Maybe the request is still waiting in a queue. What does the gateway do?
Three ways to build it. Decide what you would do first. The answers are covered: click a card to reveal it.
The idea. A timeout is a failure. Retry.
Where it breaks. The first request may have arrived. Then the exchange holds two orders: X-77 from the first attempt and X-78 from the second. Both can fill. Alice buys 200 shares for about 30,050, and her hold covers 15,025. The opposite reflex, "give up and release the hold", is just as wrong: the order may be live at the exchange with no money behind it.
The idea. Before a retry, ask the exchange whether it has an open order that looks like ours. Send again only if it has none.
What it fixes. The common case: the order arrived and only the answer was lost.
What it still misses. The question and the retry are two steps. If the first request is still on its way, the exchange answers "none", the gateway sends again, and then the first request lands too. And "looks like ours" is a guess: a user may really want two identical orders.
The key idea. Give the order a name before it leaves, and let the exchange refuse a second order with that name. Our order id travels as client_order_id. Sending twice then has the same effect as sending once.
How it works
NewOrder with client_order_id O-1.ACCEPTED to .The three designs side by side, in one picture:
Play the three options. Switch between them with the tabs at the top of the figure.
NewOrderExchange gateway → ExchangeNothing is written in this step.
Swipe to see all columns
| DD2 side by side | |||
|---|---|---|---|
| Bad: send again | Good: ask, then send | Great: same id every time | |
| The order arrived, the answer was lost | Two orders at the exchange | One order | One order |
| The first request is still on its way | Two orders | Two orders | One order |
Check it against the scenario
| O-1 on its way to the exchange | |
|---|---|
| Situation | Outcome with the Great option |
| The request is lost before it reaches the exchange | The retry creates X-77. One order |
| The order is created and the answer is lost | The retry returns X-77 again. One order |
| The request is slow and lands after the retry | The exchange already knows O-1 and ignores the late copy |
| The gateway crashes before it saves X-77 | The event is delivered again. The same id gets the same answer |
| The exchange refuses the order | |
The trade-off to name. The design leans on a promise of the exchange: it must remember client order ids for at least as long as we may retry. In return the gateway needs no clever logic. On any doubt it sends the same request again.
Because the reference comes back in the answer, and the answer is exactly the message that was lost. After a timeout we do not know X-77, so we cannot ask about it. An id that we choose before the first send is known to both sides even when no answer ever arrives. That is why it must be ours, and why it must not change between attempts.
"A timeout tells me nothing about whether the exchange has my order. So I never retry blindly and I never give up blindly. Every order goes out with my own order id as the client order id, and the exchange treats that id as an idempotency key: the same id returns the acknowledgement that already exists. On a timeout I send the identical request again, with a growing delay. The order stays in ACCEPTED with its hold until I have an acknowledgement, then moves to SUBMITTED with a guarded update. If the gateway crashes in between, the event is delivered again and the second send is harmless."
Follow-up: "What if this exchange does not recognise repeated client order ids?" — Then I query by that id before any resend, keep the order marked as "answer unknown" so it is not sent a second time on a guess, and let the poller settle it. It is slower, but it never creates a second order.
Scenario: O-1 is SUBMITTED. At 09:30:05 the exchange fills 40 shares at 150.10 and sends its report, fill xf-901. At that moment the fill processor is restarting for a deploy. The report is lost. Or it is delayed and arrives six minutes later. What do Alice's order, cash and shares show?
Three ways to build it. Decide what you would do first. The answers are covered: click a card to reveal it.
The idea. The exchange reports every fill. When a report comes, apply it.
Where it breaks. The exchange sends a report once. If it is lost, O-1 stays SUBMITTED for ever. Alice owns 40 shares that her broker does not show, so she cannot sell them, and her 15,025 stays held. No error appears in any log, because nothing failed on our side.
The idea. A background job looks for open orders that have been silent for 5 minutes and asks the exchange for their state. What it learns is applied like a report.
What it fixes. The lost report. Within about six minutes the missing fill is found.
What it still misses. A report that was only late. The poller applies the fill at 09:35. At 09:36 the delayed report arrives, and the fill processor applies it again. Alice's account shows 80 shares and the cash was taken twice. Two paths now deliver the same fact, and nothing tells them apart.
The key idea. The exchange gives each fill its own id. Store the fill under a unique index, in the same transaction that moves the money. Then it does not matter how often a fill arrives, or by which path. It is counted once.
How it works
exchange_fill_id. Then lower the cash and the hold, raise the position, and move the status with a guarded update.updated_at is more than 5 minutes old and calls . It applies every fill the exchange lists.The three designs side by side, in one picture:
Play the three options. Switch between them with the tabs at the top of the figure.
fill reportExchange → Fill processorNothing is written in this step.
Swipe to see all columns
| DD3 side by side | |||
|---|---|---|---|
| Bad: wait | Good: poller, no id check | Great: poller and unique fill id | |
| The report is lost | The order is stuck for ever | Repaired in about 6 minutes | Repaired in about 6 minutes |
| The report is 6 minutes late | Applied late, but once | Applied twice: 80 shares | Applied once: 40 shares |
Check it against the scenario
| One fill, 40 shares at 150.10 | |
|---|---|
| Situation | Outcome with the Great option |
| 09:30:05 the report is lost | Nothing changes yet. O-1 is SUBMITTED and silent |
| 09:35:05 the poller picks O-1 | GetOrder lists fill xf-901. It is applied: cash 13,996, hold 9,021, 40 shares |
| 09:36 the late report arrives | The insert of xf-901 fails on the unique index. Nothing changes |
| The order has no fill yet | The poller finds nothing new, notes the time and looks again 5 minutes later |
The trade-off to name. The poller costs calls to the exchange, and a lost report still takes minutes to repair. The 5 minutes are a dial: a shorter wait repairs sooner and asks more often.
If the exchange retries until it gets a 200, most losses disappear, and you should use that when it is offered. But it is the exchange's promise, not ours. Its retries may stop after a while, and we cannot test what it does on its worst day. The poller needs only one call, "get order", and it is ours. Use both. Rely on the one you control.
"I never read silence as 'not filled'. Fill handling is idempotent: every fill carries the exchange's fill id, I insert it under a unique constraint, and in the same transaction I adjust the cash, the hold, the position and the status. A duplicate report changes nothing. On top of that a reconciliation poller runs all the time. It scans open orders with no update for five minutes, asks the exchange for their state, and feeds anything that is missing through the same function. The report is the fast path. The poller is the guarantee."
Follow-up: "Where do the five minutes come from?" — From the normal delay of a report, which is under half a second. An order that is silent for minutes is either waiting for its price or missing a report. Five minutes keeps the number of questions low, and it can be shortened.
Scenario: O-1 is PARTIALLY_FILLED: 40 of 100 shares, with 9,021 still held. At 09:31:00.000 Alice taps cancel. Fifty milliseconds later, before her cancel reaches the exchange, the exchange matches the last 60 shares at 150.20. It will send two reports: fill xf-902, and "cancel rejected". What is the final state of O-1?
Three ways to build it. Decide what you would do first. The answers are covered: click a card to reveal it.
The idea. The user asked first. Set the order to CANCELLED, release the hold, answer "cancelled", then tell the exchange.
Where it breaks. The exchange never agreed. The fill for 60 shares arrives for an order that we call cancelled. If we drop it, Alice owns 60 shares that are in no book. If we apply it, 9,012 must be paid from a hold that was released, and that money may be in another order already. Our database cannot undo a trade.
The idea. The DELETE only sets CANCEL_REQUESTED and keeps the hold. The cancel goes to the exchange, and the exchange's report decides.
What it fixes. The money. The hold is still there when the fill arrives.
What it still misses. Two reports arrive at almost the same time, and two workers take one each. Each worker reads the order, decides, and writes the row back. The fill worker writes FILLED. The other worker read the order a moment earlier, and now writes what it saw: PARTIALLY_FILLED, 40 filled. The last write wins, and a fully filled order shows as open.
The key idea. A cancel is a question to the exchange. And no worker may change an order that has moved since the worker read it.
How it works
CANCEL_REQUESTED with a guarded update. The hold stays. The answer is 200, "cancel requested".CANCEL_REQUESTED can end as CANCELLED or as FILLED. The exchange's report picks one.UPDATE orders SET status = 'FILLED', version = 5 WHERE order_id = 'O-1' AND version = 4. If the row has moved, no row changes.The three designs side by side, in one picture:
Play the three options. Switch between them with the tabs at the top of the figure.
/v1/orders/O-1Client → Order serviceNothing is written in this step.
Swipe to see all columns
| DD4 side by side | |||
|---|---|---|---|
| Bad: cancel at once | Good: wait, plain updates | Great: wait, guarded updates | |
| What the DELETE answers | Cancelled | Cancel requested | Cancel requested |
| The hold when the fill arrives | Released | Still there | Still there |
Check it against the scenario
| Cancel at 09:31:00.000, match at 09:31:00.050 | |
|---|---|
| Situation | Outcome with the Great option |
| Alice taps cancel | O-1 is CANCEL_REQUESTED, version 4. The 9,021 stays held |
| The fill report for 60 shares arrives | It is recorded. Cash 4,984, 100 shares. O-1 is FILLED, version 5. The last 9 of the hold is released |
| The "cancel rejected" report arrives at the same moment | Its update changes no row. It reads FILLED and is dropped |
| Alice's screen | |
The trade-off to name. The user cannot be told "cancelled" at once. For a moment the app shows "cancel requested", and now and then the result is "too late, it filled". That is honest: until the exchange answers, the broker does not know.
A row lock works as well: lock the order, read it, decide, write. The version reaches the same goal without holding a lock while the worker thinks, and it also protects code that read the order outside the transaction. Either way the rule is the same: decide on fresh data, or do not write.
"Cancel is best effort. The DELETE moves the order to CANCEL_REQUESTED and forwards the cancel, and the hold stays. Only the exchange knows whether the cancel or the match came first, so its reports decide: a cancel confirmation moves the order to CANCELLED and releases the hold, a fill moves it to FILLED and the cancel is dropped. Fills always stand. Every transition is a compare-and-set on the order's version inside the fill transaction, and a final status accepts nothing, so two reports that arrive together cannot overwrite each other."
Follow-up: "The user sees 'cancel requested' and then 'filled'. Is that acceptable?" — Yes, and it is the only honest behaviour. The alternative is to say "cancelled" and then take the money anyway.
| If the interviewer keeps going | |
|---|---|
| Question | Short answer |
| A fill comes at a better price than the limit? | That is normal for a limit order. The hold was sized for the limit price, so it always covers the fill. Each fill lowers the hold by what it cost, and what is left is released when the order ends |
| And sell orders? | The same design with shares in the place of money. Placement reserves the shares in positions in one transaction, so the same shares cannot be sold twice. A fill lowers the position and adds the cash |
| The exchange gets slow, or goes down? | A circuit breaker in the exchange gateway: a switch that stops calls to a failing system for a while. Orders are still accepted and wait in ACCEPTED, with their holds. If the exchange stays down, new orders are refused with 503. Orders that were already sent stay as they are until the poller can ask again |
Two requests pass the same check before either one writes. Make the check and the hold one serializable transaction.
A stored copy drifts away from the cash and the holds behind it. Compute it each time: cash minus open holds.
The user waits for a system you do not control, and after a timeout you have no true answer to give. Accept, answer, then submit.
The first attempt may have arrived, and now there are two live orders. Send your own order id with every attempt, so a repeat creates nothing.
A report is sent once and can be lost. A poller asks the exchange about every order that has been silent too long.
The same fill can arrive by a report and by the poller. A unique fill id, stored in the same transaction as the money, makes it count once.
A fill may be on its way, and it needs that money. Release the hold only when the exchange has confirmed the cancel.
Pushes get lost and arrive out of order. The GET on the database is the truth, and the client asks it after every reconnect.
The shape of a strong answer: split the life of an order into what the broker decides and what the exchange decides. Accept an order in one transaction that checks the money and holds it. Answer the user, then send the order with an id of your own. Record every fill once, with its money, in one transaction. Treat a cancel as a question. And keep a poller running that asks the exchange about everything that has gone quiet.
Keep "accepted" apart from "executed"
The 201 says that the money is held and the order is saved. The trade is the exchange's news. It arrives by report, is pushed to the user, and can always be read with a GET.
Let one transaction move the money
Placing an order checks and holds in one serializable transaction. A fill changes the fill row, the cash, the hold, the shares and the status together. Buying power is always computed from the cash and the holds.
When in doubt, ask the exchange
A timeout is answered by sending the same request again with the same id. A silence is answered by the poller. A cancel is answered by the exchange's report. Nothing is ever guessed.
| What the interviewer expects at each level | |
|---|---|
| Level | A strong answer shows |
| Junior | The main parts: an order service, an exchange gateway, a database. The path from placing an order to a fill. Buying power is checked before an order is accepted |
| Mid-level | Splits accepting from executing and says why: the exchange is slow and asynchronous. Creates a hold with the order in one transaction, and names one way to keep it safe when requests overlap |
| Senior | Drives every choice from the two promises. Handles the exchange's failures with named tools: an id on both sides of every message, a poller, guarded status changes. Explains the cancel race without picking a fixed winner |
These aren't toy problems — they reflect real infrastructure challenges at companies that move money against systems they do not control. If you want to walk through this design in a mock interview or get feedback on your own approach, book a session with us. We're here to help you sharpen your thinking, build your confidence, and land your next offer.
Pick an answer for each question, and you see at once whether it is right. Show explanation opens the answer, why it is right, and why each of the other options fails.
Question 1 of 10
Two buy orders of one account arrive at the same moment. The cash covers one. What keeps the second from being accepted?
Question 2 of 10
Alice gets a 201 with status ACCEPTED for her buy of 100 shares at a limit of 150.25. What has the broker promised?
Question 3 of 10
The exchange gateway sent O-1 to the exchange and got no answer for 2 seconds. What is the safe move?
Question 4 of 10
O-1 has been SUBMITTED for five minutes and no report has come. What settles its state?
Question 5 of 10
The same fill reaches the broker twice: once from the poller and once as a late report. Why does Alice still have 40 shares and not 80?
Question 6 of 10
Alice taps cancel. The exchange had already matched the rest of her order. What is the final status?
Question 7 of 10
O-1 holds 15,025 for 100 shares at a limit of 150.25. The first fill is 40 shares at 150.10. How much is still held?
Question 8 of 10
The app was offline for a minute and reconnects. How does it get the right state of its open orders?
Question 9 of 10
Why is buying power not stored as a column of the account?
Question 10 of 10
Redis says Alice has 20,000 of buying power. Her order needs 15,025. What may the order service conclude?
| A timeout does not say that the order did not arrive. A second send can create a second live order |
| DD3 | An order was sent 5 minutes ago and no report came back. What is its state? | Still open. No report means no fill | Reports get lost. The order may be filled at the exchange while your books show nothing |
| DD4 | The user taps cancel while the exchange is filling the order. Who wins? | The cancel. The user asked first | Only the exchange knows which came first. Your database cannot undo a trade |
| The check and the reservation must be one step (DD1) |
| What if the exchange does not answer? | The order stays in a known state until we find out. It is never guessed and never stuck for ever | Safe retries (DD2) and a poller that asks the exchange (DD3) |
| Who decides between a cancel and a fill? | The exchange. If it reports a fill, the fill stands | A cancel is a request, not a fact (DD4) |
| How does the user learn about a fill? | A push over a WebSocket, which may lose messages, and a GET that is always right | Speed and truth are two channels |
| Does the reserved money shrink as the order fills? | Yes, fill by fill | The reservation is adjusted in the same transaction as the fill |
| The broker answered 201 | A trade happened | The 201 says the money is held. Only the exchange executes |
| The call to the exchange timed out | The order did not arrive | The request or the answer may be late or lost |
| No fill report arrived | Nothing was filled | A report is sent once and can be lost |
| The user asked to cancel | The order is cancelled | The exchange may have filled it first |
| WebSocket connections at the peak |
| 200,000 |
| Storage | An order row is about 500 bytes and a fill row about 200: 4.5 GB a day, about 1.1 TB a year |
| Database load at the peak | About 8,000 small transactions a second: 2,000 placements, 2,000 status changes, 4,000 fills |
| Buying power is computed: cash minus open holds | A stored copy could drift away from its inputs |
| The placement transaction runs at SERIALIZABLE | The database refuses two transactions that both passed the check on old data |
| An idempotency key on every POST | A client retry gets the first answer back and creates no second hold |
| Our order id travels to the exchange | Sending an order again creates no second order |
| Fills are append-only and unique by the exchange's fill id | A report that arrives twice counts once |
| Every status change is a guarded update | Two workers cannot overwrite each other, and a final status stays final |
| An outbox row in the same transaction, relayed to Kafka | No event is lost between the database and the event bus |
| A poller asks the exchange about silent orders | A lost report is repaired without anyone noticing |
| WebSocket for speed, GET for truth | A lost push costs a moment, never correctness |
amount | DECIMAL | Reserved at placement: quantity times limit price, 15,025.00 |
remaining | DECIMAL | What is still reserved. Each fill lowers it by what the fill cost |
status | ENUM | ACTIVE / CLOSED. Closed when the order ends. What remained is free again |
| Who, what, and BUY or SELL |
quantity, limit_price | INT, DECIMAL | 100 shares at 150.25 or better |
status | ENUM | See the status table below |
filled_quantity | INT | Shares executed so far |
exchange_order_ref | STRING | The exchange's name for the order, for example X-77. Set when it acknowledges |
version | INT | Raised by 1 on every status change. Used by the guarded update (DD4) |
updated_at | TIMESTAMP | The poller finds silent orders by status and this time (DD3) |
quantity, priceINT, DECIMAL |
| 40 shares at 150.10 |
reserved_quantity | INT | Shares promised to open sell orders, so that they cannot be sold twice |
ACCEPTED to REJECTED| Exchange gateway |
| The exchange refused the order. The hold is closed |
SUBMITTED to PARTIALLY_FILLED to FILLED | Fill processor | Fill reports (Phase 3) |
Any open status to CANCEL_REQUESTED | Order service | The user asked (Phase 4) |
CANCEL_REQUESTED to CANCELLED | Fill processor | The exchange confirmed. The hold is closed |
CANCEL_REQUESTED to FILLED | Fill processor | A fill came first (DD4) |
CANCEL_REQUESTEDGET /v1/orders/{order_id} | No body | The true state: status, filled quantity, amount still held, times |
GET /v1/orders?status=open&cursor= | A status filter and a cursor | One page of orders, newest first |
GET /v1/accounts/me/balance | No body | Cash, held amount, buying power |
WS /v1/orders/stream | A WebSocket | Status changes and fills, pushed as they happen. A message can be missed |
GetOrder | Our order id, or the exchange's reference | The state of the order and all its fills. Used by the poller |
Report (the exchange calls us) | Nothing | One of: a fill with its fill id, quantity and price; cancelled; rejected; cancel rejected |
SUBMITTED| Phase 3: Fill (FR3, FR5) | Green | The exchange fills 40 shares, then the other 60 | O-1 FILLED. 100 shares, cash 4,984, no hold |
| Phase 4: Cancel (FR4) | Purple | Alice cancels a second order that is waiting at the exchange | Order O-2 CANCELLED. Its hold of 2,960 is free again |
| 3 |
One transaction at SERIALIZABLE. The key is new. Cash 20,000 minus holds 0 covers 15,025. The hold, the order and an outbox row are inserted. |
Hold H-1: 15,025.00, ACTIVE. Order O-1: ACCEPTED, version 1. Key k-7f3a with the response. Outbox: order.accepted |
| 4 | The client gets 201: order O-1, status ACCEPTED, held amount 15,025.00. The exchange has not heard of the order yet. | Cache: buying power 4,975 |
| 5 | The outbox relay publishes order.accepted to the event bus, keyed by account A-1. | The outbox row is marked as published |
| The exchange acknowledges. Its reference for the order is X-77. |
| Nothing on our side |
| 4 | The gateway records the acknowledgement with a guarded update. | Order O-1: ACCEPTED to SUBMITTED, reference X-77, version 2. Outbox: order.submitted |
| 5 | The relay publishes the event. The notifier pushes "O-1 is submitted" over Alice's WebSocket. | Nothing |
| 3 |
| The relay publishes the event. The notifier pushes "40 of 100 filled at 150.10". |
| Nothing |
| 4 | The second report arrives: fill xf-902, 60 shares at 150.20, which is 9,012.00. The same transaction runs again. The order is complete, so the hold is closed and the 9.00 left in it is free. | Fill xf-902. Cash to 4,984.00. Position to 100. Order FILLED, version 4. Hold CLOSED |
| 5 | After a reconnect the client asks GET /v1/orders/O-1. The order service reads PostgreSQL: FILLED, 100 shares, 15,016.00 paid. | Nothing |
| 6 | Every minute the poller asks the exchange about open orders that have been silent for 5 minutes. A fill it finds goes through step 2. | Nothing, as long as no report was lost |
CANCEL_REQUESTEDorder.cancel_requested| 3 | The relay publishes the event. The exchange gateway sends CancelOrder for X-78 to the exchange. | Nothing |
| 4 | The exchange decides and reports to the fill processor: X-78 is cancelled, nothing was filled. | Nothing yet |
| 5 | One transaction ends the order and frees the money. | Order O-2: CANCELLED. Hold H-2: 2,960.00 to 0, CLOSED. Outbox: order.cancelled |
| 6 | The relay publishes the event. The notifier pushes "O-2 is cancelled". Buying power is back at 4,984. | Nothing |
| DD1 |
| Two orders, money for one |
| The same buy from two devices in one millisecond |
| NFR1 — No overdraft |
| DD2 | The exchange did not answer | The submit call gets no reply for 2 seconds | NFR2, NFR3 — Exactly once, availability |
| DD3 | The fill report never arrives | A report is lost, or six minutes late | NFR2 — Nothing lost, nothing twice |
| DD4 | Cancel meets fill | A cancel and a fill 50 ms apart | NFR1, NFR2 — Correct money, correct state |
SERIALIZABLE is the default level of this database. New code is protected without knowing the rule.| Nobody |
| Every code path that remembers the lock |
| The database, for every transaction |
| A new endpoint that spends money | Not protected | Not protected until it takes the lock | Protected by default |
| The price | None | Orders of one account wait in line | A retry now and then |
| The same rule: one of the two is refused and runs again |
SUBMITTEDACCEPTED, so it is sent again, with the same id and the same result.| The gateway crashes after sending |
| Sent again: two orders |
| Depends on a guess |
| Sent again with the same id: one order |
| What the exchange must offer | Nothing | A search by account | A client order id that it remembers |
REJECTED| The exchange is down for minutes | O-1 stays ACCEPTED, with its hold. The gateway keeps trying, more slowly each time |
GetOrderCANCEL_REQUESTED with no answer is asked about in the same way.| The exchange sends one report three times |
| Counted three times |
| Counted three times |
| Counted once |
| Our books against the exchange | Behind | Ahead | Equal |
| The exchange cannot be reached |
| The order stays as it is, with its hold. The poller tries again the next minute |
FILLED, a final status. Its report no longer applies and is dropped.| Final status when the fill came first |
CANCELLED, with 60 shares not recorded or not paid |
FILLED or PARTIALLY_FILLED, by luck |
FILLED |
| Who decides | Our database | The exchange, unless two writes cross | The exchange |
A push says filled. GET /v1/orders/O-1 says the same |
| The other order of events: the cancel reaches the exchange first | The report says cancelled, 60 not filled. O-1 is CANCELLED, 9,021 is released, the 40 shares stay |
| Neither report ever arrives | The poller asks the exchange after 5 minutes (DD3) |
| A regulator asks what happened to one order last March? | An audit trail. Every status change and every fill is an outbox event, and a consumer writes all of them, append-only, to cheap storage. The orders table shows the state now. The log shows every step |
| The market opens and traffic is ten times higher? | Orders collide only within one account, so one user never blocks another. Split the database by account id: all rows of an account live on one shard, and the placement transaction stays on one machine. Never lower the isolation level to gain speed. That is how overdrafts happen under load |
| The WebSocket drops a message? | Nothing is lost. A push is a hint. After a reconnect the client reads its open orders with GET and then listens again |
| Fees? | Add an estimate of the fee to the hold at placement. The real fee is taken in the fill transaction, from the hold |