System Design

C23

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.

Not startedSaved in this browser only.
  1. 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.
  2. 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.
  3. 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.
  4. 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.
C23
    A

    The prompt

    as the interviewer says it
    "Design an exchange: an order book per symbol, matching in price-time priority, in under a millisecond, never losing an order."
    questionanswer 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.

    B

    Requirements

    as numbers
    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-functionaltarget
    Peak rate≈ 427k orders/s
    Round trip, inside one sitep99 < 1 ms
    Acknowledged orders lost, 1 node down0
    Trades that later vanish0
    Order of matchingThe same on every replica
    Failoverunder 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.

    C

    Estimates

    the arithmetic, on the board
    quantityarithmeticresult
    Average rate10⁹ ÷ 23,400 s≈ 42,700/s
    Peak rate10 × average≈ 427,000/s
    Busiest symbol5% of the peak (a choice)≈ 21,000/s
    Input log10⁹ × 70 B on disk70 GB a day; 210 GB on 3 replicas
    Open orders in memory10,000 × 1,000 × 40 B0.4 GB
    Price ladders10,000 × 2 sides × 20,000 ticks × 16 B6.4 GB
    Market data427k/s × 0.82 updates × 21 B≈ 7.4 MB/s before packet headers
    Fan-out5,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.

    D

    API

    shown as calls; the wire protocol is a binary session over TCP
    callsuccesserrorsretry safe?
    NEW {id, symbol, side, type, price, qty}ack: sequence number, then fillsrefused: limit, collar, credit, bandYes: the id dedupes
    CANCEL {id}canceled: quantity leftrefused: unknown idYes: the second is refused
    fills, on the sessionorder, price, qty, sequence numbernoneReplay from a sequence number
    SUBSCRIBE {symbol}level updates, multicasta jump in sequenceLoad a snapshot
    GET /book/{symbol}/snapshot200 levels at a sequence number404Yes: 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.

    E

    Data model

    the book in memory, and the log on disk
    pricebitqueue, oldest first100.031#3 · 50best ask →100.021#1 · 20#2 · 30100.010100.000best bid →99.991#5 · 1099.981#4 · 4099.970map: order id → node#2 → node in level 100.02A cancel finds the node at once,then unlinks it from the queue.arena of order nodesLinks are array indexes.A free list reuses slots, so thehot path allocates nothing.best price: read one numberadd at a price: array index, then link at the tailnext best price: scan the bitmap, 64 prices per word
    storekeyvalue
    Price ladder, in memoryside, priceQueue head, tail, total
    Order arena, in memoryindexId, account, quantity, links; 40 B
    Order map, in memoryorder idArena index
    Session state, in memoryaccountHighest order id accepted
    Input log, replicatedsequence numberOne command, 34 B plus a record header
    Snapshot filebook, sequence numberEvery order, in queue order
    Trade storebook, sequence number, fillBuyer, 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.

    F

    The architecture

    click a step; its path lights up
    TraderssessionsGatewaysrate limit, riskSequencerone per book groupPrimary matcherone thread per bookStandby 1same log, same bookStandby 2same log, same bookMarket datamulticastTrade storesettlement

    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.

    G

    Capabilities used

    what each part gives you
    toolcapabilitywhat it gives this designalso used for
    MatcherDeterministic state machineThe same log gives the same book on every node.Consensus-replicated services
    MatcherSingle writer per bookNo locks, no contention, and exact order.In-memory databases, counters
    MatcherArray ladder, FIFO lists, arenaConstant-time operations; no garbage on the hot path.Timers, schedulers
    RingsA fixed queue with one reader and one writerThreads hand off work with no lock and no sleep.Log pipelines, packet paths
    SequencerOne total orderTime priority is the sequence number, not a clock.X4
    Raft logCommit on a majority; elect the longest logAn acknowledged order survives 1 node; no split brain.X5
    Segment logSequential appends and fast reads from any offsetReplay and restart from disk.C13
    MulticastThe switch copies one stream to every readerEvery reader sees an update at about the same moment.Market data, cluster discovery
    GatewayToken bucket per sessionA burst costs only the session that sends it.B3
    PostgresUnique keys, transactionsStores 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.

    H

    Deep dive: the book and the match

    data structure, then price-time priority
    book structurestatuscost
    Sorted list of ordersNot approvedA new order walks the list: O(n).
    Heap of ordersNot approvedA cancel in the middle needs a search or a lazy delete.
    Balanced tree of levelsWide price rangeO(log n) per level, with pointer chases.
    Array of levels, FIFO at each, bitmapApprovedO(1); needs a bounded band of ticks.
    Rows in a databaseNot approvedEach match costs a round trip and a lock.
    order typetakes liquiditywhat is left
    LimitUp to its priceRests at its price, last in the queue
    MarketAt any priceIs canceled; it never rests
    CancelNoneRemoves the order; others keep their place
    apply one commandpseudo code
    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
    1. 1A gap in the sequence is a bug, and the engine refuses to continue.
    2. 2The map finds the node; the links remove it. The cost does not depend on queue depth.
    3. 3Ids rise per account, so one number per account stops every retry.
    4. 4Price priority: the walk starts at the best price and stops at the limit.
    5. 5Time priority: the head of the queue, which is the lowest sequence number there.
    6. 6The resting order sets the price, so a crossing order gets the better price.
    7. 7A new order goes last at its price, behind everyone already there.
    Tested source Go: book · Go: match
    Go: bookgo
    
    // 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
    }
    
    Go: matchgo
    
    // 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.

    I

    Deep dive: why one thread

    a lock adds cost and takes away order
    driving one bookorders/srepeatable?
    One thread, no lock8,098,485Yes
    2 threads on one lock5,619,418No
    4 threads on one lock5,363,588No
    8 threads on one lock4,987,803No
    designstatuswhy
    One lock per bookNot approvedSerial work, plus the cost of the lock. Lock order decides priority.
    A lock per price levelNot approvedOne match spans levels, so the locks must nest, and deadlock appears.
    Lock-free bookNot approvedHard to prove, and the result still depends on thread timing.
    One thread per book, a sequenced log in frontApprovedNo shared state; replay gives the same result.
    the threadspseudo code
    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
    1. 1Waking a sleeping thread costs far more than one match, so a busy thread keeps its core.
    2. 2This line is what makes replay exact.
    Tested source Go: digest of the book
    Go: digest of the bookgo
    
    // 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 eachorders/s
    17,934,422
    214,376,420
    424,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.

    J

    Deep dive: the log and the hot standby

    replicate, then act
    ✕ act, then replicate✓ replicate, then actgatewayprimarystandbygatewayprimarystandbyordermatch, publishack✕diestakes overno entryThe client holds an ack for an order nobody has.orderentryheldmatch, publishack✕diestakes overhas the entryNo ack yet? The gateway resends; the id dedupes.
    designacked orders losttrades that vanishedstatus
    act, then replicate856 in 200 of 200 runs308Not approved
    replicate, then act00Approved
    • 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 bystatuscost
    fsync on one diskNot approvedAbout 20 ms on the lab laptop, over the whole budget. The node can still die.
    Asynchronous copy to a standbyNot approvedFast, and it loses the tail.
    Majority of 3 in one siteApprovedOne network round trip. Flush to disk behind it.
    Synchronous copy to a second siteDistance under the budgetLight in fibre costs about 5 µs per km, each way.
    log first, then the bookpseudo code
    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
    1. 1This wait is the price of the guarantee, and it takes most of the budget.
    2. 2A standby never acts on an entry that a new primary might not have.
    3. 3Raft's election rule: a committed entry is on a majority, so the winner has it.
    4. 4Readers keep a cursor. Nobody gets a gap or a duplicate at the failover.
    5. 5A retry of an order that committed changes nothing.
    Tested source Go: apply committed entries · Go: input log and replay
    Go: apply committed entriesgo
    
    // 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
    }
    
    Go: input log and replaygo
    
    // 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 commandstakes
    Replay the whole log from disk8.8 s
    Load a snapshot, replay the last 200,0000.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.

    K

    See it: orders hit a live book

    recorded from the lab engine; both replicas after each step
    step 1 of 15
    sequence
    1
    serving
    primary
    primary
    510f37965484dfa3
    standby
    ✓ same digest
    priceqtyqueue, oldest first
    ask ·100.0220Ana 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.

    L

    Deep dive: the edge

    risk, fairness and market data
    gateway policyquiet p99burst refusedstatus
    One queue, no limit4,119 µs0Not approved
    Round robin per session0 µs0Arrival order changes
    Token bucket per session, then one queue24 µs5,701 of 6,000Approved

    Seeded simulation: 10 sessions, a sequencer of 1 order per µs, one session sending 3 per µs for 2 ms.

    fairness rulewhy
    Every session gets the same limitA published rule, the same for everyone.
    Refuse at the gateway, not in the queueA refused order costs its sender only.
    Equal path from every gateway to the sequencer30 m of extra fibre is about 150 ns, close to a whole match.
    Time priority starts at the sequencerA client's timestamp is a claim, not a fact.
    updates lostsnapshots neededreader's final book
    0%0Exact
    0.1%81Exact
    1%817Exact

    100,000 commands, 0.82 updates per command. A real reader buffers updates during the snapshot; the lab reader loads the newest book.

    gateway, feed, readerpseudo code
    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
    1. 1The refusal is immediate, so the sender can react and the queue stays short.
    2. 2The fat-finger check. It stops an order of 50,000 in the recorded session.
    3. 3A limit far from the last trade is usually a typing error.
    4. 4Reserved before the order runs and released by fills and cancels, read from the matcher's events.
    5. 5The update states the new total, not the change, so a reader can resume from any snapshot.
    6. 6Multicast has no retransmission, so the reader must notice the gap itself.
    Tested source Go: risk · Go: gateway policies · Go: feed and reader
    Go: riskgo
    
    // 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.
      }
    }
    
    Go: gateway policiesgo
    
    // 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
    }
    
    Go: feed and readergo
    
    // 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.

    M

    Deep dive: the latency budget

    spend it before you build
    one order, gateway in to acknowledgement out: 1,000 µs14671Network in, decode, session check100 µs2Risk check10 µs3Sequencer and thread hops40 µs4Log held by a majority: one round trip500 µs5Match10 µs6Publish, network out100 µs7Margin240 µs
    measuredp50p99p99.9
    Match, one command0.2 µs0.4 µs0.6 µs
    Risk, sequence, rings, match, at 200k/s2.4 µs32 µs17.4 ms
    Same path with a log write8.5 µs98 µs16.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.

    N

    Failure cases

    what breaks, and what stays correct
    eventresultwhy it is safesaved by
    The primary dies after an acknowledgementA standby takes over with the same book.A majority held the entry before the acknowledgement.Raft majority
    The primary dies before an acknowledgementThe gateway resends the order.The engine refuses the id if the order did commit.Rising ids
    A standby diesThe 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 primaryIt 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 dieThe symbol halts.The system refuses to guess. Orders resume when a majority returns.Raft quorum
    A bug crashes the matcher on one orderEvery 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 sessionThe gateway refuses the excess.Other sessions see no queue.Token bucket
    A market data packet is lostThe reader sees a jump in the sequence.It loads a snapshot and rejoins the feed.Feed sequence
    A fat-finger orderRefused by risk, or stopped by the collar.It never reaches the log.Risk
    The price moves too far, too fastThe 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
    O

    Scale ladder

    start simple; climb only on a signal
    Each step adds one component1One matcher2+ 2 standbys3+ book groups4+ gateways5+ pinned cores6+ second sitemore load →
    Orders per second against this prompt's demand10k100k1M10M100MDemand: average: 42,735 orders per secondDemand: average42,735Demand: peak: 427,350 orders per secondDemand: peak427,350Replay from the log: 455,288 orders per secondReplay from the log455,2888 threads on a lock: 4,987,803 orders per second8 threads on a lock4,987,803One book, one thread: 8,098,485 orders per secondOne book, one thread8,098,4854 books, 4 threads: 24,064,704 orders per second4 books, 4 threads24,064,704orders per second, log scale
    stepaddit handlesmove up when you see
    1One 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.
    22 hot standbys; commit on a majority.One node can die with no acknowledged order lost.One busy symbol delays another in the same thread.
    3Book 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.
    4More gateways and feed handlers, with equal paths.Thousands of sessions; 5,000 readers on one multicast stream.The p99.9 passes the budget.
    5Pinned cores, kernel bypass on the network card.Removes scheduler stalls and system calls from the path.A whole-site loss must not lose trades.
    6A 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.

    P

    Follow-ups

    what the interviewer asks next
    questionanswerdeeper
    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
    Q

    Drill

    predict, then reveal

    0 of 10 known

    1. Two buy orders arrive at 100.02. Which trades first, and what decides it?

    2. A resting sell sits at 99.97. A buy arrives with a limit of 100.00. At what price do they trade?

    3. Why does the book use an array of price levels and not a balanced tree?

    4. How does a cancel avoid a walk through the queue?

    5. Why does one thread beat several threads on a lock for one book?

    6. What must the matcher not do, so that a standby can replay its log?

    7. The primary acknowledges an order and dies a moment later. When is that safe?

    8. A gateway times out and resends an order that the old primary had already committed. Why is there no second order?

    9. Why do risk checks run before the sequencer and not inside the matcher?

    10. Why do readers get a sequence number on every market data update?

    R

    Numbers to say

    measured, derived or cited
    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.