Ch.27: System Design: How a Stock Exchange Matches Orders

Outline

Transcript

0:00 It's mid-morning at Lantern, a stock exchange we made up for this episode. Priya is offering 100 shares of Kestrel Robotics, a company we also made up, at 50 dollars each. In the same instant, Marco and Lena each send an order to buy 100 shares at 50 dollars or less. Two buyers, and only one seller at that price. So somebody walks away without the shares. Somebody has to. Here's how it should end: Marco gets the shares, Lena's order waits in line, and when Priya tries to cancel a moment later, she's told it's too late.

0:34 Okay, so what does the broken version look like? Pick your failure. One design sells 200 shares when only 100 were ever offered. Another tells Marco he bought them, then a server dies, and the backup's records say Lena did. Oof. So Marco is holding a confirmation for a trade that the surviving machine never made. Exactly. So today we build an exchange where every computer involved gives that same answer, even after one of them dies. So let's put the finished system on screen first. On the left, brokers, the firms that send orders in for traders, connect through gateways that check each order at the door.

1:12 And then straight into whatever does the matching? Not quite. First a sequencer, which numbers every order and writes it to a journal that's copied to a second machine. Huh, so numbering comes before matching, not after. Right. The matching engine is the part that pairs buyers with sellers, and it has a twin shadowing it. On the right, the results fan out to brokers, to a public data feed, and to the firms that settle the money. So the whole design is about who goes first, and whether anybody can cut in line?

1:44 Pretty much. Each box exists so that nobody cuts the line, and by the end, Marco's order will have touched every one of them. Before we open any of those boxes, I need a quick vocabulary check, because I've honestly never had to learn the trading words. Marco's order says 100 shares, 50 dollars at most. What's that called, and is he guaranteed to get them? That's a limit order: buy or sell at this price or better. And no, the SEC's investor guide says plainly that it isn't guaranteed to execute. If nobody is selling at 50 or below, Marco just waits. Waits where, though? In the order book. Think of it as two sorted lists of waiting orders.

2:26 Buyers are ranked highest price first, and sellers lowest price first. Right now Priya tops the sell side at 50 dollars, and the next seller is asking 50 dollars and 10 cents. When a buy and a sell meet on price, they trade, and each trade is called a fill. And when two orders sit at the same price, does the bigger one win? No, size doesn't buy you anything there. On a first-in, first-out book, whoever got there first. CME Group, a big exchange operator, documents that as one of its matching rules: best price wins, and arrival time breaks the tie.

3:03 So what if Priya edits her order? Does she keep her spot? Not if she changes her price or adds shares. Under that CME rule, either one sends her to the back of the line. Oh, so arrival order isn't bookkeeping trivia here. A tiny head start decides who actually trades. And protecting that head start is the whole job. The functional requirements fit in one breath: take limit orders and cancels from brokers, match them by price and then by time, tell both sides about every fill, and publish what happened.

3:34 Okay, but none of that rules out our two broken endings. No, the non-functional requirements do that. Conservation comes first: the exchange never sells more shares than were offered, and every trade happens once. Our 200-share ending violates that one. And Marco's orphaned confirmation is a determinism failure. Every machine should apply one agreed sequence of orders and end with an identical book, so a backup or an auditor can replay the whole day and land in the same place. Then there's a 3rd failure we haven't even seen yet, and the fix for it is durability.

4:08 No trader gets told they bought anything until the order behind it is written down and copied. Latency matters too. Everyone watching should get the feed at the same moment, and a frenzy in one stock can't slow down all the others. But a short pause during failover, or a rejected order, is an acceptable tradeoff. When speed and correctness collide, correctness wins. And that's why the obvious scaling move scares me. Most engineers expect to scale this like any web service. So let's say we do it, with two stateless matching servers reading the same shared book. Marco's order lands on one, and Lena's lands on the other.

4:48 And both read the book at the same moment. Both see Priya's offer still available, so both fill it, and the exchange has sold double what Priya offered. The classic check-then-act race. We've all shipped some version of that bug against a database row. Usually it shows up as an inventory count of minus one and a ticket nobody wants. The standard fix is a lock, which does fix the count. But now whichever server grabs the lock first wins, and that comes down to timing on that particular run. So the count is right, but the winner gets picked by timing instead of anything we can write down? Yes. Nothing about why Marco won survives the run, so nobody can check it later.

5:29 So think about what it costs to compute on a book that keeps changing underneath you, like on Facebook's first trading day in May 2012. Nasdaq had to compute one big opening match from all the waiting orders, and the SEC's 2013 order, linked in the description, lays out what went wrong. I remember the headlines, but not the mechanics. What actually broke? Traders could still cancel while the calculation was running. A validation check noticed the book had changed and forced a recalculation. I mean, that sounds like the responsible thing to do.

6:01 Why match on stale orders? It is, as long as the cancels stop. That recalculation picked up only the first new cancel, more kept arriving, and the system went around in a loop. Oh no. So it kept chasing a moving target and never caught it. It never did. So engineers bailed out: they switched to a duplicate copy of the matching engine with that validation check removed. The match finally completed around 11:30, but the system had fallen 19 minutes behind. Hold on. So the cancels that came in during those 19 minutes...

