Ch.72: System Design: Build a Robinhood-Style Stock Broker

Outline

Transcript

0:00 Robinhood is a retail stock broker. You watch stock prices and send buy or sell instructions; outside firms or markets can execute those trades. We'll design that journey from live quotes to trades and holdings. A connection failure mustn't turn one purchase into two. Take a customer, Maya, buying 10 shares of fictional ABC, with a 20-dollar maximum per share. Four execute before she cancels. Then her order can say canceled while she owns four shares. Cancellation can close the remaining six; it can't erase that trade.

0:31 Watch these three cards: price observed, order accepted, execution confirmed. Public broker APIs distinguish those facts. Sources are in the description; this is our proposed design, not Robinhood's private internals. Here's the complete broker path. The upper route feeds prices to Maya. Her buy instruction passes the authenticated gateway into the account and order core. That transaction boundary contains the order, the money held for it, and the outbound work still owed. We commit them together.

1:00 The execution adapter contacts our partner. Its reports return through a durable inbox before updating the account, holdings and history. Her account view exposes those committed results. She can miss the notification and still own the shares. Could prices and orders use one shared delivery pipeline? An obsolete display price may no longer help her. An older execution report can still explain shares she owns. Dropping both kinds of message would lose different things. Two delivery contracts, then. Keep that adapter in mind, too: later we'll test an old sender still trying to send after its replacement takes over. Let's pin down the functional requirements.

1:38 Maya loses her buy response, so we must retrieve her original order. What else should the service let her do? Retry that instruction or request cancellation, then reconnect to holdings and history showing filled and remaining quantities. Add watchlists, timestamped prices, and buy and sell limit orders. For Maya's buy, the limit caps her price per share. For a seller, it sets the minimum. Neither promises a complete trade right away. We'll start with eligible, funded cash accounts and whole shares.

2:06 Unresolved outside outcomes need operator investigation. Settlement means later delivery of money and shares after the trade. We'll name settlement's interface and leave its internals outside, along with the exchange's matching of buyers and sellers. Now set the non-functional requirements around those actions. An accepted instruction must survive failures and stay authorized to Maya's account; a retry mustn't create another outside order. Let's size them separately. Imagine 100,000 connected viewers, 10 watched symbols each and two delivered quote states per second.

2:39 The slide multiplies that into two million deliveries every second. 500 order commands per second in our example. These are design assumptions, not Robinhood's numbers. Would you give that smaller stream stronger guarantees? Honestly, I'm more nervous about the orders. An old price and a duplicate purchase aren't comparable losses. What must be saved before telling Maya her order was accepted? Save her instruction, protect the cash or shares committed to it, and retain dispatch work in the same durable transaction.

3:10 Replying earlier could promise work that disappears with the server. I'd accept extra order latency for that boundary. For the display, I'd prioritize freshness and bounded buffers over delivering every intermediate tick. Accepted still means we own her instruction. The partner must confirm execution before we claim she acquired shares. For that heavier price stream, suppose Maya's phone has three prices queued. By the time we display the first, it's already old. Would you make her watch the ones she missed?

3:40 No, let her catch up. Keep the newest quote with its source time and discard obsolete display states. Ingest and normalize each market feed once, then share its latest quote across subscription gateways. The diagram follows ABC out to its subscribers. Yes, but the fill card stays. Replacing a price must never replace evidence that four shares traded. If the feed stops, label its last price stale. Accepting an order still needs its own account, session and partner-readiness checks. Next, the command route needs stronger delivery rules.

4:15 Request K seven names Maya's account, 10 shares of ABC and a 20-dollar buy limit. Bind that identity to those original fields. Her phone loses the response and retries K seven. Would a fast cache lookup protect us from another order? The durable account transaction must enforce uniqueness. Check permissions and risk, reserve the funds, create O seven and save the instruction to send it outside, all in that transaction. For example, start Maya with 200 dollars available and no fees. Reserving 200 leaves none available for another purchase, even though nothing has traded yet.

4:51 And the same protection applies to selling: reserve shares instead. Both reservations belong under the account authority, so competing requests can't spend the same money or shares. And if the same identity comes back with changed order fields? Reject that conflict. An unchanged K seven retrieves the saved O seven; changed fields don't turn that identity into permission for another instruction. So we still owe Maya that send. Saving O seven doesn't pull the partner's network call inside our transaction.

