Design a stock exchange
hard 60 minPair buyers with sellers by one strict rule, in microseconds, without ever losing an accepted order.
See it run
Follow one order from the broker to the book, match it by hand, publish the trade, and lose a machine without losing an order.
Operations
Place an order
Check, number, journal, match, report. The order of these five is the design.
Step 1 of 10
The broker sends
order
buy 100 at 150.00
id
c-7781
Buy 100 TOYS at 150.00, with client order ID c-7781. Why: the ID makes a retry harmless.
Step 1: The broker sends
def on_order(msg, session): firm = session.firm # never from the message if not limits.reserve(firm, msg): # size, price band, budget return reject("limit") seq = sequencer.next(firm, msg.client_id) # same ID, same number journal.append(seq, msg) # wait for 2 of 3 copies report(firm, "accepted", seq) for fill in engine.apply(seq, msg): # one thread report_both_sides(fill) feed.publish(fill)- Time
- 75 µs budget
- Cost
- 200 B journaled
- Average
- 214K/s
- Peak (3x)
- 641K/s
Accepted means a majority of journals has it. Filled comes later, perhaps hours later.
In the real world
The same stock exchange doing real jobs. Pick one and step through it.
1,500.00 instead of 150.00, for a million shares.
Step 1 of 4
It arrives
price
1,500.00
shares
1,000,000
The format is valid, so parsing does not help.
Step 1: It arrives
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Sorting by server time
criticalClocks differ, and an earlier order may still be on its way.
Wrongorders.sort(key=lambda o: o.gateway_time)Rightengine.apply(sequencer.next(order))Reporting before the journal
criticalA crash then loses an order the client was told about.
Wrongfills = engine.apply(order)report(fills); journal.append(order)Rightjournal.append(seq, order) # majorityreport(engine.apply(seq, order))Floating-point prices
majorEqual prices may not compare equal, so levels split.
Wrongprice = 0.1 + 0.2Rightprice_ticks = 30 # tick 0.01Two voters
criticalLosing one leaves no majority. Ignoring that gives two leaders.
Wrongvoters = [primary, standby]Rightvoters = [a, b, c]A clock inside the engine
majorReplay happens later, so it takes another branch.
Wrongif time.now() > order.expires: cancel()Rightif event.time > order.expires: cancel()
Interview tips
Define fair first
- Arrival is the sequencer's number.
- Same rules and path in each tier.
- Distance is a policy question.
Split latency from rate
- 75 µs through the pipe.
- 5 µs on the slowest thread.
- Half busy, or queues grow.
Make replay true
- No clocks, no random, no calls.
- Checksums between leader and standby.
- Halts are events too.
Stay in scope
- Brokers own customers.
- A clearing house settles.
- Teach the system, not trading.