6:35 ...were ignored, even though Nasdaq had already confirmed them to the traders. Orders their owners thought were canceled got matched anyway, and Nasdaq absorbed those trades into an account it keeps for its own mistakes. Wait, so Nasdaq ended up owing shares it didn't have? It did, because more of the canceled shares were sells than buys. That left Nasdaq short more than three million shares of Facebook, worth about 129 million dollars. The SEC later fined it 10 million dollars. That's brutal. So the lesson I'd take, and this is our reading rather than the SEC's wording: compute on one numbered, frozen sequence of inputs, never on a book that something else is still changing.

7:17 Then let's freeze it. Every order and every cancel goes through one sequencer first, and it stamps the next number before anything touches the book. Marco's buy gets 81, Lena's gets 82, and Priya's cancel gets 83. Even though they arrived in the same instant? Same instant to us, but the sequencer still has to put one of them first, and once it has, that choice is written down. Wait, isn't that just the lock again with a nicer name? Somebody still wins on timing. Yes, on timing, but only once. A lock's choice vanishes when the run ends, while the sequencer's choice is a number in a journal that every replica and every auditor reads. Okay, then walk me through 81.

7:59 Marco bids 50 dollars and Priya asks 50, so 100 shares trade and her order leaves the book. Then 82 is Lena. The next seller wants 10 cents more than she'll pay, so nothing trades. Does that make her what you'd call the best bid? Right, that's the highest price any buyer is offering, so she waits on the book. And 83, Priya's cancel, points at an order that no longer exists, so it gets rejected as too late. Okay, but take the other ordering. What if her cancel had been stamped 80, ahead of both buys?

8:34 Then her shares disappear before either buy shows up. Both buyers wait at 50 dollars, Marco first in line, and nothing trades at all. And in that cancel-first world, what if Lena had bid 50 dollars and 5 cents? Then she'd sit ahead of Marco even though she arrived second, because price comes before time. Change what's in the log and you change the winner, and nothing outside the log can change it. I like that a lot. Nobody gets to argue afterward about whose network cable was faster, because the numbered log makes the decision.

9:07 And in our design, whatever reads that numbered log is a single thread. One thread holds the book for a whole group of stocks in memory and applies one numbered message at a time. Hold on, one thread handles every order for all of those stocks? Every one. My instinct was parallelism too, the moment anything gets busy. But matching is sequential by nature. Whether Lena fills depends on whether Marco already took the shares, so a parallel engine ends up taking locks around the best prices anyway. So the single thread makes the winner a property of the log, not of the scheduler.

9:45 But has anyone actually run it that way at real volume? LMAX, a retail financial trading platform, put all of its business logic, every trade from every customer, on one in-memory thread. Martin Fowler, the software design writer, described it in 2011. And it kept up? On Fowler's own numbers, yes. He reported about six million orders per second on a benchmark server from that era. I wouldn't quote that as a number for today, but it's strong evidence that one thread doesn't have to mean slow. Okay, but replay only works if the engine is strictly deterministic.

10:21 For example, no reading the local clock, no random tie-breaks, and no looping over a hash map whose order can change. But then where does a trade's timestamp come from? From the sequencer. In our design, time arrives as a field the sequencer stamps on each message, and the engine never asks the machine what time it is. And I can already hear a platform lead pushing back: we run Postgres for everything, so shard by stock, use serializable transactions, keep synchronous replicas, and ship it. Honestly, that's a serious design, and at modest volume it works.

10:55 It loses here because every order that wants to trade right now fights over the same few rows, so contention sets your speed, and the commit order quietly becomes the tie-break. A replica copies the results the primary committed, but you can't rerun the matching itself to see why one order beat another. Fair. So take a stock that goes wild on a big news day. Can it borrow a second thread? No, and I won't pretend otherwise. One stock tops out at what one core can do. We still shard, just by stock, so different stocks live on different engines, but one stock's book never splits.

11:32 Now the 3rd broken ending we promised. Imagine we let the engine run ahead of the journal. It matches Marco, confirms the trade, publishes it, and then crashes before 81 reached the journal or the standby. So the standby takes over with no idea that 81 ever existed. It still sees Priya's offer resting, and it matches Lena against it... ...and the same hundred shares are now confirmed to two different buyers. Ugh, that's the nightmare version, because both confirmations look completely legitimate.

12:04 How do we close that gap? Order of operations. Each numbered message is written to the journal and copied to the standby before the engine acts on it. Fowler describes LMAX doing that: journaling and replication finish before the business logic ever sees a message. So a confirmation can never get ahead of the record. Which means every order waits on a disk write and a network copy before it can match. For an exchange, I'd pay that every single time. But take the sequencer and the journal themselves.

12:34 They sit on every order's path, so don't they need a standby of their own? They do. I mean, you could replicate that journal with a consensus protocol like Raft, and that's a reasonable choice. Jane Street, the trading firm, wrote in 2017 about a simpler route for its own matching venue: reliable multicast, where every copy hears the same numbered stream. They said it relies on every component being fast and predictable. Now the standby itself. Why not let it read orders straight off the network as they arrive? Then it's always caught up.