5:21 Right, that's the outbox record. We can reply after that commit; a restarted adapter still finds the send waiting. Now the adapter takes O seven from the outbox and sends it as B seven. The call times out. Did it fail to arrive, or did the partner act while its response went missing? We can't tell from that timeout. Keep the routing outcome unresolved. I want the partner contract to recover the original client identity or resume its ordered session. For instance, the Alpaca brokerage API's order guide directs a timed-out submitter to check the broker dashboard and contact support, without resending or declaring the order canceled.

5:59 So an operator is part of that documented recovery path. Their client-order-ID lookup helps us track B seven; it doesn't make every empty result current. I don't trust that absence. For example, a later lookup finds B seven accepted. Can we tell Maya she owns shares? That confirms the instruction, not an execution. Attach the partner record to O seven. We need the fill evidence before adding shares, not another purchase attempt. When documented recovery can't resolve that outcome, keep O seven pending, protect its reservation and compare our records with the partner's.

6:34 A timer can't authorize another purchase. Now an execution arrives: E seven, four shares at 19 dollars and 90 cents. That's 79 dollars and 60 cents without fees. Six shares remain unfilled. Our inbox first saves the raw report. Application follows durable receipt; a socket receiving bytes isn't enough to keep that evidence through a crash. Yeah, saving the report isn't the finish. Apply E seven once in a local transaction: record that it's applied alongside the fill, order quantities, cash effects and outgoing event.

7:05 A repeat finds that record and stops. Look at the cash beside her shares. Our account model now records 120 dollars and 40 cents. We still reserve 120 for the remaining six; 40 cents can fund another order. Now E seven returns after a report reconnect. Maya still owns four shares, which is a relief. Can its identity tell us where to resume reading? No. That identity recognizes the trade; the saved replay position finds our place in the report history. They answer different questions. A bookmark and a receipt, then.

7:38 Rereading that receipt leaves her position at four. A missing report might hide an actual purchase. Can our bookmark get ahead of that evidence? A crash could lose that report but keep the later place. Save the incoming evidence with its receive checkpoint in one transaction, so we can't skip something we never kept. So we've kept the evidence, even if a worker hasn't booked its effect yet. Right. The worker commits each report's account effects and applied marker together. If processing crashes first, the saved report is still waiting; an already-applied E seven has no extra effect.

8:13 Now suppose the partner warns it dropped a report. We have one bookmark known to precede the gap and another after it. Where should we restart? Use the earlier place under the partner's replay rules. The later one skips the missing report. Stop checkpoint progress until recovery is established; a newer bookmark isn't proof of complete history. If that missing report could change Maya's available money, can we accept her next buy? Not against an unverified balance. Keep her last-applied view updating.

8:44 Without a safe replay place, compare records with the partner before promising funds. Alpaca's beta Activity stream illustrates these two roles. The field names and a separate trade-correction reference are on screen. Order status uses a separate stream. Next, Maya requests cancellation with four shares filled and six still open. Our core records cancel pending and dispatches that request to the partner. That screen would worry me. Graying out all 10 would make the four purchased shares look canceled too.

9:14 Keep the filled segment intact. Another execution may happen while cancellation is traveling. Who determines the final remaining quantity? The partner's evidence. Apply intervening fills according to its protocol, then apply confirmed cancellation to the quantity actually left open. In our chosen trace, the partner confirms six canceled. Release their 120-dollar reservation. Maya keeps her four shares. Her available cash is 120 dollars and 40 cents, with fees omitted. So the order says four filled, six canceled.

9:45 Canceled describes how it stopped, not whether it ever traded. The price stays beside the acquired four. Support can't promise a cancellation while the partner's outcome remains unknown. Next, turn those executions into holdings and history. Maya's position has four ABC shares. A later quote changes their displayed value; it cannot create a 5th share. For example, Maya fetches a snapshot at revision 41. She subscribes and gets 44 next. Did she really catch up? No, 42 and 43 are missing. A quote beside it can't fill that gap.

10:21 I'd label the account view updating. Keep a change log and resume after the snapshot's revision. That also closes the race between fetching a snapshot and subscribing. And if the log no longer has those missing changes? Fetch another coherent snapshot, rather than guess. New orders still need the account core's current funds check; this older display can't authorize spending. Notifications follow the same committed results. Dropping a notification can delay Maya's news; it mustn't change whether her order executed or how many shares she holds. Now scale the quote and order paths separately.

10:57 Quote distribution groups subscribers by symbol, spreading a popular stock's viewers across gateways. Could order commands use the same symbol partitioning? Maya can send an order for ABC, then XYZ, almost together. Separate symbol workers might both decide the same balance is available. We choose one account transaction authority for those decisions. The second reservation sees what the first already held. Other coordinated layouts can work; separate symbol writers can't each promise her the same money.

