Stock exchange
A state machine fed by one ordered log. The hard parts: one book's work on one thread, a log that is safe before anyone acts on it, and a fair path.
- 1One thread per book, fed by a sequenced log. The sequence number is the only clock, so time priority is exact and every replica agrees.
- 2The book is an array of price levels with a FIFO queue at each price. Best price, add and cancel are constant time, and the hot path allocates nothing.
- 3Replicate the log to a majority before you act. A hot standby applies the same log and holds the same book, down to queue positions.
- 4Stop bad flow at the edge. Rate limits and risk checks run before the sequencer, so one session cannot slow a symbol for the others.
"Design an exchange: an order book per symbol, matching in price-time priority, in under a millisecond, never losing an order."
| question | answer assumed |
|---|---|
| How many symbols? | 10,000. |
| Which order types? | Limit, market, cancel. Replace is a follow-up. |
| How much flow? | 1 billion orders and cancels in a 6.5 hour session. |
| What is the peak? | 10× the average at the open and the close. |
| What does under a millisecond cover? | Gateway in to acknowledgement out, inside one site. |
| What does never losing mean? | No acknowledged order or trade is lost when 1 node dies. |
| Who settles trades? | A separate system, fed by the trade events. |
I clarify the order types, the latency target, and what never losing an order means, because the last one decides when I can acknowledge.
| functional |
|---|
| Accept limit and market orders; cancel a resting order. |
| Match each symbol in price-time priority. |
| Report every fill to both sides. |
| Publish the book's changes to every reader. |
| Refuse orders that break a risk limit. |
| non-functional | target |
|---|---|
| Peak rate | ≈ 427k orders/s |
| Round trip, inside one site | p99 < 1 ms |
| Acknowledged orders lost, 1 node down | 0 |
| Trades that later vanish | 0 |
| Order of matching | The same on every replica |
| Failover | under 1 s, no operator |
An acknowledgement means a majority holds the order. Everything else in the design follows from that sentence and the order of the log.
| quantity | arithmetic | result |
|---|---|---|
| Average rate | 10⁹ ÷ 23,400 s | ≈ 42,700/s |
| Peak rate | 10 × average | ≈ 427,000/s |
| Busiest symbol | 5% of the peak (a choice) | ≈ 21,000/s |
| Input log | 10⁹ × 70 B on disk | 70 GB a day; 210 GB on 3 replicas |
| Open orders in memory | 10,000 × 1,000 × 40 B | 0.4 GB |
| Price ladders | 10,000 × 2 sides × 20,000 ticks × 16 B | 6.4 GB |
| Market data | 427k/s × 0.82 updates × 21 B | ≈ 7.4 MB/s before packet headers |
| Fan-out | 5,000 readers × 7.4 MB/s, one stream each | ≈ 37 GB/s; multicast sends 1 stream |
Inputs are the assumed answers in panel A. Log, order and level sizes and updates per command were measured in the lab. Method: R2.
The peak is about 427 thousand orders a second, and one laptop thread matches 8.1 million a second. Capacity is not the problem; latency, order and safety are.
| call | success | errors | retry safe? |
|---|---|---|---|
| NEW {id, symbol, side, type, price, qty} | ack: sequence number, then fills | refused: limit, collar, credit, band | Yes: the id dedupes |
| CANCEL {id} | canceled: quantity left | refused: unknown id | Yes: the second is refused |
| fills, on the session | order, price, qty, sequence number | none | Replay from a sequence number |
| SUBSCRIBE {symbol} | level updates, multicast | a jump in sequence | Load a snapshot |
| GET /book/{symbol}/snapshot | 200 levels at a sequence number | 404 | Yes: a read |
- An acknowledgement returns the sequence number, so a client can match its fills to the public feed.
- A session has its own rate limit. The limit is part of the contract, not a surprise under load.
Every order carries an id that rises per account. Sending it twice is safe, and the acknowledgement means a majority holds it.
| store | key | value |
|---|---|---|
| Price ladder, in memory | side, price | Queue head, tail, total |
| Order arena, in memory | index | Id, account, quantity, links; 40 B |
| Order map, in memory | order id | Arena index |
| Session state, in memory | account | Highest order id accepted |
| Input log, replicated | sequence number | One command, 34 B plus a record header |
| Snapshot file | book, sequence number | Every order, in queue order |
| Trade store | book, sequence number, fill | Buyer, seller, price, quantity |
- The order map, the arena and the ladder live only in memory. The log rebuilds them.
- Prices are integer ticks and quantities are integers. A float never touches the book.
The log is the truth and the book is a view of it. Any node can rebuild the book by replaying from a snapshot.
Step 1: Gateway
- Each trader holds a session on one gateway.
- The gateway decodes the order, charges a token, and runs the risk checks.
- A refusal goes back at once. It never reaches the log.
If it fails
A gateway dies: the session reconnects to another gateway and resends every order with no acknowledgement. The order id dedupes them.
Gateways filter, one sequencer orders, a majority stores, one thread matches, and standbys apply the same log in step.
| tool | capability | what it gives this design | also used for |
|---|---|---|---|
| Matcher | Deterministic state machine | The same log gives the same book on every node. | Consensus-replicated services |
| Matcher | Single writer per book | No locks, no contention, and exact order. | In-memory databases, counters |
| Matcher | Array ladder, FIFO lists, arena | Constant-time operations; no garbage on the hot path. | Timers, schedulers |
| Rings | A fixed queue with one reader and one writer | Threads hand off work with no lock and no sleep. | Log pipelines, packet paths |
| Sequencer | One total order | Time priority is the sequence number, not a clock. | X4 |
| Raft log | Commit on a majority; elect the longest log | An acknowledged order survives 1 node; no split brain. | X5 |
| Segment log | Sequential appends and fast reads from any offset | Replay and restart from disk. | C13 |
| Multicast | The switch copies one stream to every reader | Every reader sees an update at about the same moment. | Market data, cluster discovery |
| Gateway | Token bucket per session | A burst costs only the session that sends it. | B3 |
| Postgres | Unique keys, transactions | Stores each trade once for settlement, off the hot path. | T9 |
A sequenced log gives me order and replay. A majority gives me durability inside the latency budget. A single writer gives me speed with no locks.
| book structure | status | cost |
|---|---|---|
| Sorted list of orders | Not approved | A new order walks the list: O(n). |
| Heap of orders | Not approved | A cancel in the middle needs a search or a lazy delete. |
| Balanced tree of levels | Wide price range | O(log n) per level, with pointer chases. |
| Array of levels, FIFO at each, bitmap | Approved | O(1); needs a bounded band of ticks. |
| Rows in a database | Not approved | Each match costs a round trip and a lock. |
| order type | takes liquidity | what is left |
|---|---|---|
| Limit | Up to its price | Rests at its price, last in the queue |
| Market | At any price | Is canceled; it never rests |
| Cancel | None | Removes the order; others keep their place |
apply(command): // one thread per book
seq = seq + 11
IF cancel: unlink the node by id2; RETURN
IF limit outside the band or id repeats3: refuse
WHILE qty > 0 AND best opposite price crosses4:
maker = oldest order at that price5
fill = min(qty, maker.qty)
emit trade(fill, maker.price6)
IF maker is empty: unlink it
IF qty > 0 AND limit: append at the tail of its price7
IF qty > 0 AND market: cancel the rest- 1A gap in the sequence is a bug, and the engine refuses to continue.
- 2The map finds the node; the links remove it. The cost does not depend on queue depth.
- 3Ids rise per account, so one number per account stops every retry.
- 4Price priority: the walk starts at the best price and stops at the limit.
- 5Time priority: the head of the queue, which is the lowest sequence number there.
- 6The resting order sets the price, so a crossing order gets the better price.
- 7A new order goes last at its price, behind everyone already there.
Tested source Go: book · Go: match
// order is one resting order, in a fixed arena. Links are arena indexes, so the queue at a price
// is a doubly linked list that the garbage collector never has to walk.
type order struct {
id uint64
qty int64
account uint32
price int32
prev, next int32
side Side
}
// level is the FIFO queue at one price.
type level struct {
head, tail int32
total int64
}
// ladder is one side of the book: one level per tick in the band, a bitmap of non-empty levels,
// and the best price. Best price, add and remove are O(1); the next best price scans the bitmap.
type ladder struct {
levels []level
bits []uint64
best int32 // none when empty
}
// Engine is the book of one symbol. Only one goroutine ever touches it.
type Engine struct {
seq uint64
ticks int32
sides [2]ladder
orders []order
free int32
byID map[uint64]int32 // resting order id -> arena index
last map[uint32]uint64 // account -> highest order id accepted; ids rise per account
}
// Apply runs one command and appends its events to out. It reads nothing but the command and the
// book, so a replica that applies the same log holds the same book.
func (e *Engine) Apply(c Command, out []Event) ([]Event, error) {
if c.Seq != e.seq+1 {
return out, fmt.Errorf("%w: got %d after %d", ErrSequence, c.Seq, e.seq)
}
e.seq = c.Seq
if c.Kind == Cancel {
return e.cancel(c, out), nil
}
if reason := e.validate(c); reason != NoReason {
return append(out, Event{Seq: c.Seq, Kind: Rejected, Side: c.Side, Reason: reason, ID: c.ID, Qty: c.Qty}), nil
}
e.last[c.Account] = c.ID
left, out := e.match(c, c.Qty, out)
switch {
case left == 0:
case c.Kind == Market:
out = append(out, Event{Seq: c.Seq, Kind: Canceled, Side: c.Side, ID: c.ID, Price: none, Qty: left}) // never rests
default:
e.push(order{id: c.ID, qty: left, account: c.Account, price: c.Price, side: c.Side})
out = append(out, Event{Seq: c.Seq, Kind: Rested, Side: c.Side, ID: c.ID, Price: c.Price, Qty: left})
}
return out, nil
}
// match walks the opposite side from its best price. At each price it takes the oldest order
// first, and every trade prints at the resting order's price.
func (e *Engine) match(c Command, left int64, out []Event) (int64, []Event) {
opp := &e.sides[1-c.Side]
for left > 0 && opp.best != none {
p := opp.best
if c.Kind == Limit && ((c.Side == Buy && p > c.Price) || (c.Side == Sell && p < c.Price)) {
break // the best resting price is worse than this order's limit
}
l := &opp.levels[p]
for left > 0 && l.head != none {
i := l.head
m := &e.orders[i]
q := min(left, m.qty)
left -= q
out = append(out, Event{Seq: c.Seq, Kind: Trade, Side: c.Side, ID: c.ID, Maker: m.id, Price: p, Qty: q})
if q == m.qty {
e.unlink(i) // also moves opp.best when the level empties
continue
}
m.qty -= q
l.total -= q
}
}
return left, out
}
Tested on 40 seeded flows of 3,000 commands against a slow reference book. Each trade hits the order that priority picks, and the book is never crossed. Every share is filled, resting or canceled. The checks also refuse streams from deliberately broken matchers.
Best price, add and cancel are constant time. In the lab, one match took a median 167 ns and allocated nothing.
| driving one book | orders/s | repeatable? |
|---|---|---|
| One thread, no lock | 8,098,485 | Yes |
| 2 threads on one lock | 5,619,418 | No |
| 4 threads on one lock | 5,363,588 | No |
| 8 threads on one lock | 4,987,803 | No |
| design | status | why |
|---|---|---|
| One lock per book | Not approved | Serial work, plus the cost of the lock. Lock order decides priority. |
| A lock per price level | Not approved | One match spans levels, so the locks must nest, and deadlock appears. |
| Lock-free book | Not approved | Hard to prove, and the result still depends on thread timing. |
| One thread per book, a sequenced log in front | Approved | No shared state; replay gives the same result. |
gateways -> ring -> sequencer -> log -> ring -> matcher
-> feed
matcher thread:
LOOP:
command = next from the ring // spin, never sleep1
events = apply(command) // no locks, no clock, no random2
publish events- 1Waking a sleeping thread costs far more than one match, so a busy thread keeps its core.
- 2This line is what makes replay exact.
Tested source Go: digest of the book
// Digest hashes the sequence number, every resting order in price and time order, and the highest
// id per account. Two engines with the same digest hold the same book, queue positions included.
func (e *Engine) Digest() uint64 {
h := fnv.New64a()
var b [8]byte
put := func(v uint64) {
for i := range b {
b[i] = byte(v >> (8 * i))
}
h.Write(b[:]) // a hash write cannot fail
}
put(e.seq)
for _, s := range []Side{Buy, Sell} {
for _, l := range e.Depth(s) {
put(uint64(l.Price))
for _, o := range l.Orders {
put(o.ID)
put(uint64(o.Account))
put(uint64(o.Qty))
}
}
put(^uint64(0))
}
for _, a := range slices.Sorted(maps.Keys(e.last)) {
put(uint64(a))
put(e.last[a])
}
return h.Sum64()
}
| books, one thread each | orders/s |
|---|---|
| 1 | 7,934,422 |
| 2 | 14,376,420 |
| 4 | 24,064,704 |
Separate books share nothing, so they scale with cores. Scale comes from more books, not from more threads on one book.
One book is serial work. A lock on it gave 62% of one thread's rate at 8 threads, and racing threads end in a different book each run.
| design | acked orders lost | trades that vanished | status |
|---|---|---|---|
| act, then replicate | 856 in 200 of 200 runs | 308 | Not approved |
| replicate, then act | 0 | 0 | Approved |
- Each run streams 1,200 commands into 3 Raft replicas, each with an engine, and kills the primary.
- The gateway resent 1,804 orders in total. The engine refused 600 as duplicates and applied the rest once.
- Every node ended with the same digest and the same event history, and the feed carried each sequence number once.
- The order flow stalled for a median 216 ms with election timeouts of 150 to 300 ms. Tune those timeouts down in one site.
| make an entry safe by | status | cost |
|---|---|---|
| fsync on one disk | Not approved | About 20 ms on the lab laptop, over the whole budget. The node can still die. |
| Asynchronous copy to a standby | Not approved | Fast, and it loses the tail. |
| Majority of 3 in one site | Approved | One network round trip. Flush to disk behind it. |
| Synchronous copy to a second site | Distance under the budget | Light in fibre costs about 5 µs per km, each way. |
primary, for each command:
append it to the log, send it to the standbys
wait until a majority holds it1
apply it to the book, publish, acknowledge
standby, for each entry:
append it, confirm to the primary
apply it once the primary says it is committed2
on primary death:
the majority elects the standby with the longest log3
new primary applies the rest of the committed entries
publish from the feed's last sequence number + 14
gateways resend every order with no acknowledgement
the engine refuses ids it has already seen5- 1This wait is the price of the guarantee, and it takes most of the budget.
- 2A standby never acts on an entry that a new primary might not have.
- 3Raft's election rule: a committed entry is on a majority, so the winner has it.
- 4Readers keep a cursor. Nobody gets a gap or a duplicate at the failover.
- 5A retry of an order that committed changes nothing.
Tested source Go: apply committed entries · Go: input log and replay
// pump applies newly safe log entries on every running node. A node applies an entry only once a
// majority holds it. The sequence number is the position among real commands, so every node
// derives the same one. In the ActFirst design the primary skips that wait.
func pump(c *consensus.Cluster, nodes []*replica, actFirst bool, onApply func(node int, cmd Command, evs []Event)) error {
for i, r := range nodes {
if !c.Up(i) {
continue
}
nd := c.Nodes[i]
safe := nd.Commit
if actFirst && c.Leader() == i {
safe = len(nd.Log)
}
for ; r.applied < safe; r.applied++ {
cmd := nd.Log[r.applied].Cmd
if cmd == "no-op" {
continue
}
cm, err := Decode([]byte(cmd))
if err != nil {
return fmt.Errorf("node %d entry %d: %w", i, r.applied, err)
}
cm.Seq = r.eng.Seq() + 1
first := len(r.events)
if r.events, err = r.eng.Apply(cm, r.events); err != nil {
return fmt.Errorf("node %d entry %d: %w", i, r.applied, err)
}
r.cmds = append(r.cmds, cm)
onApply(i, cm, r.events[first:])
}
}
return nil
}
// Journal is the input log of one symbol on disk: the segment log of the message queue sheet,
// with one record per command. Log offset = Seq - 1.
type Journal struct {
log *mqueue.Log
}
// OpenJournal opens or creates a journal in dir.
func OpenJournal(dir string, sync bool) (*Journal, error) {
l, err := mqueue.Open(dir, mqueue.Options{SegmentBytes: 64 << 20, IndexEvery: 4096, Sync: sync})
if err != nil {
return nil, fmt.Errorf("open journal: %w", err)
}
return &Journal{log: l}, nil
}
// Append writes a batch with one write call.
func (j *Journal) Append(cmds []Command) error {
recs := make([]mqueue.Record, len(cmds))
for i, c := range cmds {
recs[i] = mqueue.Record{Offset: -1, Seq: -1, Value: Encode(make([]byte, 0, CommandBytes), c)}
}
if _, err := j.log.Append(recs); err != nil {
return fmt.Errorf("journal append: %w", err)
}
return nil
}
// Replay feeds every command after seq to fn, in log order.
func (j *Journal) Replay(seq uint64, fn func(Command) error) error {
for from := int64(seq); from < j.log.LEO(); {
recs, _, err := j.log.Read(from, 4096)
if err != nil {
return fmt.Errorf("journal read at %d: %w", from, err)
}
if len(recs) == 0 {
return fmt.Errorf("journal read at %d: no records before the end at %d", from, j.log.LEO())
}
for _, r := range recs {
c, err := Decode(r.Value)
if err != nil {
return fmt.Errorf("journal offset %d: %w", r.Offset, err)
}
if err := fn(c); err != nil {
return fmt.Errorf("journal offset %d: %w", r.Offset, err)
}
}
from = recs[len(recs)-1].Offset + 1
}
return nil
}
| rebuild 4,000,000 commands | takes |
|---|---|
| Replay the whole log from disk | 8.8 s |
| Load a snapshot, replay the last 200,000 | 0.1 s |
Replay read 455,288 commands a second from the log files. The read path sets that limit, not the matcher. In the replay test, a second engine matched the first at every checkpoint of 200,000 commands.
I acknowledge after a majority holds the entry. Across 200 lab failovers that lost 0 of 240,000 acknowledged orders. Acting first lost 856.
- sequence
- 1
- serving
- primary
- primary
- 510f37965484dfa3
- standby
- ✓ same digest
| price | qty | queue, oldest first | |
|---|---|---|---|
| ask · | 100.02 | 20 | Ana 20 |
| one side empty | |||
Trades from this order
none
Market data sent
- #1 sell 100.02 now 20
Each frame is the engine's state after one command. The primary and the standby applied the same log, and the digest covers every order and its queue position.
Gus's buy hits Ana first because she came first at that price. The standby takes over with the same book, and the next order trades on it.
| gateway policy | quiet p99 | burst refused | status |
|---|---|---|---|
| One queue, no limit | 4,119 µs | 0 | Not approved |
| Round robin per session | 0 µs | 0 | Arrival order changes |
| Token bucket per session, then one queue | 24 µs | 5,701 of 6,000 | Approved |
Seeded simulation: 10 sessions, a sequencer of 1 order per µs, one session sending 3 per µs for 2 ms.
| fairness rule | why |
|---|---|
| Every session gets the same limit | A published rule, the same for everyone. |
| Refuse at the gateway, not in the queue | A refused order costs its sender only. |
| Equal path from every gateway to the sequencer | 30 m of extra fibre is about 150 ns, close to a whole match. |
| Time priority starts at the sequencer | A client's timestamp is a claim, not a fact. |
| updates lost | snapshots needed | reader's final book |
|---|---|---|
| 0% | 0 | Exact |
| 0.1% | 81 | Exact |
| 1% | 817 | Exact |
100,000 commands, 0.82 updates per command. A real reader buffers updates during the snapshot; the lab reader loads the newest book.
gateway, for each order:
take a token for this session, else refuse now1
IF qty > max order: refuse2 // fat finger
IF price outside the collar: refuse3
IF used credit + price × qty > limit: refuse
reserve the credit4, pass the order to the sequencer
feed, after each command:
FOR EACH price that changed:
send (feed seq, side, price, new total)5
reader, for each update:
IF seq jumps: load a snapshot6, carry on from it- 1The refusal is immediate, so the sender can react and the queue stays short.
- 2The fat-finger check. It stops an order of 50,000 in the recorded session.
- 3A limit far from the last trade is usually a typing error.
- 4Reserved before the order runs and released by fills and cancels, read from the matcher's events.
- 5The update states the new total, not the change, so a reader can resume from any snapshot.
- 6Multicast has no retransmission, so the reader must notice the gap itself.
Tested source Go: risk · Go: gateway policies · Go: feed and reader
// Risk runs before the sequencer, so a refused order never reaches the log or the matcher. It
// reserves credit when an order passes and releases it from the matcher's events.
type Risk struct {
lim Limits
ref int32 // the last trade price
open map[uint64]working
used map[uint32]int64
}
// NewRisk starts with ref as the reference price.
func NewRisk(lim Limits, ref int32) *Risk {
return &Risk{lim: lim, ref: ref, open: map[uint64]working{}, used: map[uint32]int64{}}
}
// Check returns NoReason and reserves credit, or the reason the order is refused.
func (r *Risk) Check(c Command) Reason {
if c.Kind == Cancel {
return NoReason
}
if c.Qty > r.lim.MaxQty {
return OverLimit
}
price := c.Price
if c.Kind == Market {
price = r.ref + r.lim.Collar // a market order may trade up to the collar: reserve the worst case
} else if d := c.Price - r.ref; d > r.lim.Collar || d < -r.lim.Collar {
return OutsideCollar
}
cost := int64(price) * c.Qty
if r.used[c.Account]+cost > r.lim.Credit {
return OverCredit
}
r.used[c.Account] += cost
r.open[c.ID] = working{c.Account, price, c.Qty}
return NoReason
}
// Observe releases credit for one matcher event.
func (r *Risk) Observe(e Event) {
switch e.Kind {
case Trade:
r.ref = e.Price
r.release(e.ID, e.Qty)
r.release(e.Maker, e.Qty)
case Canceled:
r.release(e.ID, e.Qty)
case Rejected:
if w, ok := r.open[e.ID]; ok {
r.release(e.ID, w.qty)
}
case Rested:
// Still working: the credit stays reserved.
}
}
// RunFair replays one traffic pattern through a policy. The refusal happens at the gateway, in
// front of the sequencer, so one session's burst costs only that session.
func RunFair(cfg FairConfig, policy string) (FairResult, error) {
queues := make([][]arrival, cfg.Sessions)
tokens := make([]int, cfg.Sessions)
for i := range tokens {
tokens[i] = cfg.Depth
}
res := FairResult{Policy: policy}
var quiet, busy []int
turn := 0
queued := func() int {
n := 0
for _, q := range queues {
n += len(q)
}
return n
}
offer := func(s, now int) {
if s == 0 {
res.BusySent++
}
if policy == PolicyBucket {
if tokens[s] == 0 {
if s == 0 {
res.BusyRefused++
}
return
}
tokens[s]--
}
if policy == PolicyRoundRobin {
queues[s] = append(queues[s], arrival{s, now})
} else {
queues[0] = append(queues[0], arrival{s, now}) // one shared queue, in arrival order
}
}
switch policy {
case PolicyFIFO, PolicyBucket, PolicyRoundRobin:
default:
return res, fmt.Errorf("unknown policy %q", policy)
}
for now := 0; now < cfg.Horizon || queued() > 0; now++ {
if now%cfg.RefillEvery == 0 {
for i := range tokens {
tokens[i] = min(tokens[i]+1, cfg.Depth)
}
}
if now < cfg.Horizon {
for s := 1; s < cfg.Sessions; s++ {
if (now+s*7)%cfg.QuietEvery == 0 {
offer(s, now)
}
}
if now < cfg.BurstUS {
for range cfg.Burst {
offer(0, now)
}
}
}
for range cfg.Capacity {
var a arrival
if policy == PolicyRoundRobin {
i := 0
for i < cfg.Sessions && len(queues[turn]) == 0 {
turn = (turn + 1) % cfg.Sessions
i++
}
if i == cfg.Sessions {
break
}
a, queues[turn] = queues[turn][0], queues[turn][1:]
turn = (turn + 1) % cfg.Sessions
} else {
if len(queues[0]) == 0 {
break
}
a, queues[0] = queues[0][0], queues[0][1:]
}
if a.session == 0 {
busy = append(busy, now-a.at)
} else {
quiet = append(quiet, now-a.at)
}
}
}
slices.Sort(quiet)
slices.Sort(busy)
if len(quiet) == 0 || len(busy) == 0 {
return res, fmt.Errorf("policy %s: no traffic served", policy)
}
res.QuietP50US = quiet[len(quiet)/2]
res.QuietP99US = quiet[len(quiet)*99/100]
res.QuietMaxUS = quiet[len(quiet)-1]
res.BusyMaxUS = busy[len(busy)-1]
return res, nil
}
// Publish appends one update per price that changed, after a batch of events.
func (p *Publisher) Publish(evs []Event, out []Update) []Update {
start := len(out)
add := func(s Side, price int32) {
for _, u := range out[start:] {
if u.Side == s && u.Price == price {
return // this command already reported that level
}
}
p.seq++
out = append(out, Update{p.seq, s, price, p.e.sides[s].levels[price].total})
}
for _, ev := range evs {
switch {
case ev.Kind == Trade:
add(1-ev.Side, ev.Price)
case ev.Kind == Rested, ev.Kind == Canceled && ev.Price != none:
add(ev.Side, ev.Price)
}
}
return out
}
// On handles one update. A jump in the sequence means a lost packet: the reader discards its
// copy, loads a snapshot and carries on from it.
func (s *Subscriber) On(u Update, snapshot func() BookView) {
switch {
case u.Seq > s.view.Seq+1, u.Price == none && u.Seq > s.view.Seq:
s.Gaps++
s.view = snapshot()
case u.Seq == s.view.Seq+1:
s.view.Seq = u.Seq
if u.Total == 0 {
delete(s.view.Levels[u.Side], u.Price)
} else {
s.view.Levels[u.Side][u.Price] = u.Total
}
}
}
A per-session limit in the gateway keeps a quiet session's p99 wait at 24 µs during another session's burst. With no limit it was 4,119 µs.
| measured | p50 | p99 | p99.9 |
|---|---|---|---|
| Match, one command | 0.2 µs | 0.4 µs | 0.6 µs |
| Risk, sequence, rings, match, at 200k/s | 2.4 µs | 32 µs | 17.4 ms |
| Same path with a log write | 8.5 µs | 98 µs | 16.6 ms |
- The budgets are design choices to load test. The measured rows show one laptop, not a site.
- The match time includes 2 clock reads, about 26 ns.
- A thread that only read the clock saw 24 gaps over 1 ms in 5 s, up to 10.3 ms. The laptop's scheduler sets the far tail of the path.
- A site pins each thread to a core, keeps other work off that core, and reads packets directly from the network card.
- The p99.9 is the number to defend. An average hides a stall that a trader sees.
Replication takes half of the millisecond, and matching took 0.4 µs at p99. A faster book buys little; a quieter path buys a lot.
| event | result | why it is safe | saved by |
|---|---|---|---|
| The primary dies after an acknowledgement | A standby takes over with the same book. | A majority held the entry before the acknowledgement. | Raft majority |
| The primary dies before an acknowledgement | The gateway resends the order. | The engine refuses the id if the order did commit. | Rising ids |
| A standby dies | The other standby makes the majority. | The dead node replays from a snapshot and the log when it returns. | Snapshot, log |
| A partition cuts off the primary | It cannot reach a majority, so it stops acknowledging. | The majority side elects a new primary. Only one side can commit. | Raft quorum |
| Two of 3 replicas die | The symbol halts. | The system refuses to guess. Orders resume when a majority returns. | Raft quorum |
| A bug crashes the matcher on one order | Every replica crashes on the same entry. | Replicas protect against machines, not logic. Halt the symbol and replay on a fix. | Halt, replay |
| A trader floods a session | The gateway refuses the excess. | Other sessions see no queue. | Token bucket |
| A market data packet is lost | The reader sees a jump in the sequence. | It loads a snapshot and rejoins the feed. | Feed sequence |
| A fat-finger order | Refused by risk, or stopped by the collar. | It never reaches the log. | Risk |
| The price moves too far, too fast | The symbol halts; orders collect for an auction. | A halt is an entry in the log, so every replica halts at the same place. | Log entry |
| step | add | it handles | move up when you see |
|---|---|---|---|
| 1 | One matcher thread and a log on disk. | About 8.1 million orders a second on a laptop core. | A node failure would stop trading or lose the tail. |
| 2 | 2 hot standbys; commit on a majority. | One node can die with no acknowledged order lost. | One busy symbol delays another in the same thread. |
| 3 | Book groups: about 16 threads, a log per group. | A busy symbol delays only its own group. Orders never cross books. | Sessions or readers pass what one gateway or feed holds. |
| 4 | More gateways and feed handlers, with equal paths. | Thousands of sessions; 5,000 readers on one multicast stream. | The p99.9 passes the budget. |
| 5 | Pinned cores, kernel bypass on the network card. | Removes scheduler stalls and system calls from the path. | A whole-site loss must not lose trades. |
| 6 | A second site: an asynchronous log copy, or synchronous if close. | A site can fail. An asynchronous copy can lose the last entries. | Top of the ladder. |
Demand from panel C. Rates are single-process lab runs of 4,000,000 commands, median of 3, on a shared 8-core laptop. Read them as orders of magnitude.
One thread holds this prompt's peak many times over. I add standbys for safety, more book groups for isolation, and a quieter path for the tail.
| question | answer | deeper |
|---|---|---|
| How does the standby become primary without split brain? | Raft needs a majority to win an election and to commit. A cut-off old primary cannot commit, so its work never counts. | X5 |
| How fast can you detect a dead primary? | Heartbeats and a timeout set the delay. The X5 lab elected in a median 157 ms with timeouts of 150 to 300 ms; one site can use far lower timeouts. | X6 |
| Why not put the input log on the message queue from C13? | Use the same shape: a replicated, ordered log. An exchange tunes it for microseconds and keeps it inside the matcher group. | C13 |
| Why not use wall clocks for time priority? | Two gateways never agree to the nanosecond, and a clock can step back. One sequencer gives one order, with no agreement needed. | X4 |
| How do you settle trades exactly once? | Each fill has a key from its sequence number and fill number. A ledger inserts it with a unique constraint, so a replay posts nothing new. | T9 |
| How do you add replace, stop or iceberg orders? | Each one is a new command the state machine handles. Keep them deterministic; a stop order fires on the sequence number of a trade, not on a timer. | X5 |
| What happens if a replica's state drifts from the others? | Compare digests at fixed sequence numbers. A mismatch shows a bug or bad memory, so restart that replica from a snapshot. | X1 |
| How do you size the gateway limits? | Publish a rate per session, and use a token bucket so a short burst passes. Measure the sequencer's rate first. | B3 |
0 of 10 known
Two buy orders arrive at 100.02. Which trades first, and what decides it?
A resting sell sits at 99.97. A buy arrives with a limit of 100.00. At what price do they trade?
Why does the book use an array of price levels and not a balanced tree?
How does a cancel avoid a walk through the queue?
Why does one thread beat several threads on a lock for one book?
What must the matcher not do, so that a standby can replay its log?
The primary acknowledges an order and dies a moment later. When is that safe?
A gateway times out and resends an order that the old primary had already committed. Why is there no second order?
Why do risk checks run before the sequencer and not inside the matcher?
Why do readers get a sequence number on every market data update?
- demand
- About 427 thousand orders a second at peak; 70 GB of log a day.
- match
- 8.1 million orders a second on one thread; p50 167 ns, p99 440 ns.
- lock
- 8 threads on one lock: 62% of one thread, and no repeatable order.
- allocations
- 0 per command after warm-up.
- safety
- 0 of 240,000 acknowledged orders lost when replicating first; 856 when acting first.
- replay
- 455 thousand commands a second from disk.
- order
- 40 B in memory, 34 B in a log entry, 21 B on the feed.
- fibre
- About 5 µs per km, derived from the speed of light in glass.
Go on an 8-core laptop shared with other jobs, no pinned cores. Failover and gateway runs are seeded and repeat exactly.