13:07 Because that's how you get Marco's orphaned confirmation. Packets aren't guaranteed to arrive in the same order at two different machines, so the sequencer might put Marco first while the standby sees Lena first. Jane Street's 2017 talk says their backup engine listens to the numbered stream instead of the network ports, for that reason. So the standby consumes the numbered messages and computes every fill. Then why doesn't Marco get two confirmations? Because it never sends a thing. It stays silent until it's promoted.

13:36 In Fowler's account, LMAX ran several of these, with every output ignored except the leader's, and when the leader's heartbeat stops, another one takes over. In our design, the old primary also gets fenced off so it can't keep talking. And look what that does to our failures. Same log on both machines means the same answer, and no confirmation can outrun the journal. The orphaned confirmation and the double confirmation are both gone. There's a bonus, too. As that talk puts it, if a regulator asks why a trade happened at a given moment, there's really no uncertainty, because you can replay the day and watch it happen again.

14:13 But that same replay has a dark side, and I have to poke at it. Imagine an order with some odd combination of fields that crashes the engine. If every replica replays the same input, what happens next? Then it crashes the standby too, the moment that order reaches it. So our clever backup protects us from a dead machine, but not from wrong code. Yeah, it's the perfect understudy. It learned every line by heart, including the wrong one. And it'll deliver that wrong line perfectly, on every stage we own.

14:47 The SEC's Facebook order even notes that Nasdaq's failovers were normally identical copies of the same system, the kind of backup you want when the power goes out. So what actually protects us from a bug? Not failover. In our design, three layers do the real work. First, strict validation at the gateway, so a malformed order never even gets a number. Second, if an order still blows up inside the engine, the engine rejects that one message and halts just that stock, and because every replica hits the same message at the same number, they all halt the same way.

15:21 3rd, an operator resumes that stock once the fix is in. Determinism cuts both ways, then. It makes the system auditable, and it also makes a bug perfectly reproducible on every machine we own. So that validation layer lives at the front door. Gateways authenticate each broker, check every field, and enforce price and size limits we'd set per order, before anything reaches the sequencer. And the brokers carry a version of that job too. The SEC's market access rule says brokers that plug straight into an exchange need controls that block orders exceeding credit limits or looking erroneous.

15:58 So say you're a trader who types 100,000 shares instead of 100. Oh, three extra zeros. Right, and at 50 dollars a share, that's one expensive typo. That order can get stopped twice, and it never reaches the matching engine at all. So that covers the way in. On the way out, the engine's results become a public feed, and Nasdaq publishes the spec for its own: every order added, executed, or canceled becomes one message. And everyone gets the same feed? How do you send it to every subscriber without favoring whoever's connection gets served first? With multicast. Nasdaq's spec for delivering that feed says each packet is transmitted once, no matter how many listeners there are.

16:42 So nobody's copy leaves first, which is the fairness requirement from the start. But multicast rides on UDP, so a packet can just get lost on the way, right? Right, so every message carries a sequence number, and a subscriber can spot a gap itself. For instance, if it gets message 10 and then message 13, it knows it's missing two. And then it asks someone to resend just those two? Yep, a re-request server, for just that range. And when the market is quiet, a heartbeat goes out once a second carrying the next expected number.

17:15 Nice. So even the very last message before a lull can't vanish unnoticed. And what about the private confirmations to brokers? Same idea. Jane Street describes retransmitters, servers whose only job is to record every message, and in our design a reconnecting broker replays what it missed from one. So gaps on the feed, subscribers can catch themselves. But suppose a deploy leaves the two engines on slightly different builds, and one quietly drifts by one share. Who notices? Nobody, unless we check.

17:46 In our design, both engines hash their book at the same sequence number every so often, and a monitor compares the two. A mismatch should page whoever's on call right away. And I wouldn't stop at paging. Until we know which copy is wrong, I'd pull the standby out of rotation, because a standby that disagrees is worse than none. Promote it, and you might promote the wrong book. Agreed. And it's the same trick as the feed: compare at the same numbered message, not at a moment in time, or two healthy engines look different just because one is a message behind.

18:21 So here's that first picture again, and I want to walk Marco's order through it. A gateway checks it, it gets stamped 81, and it's journaled and copied before any matching happens. Then the engine fills it against Priya and sends Marco his confirmation. Because 81 was on record first, overselling and double confirmations are already ruled out. Every order paid for that with 1 extra save and one extra copy before matching. Next, 82 puts Lena's bid on the public feed at 50 dollars. 83 bounces Priya's cancel as too late, and a subscriber that dropped a packet asks for exactly the messages it lost.

19:00 And the standby replays the same three numbers and lands on exactly the same book. If the primary died right now, nobody's answer would change. So Marco owns those hundred shares, Lena's bid is waiting at 50, and Priya was too late. One line, one number for every order, and a book that's nothing more than the replay of that line. Thanks for listening to Learning Podcasts.