11:28 A hot account can still outrun its database writer. Imagine a product manager asking, 'Can we accept the order now and send it when the queue clears?' We'd owe that order, even with a full queue. I'd return retryable busy before accepting beyond our bounded capacity. The phone keeps the original request identity. Maya's phone lost an earlier response, though. What if that same request was already saved before she hit busy? Return O seven when K seven is already saved. Busy means no new acceptance on this attempt; the original outcome still needs checking.

12:02 Next, recover accepted orders and outbox work from replicated storage after failover. The store rejects commits from the old writer. Does that stop its adapter's delayed network send? No, that boundary needs outside enforcement. Our proposed session contract disables the old sender before activating the replacement, so an old-session new-order send is rejected outside our database. But B seven might already have reached the partner before disablement. Would we reject valid execution evidence delivered afterward?

12:30 We'd still accept valid evidence of that earlier execution through the partner's authenticated reporting or recovery channel. The new adapter recovers B seven under the same contract; fencing future sends doesn't erase previous trades. I think that outside barrier belongs in the integration contract. We aren't claiming Alpaca or Robinhood provides this exact session design. If we can't establish current authority and a safe sender handoff, pause new acceptance or dispatch as appropriate. A stale region may serve labeled historical reads, but cannot independently promise new orders.

13:03 I'd take that visible interruption. A pending instruction is painful; secretly sending it twice gives Maya a different position to pay for. Now look at this hypothetical account view after the partial fill: no ABC position. What would the operator check before trying a repair? Pull B seven's execution report through the authenticated channel. Its four shares cost 19 dollars and 90 cents each, under E seven. That establishes a trade; an accepted-order row alone wouldn't. Both execution records say four, but holdings show 0.

13:38 That points me to the view. A missing local fill would need a different repair. Yes, rebuild the derived holdings view from the committed execution, without another purchase. If the local fill itself were missing, recover and verify the partner report before applying its account effect once. Buying again would make Maya pay for our broken view. I'd track this mismatch until its owner resolves it, or our exception queue becomes a well-documented waiting room. With a very neat ticket and still no shares on her screen.

14:07 Robinhood engineers frame reliability around the customer's objective, separating essential dependencies from things that can degrade. Here, unavailable money or risk checks stop acceptance; missing news doesn't. An outage matters according to whether Maya can safely finish her objective. And a healthy connection isn't that objective. Track accepted-but-unsent work and report backlogs too; those locate durable work our services still owe her. Then the operator can link Maya's four listed shares back to E seven.

14:36 A customer result, its evidence and someone responsible for fixing a mismatch belong together. Now consider a crash during Maya's purchase, starting our fictional example with no position in ABC. K seven commits O seven, its reservation and the outbox, then the server crashes before replying. Her unchanged retry retrieves O seven. Recovery dispatches B seven from the saved work, but its reply is lost too, so the outside outcome is unresolved. We disable the previous session and activate its replacement, but lookup still doesn't find B seven.

15:10 Can we release Maya's reservation now? No. That barrier stops future old-session sends; it doesn't establish what happened before it. O seven stays pending with its reservation and original identity as we continue recovery under the agreed protocol. Then the current authenticated report channel delivers E seven, reporting that the earlier instruction bought four shares before the old session closed. Does the earlier empty lookup let us reject it? It doesn't. Persist E seven durably, then apply it once.

15:40 Record four acquired shares and their trade cost, retaining the reservation for six at the limit. E seven arrives again, then our partner confirms cancellation of those six. Maya reconnects while the quote feed is down. What should her account show? Four filled, six canceled, and a four-share position. Her reservation is cleared, leaving 120 dollars and 40 cents available. Recover that view through its snapshot and revisions; a stale price cannot change the acquired quantity. The empty lookup left us uncertain, but the later execution evidence resolved it.

16:12 We recovered Maya's trade without turning uncertainty into another purchase. Finally, return to our complete architecture. Prices reach Maya through the separate quote route. Her instruction reaches the account core, where the order, reservation and dispatch work commit together. Maya never had to place a replacement purchase. The adapter and partner recovery contract kept working on her instruction; execution evidence reached the inbox before holdings and history followed its results. Maya owns four shares, and six of the requested 10 are confirmed canceled.

16:44 Reconciliation checks the outside records; notifications explain the outcome. Thanks for listening to Learning Podcasts.