← Back to all chapters

Chapter 06Down the Rabbit Hole: How Trading Firms Keep C++ Warm for the Moment That Matters

8 min read
rabbit-holecpplow-latencyperformance

I expected a list of C++ tricks: avoid allocations, avoid virtual calls, bypass the kernel. Those are all there. The idea that reorganized it for me was different: the hot path runs about 0.01% of the time, so it is always cold, and some firms run it on fake market data all day, stopping one step short of sending the order. That sounded absurd until I worked through why.

A race measured in microseconds#

On the London Stock Exchange, latency-arbitrage races happen about once a minute per FTSE-100 symbol (Aquilina, Budish and O'Neill).

  • Most common winning margin: 5 to 10 microseconds.
  • Races cover about 20% of volume; the top 6 firms take over 80% of wins and losses.
  • About $5 billion a year is at stake in global equities. Second place by a microsecond gets nothing.

The physics is settled. Chicago to New Jersey is 1139.5 km, a 7.6 ms speed-of-light round trip. Light in fiber is about 1.47x slower than in air (roughly 4.9 µs per km against 3.34), so firms built microwave networks within 1.5% of c. What's left to compete on is inside the box.

Carl Cook (Optiver, CppCon 2017) put a very good wire-to-wire time for software at around 2.5 µs. Compare:

EventTypical cost
Kernel TCP path vs raw ef_vi (vendor slide)+3.9 µs
Context switch3 to 4.5 µs
Waking a core from deep C6 sleepabout 90 µs measured
DRAM miss60 to 100 ns
Branch mispredict16 to 20 cycles, about 5 ns
Exception thrownat least 1.5 µs

One page fault, one deep-sleep exit or one exception costs more than the whole budget. The problem isn't shaving averages, it's removing variance.

  • Good software wire-to-wire (Cook)2.5
  • Exception thrownat least 1.5
  • Kernel TCP vs raw ef_vi+3.9
  • Wake core from deep C6about 90
Single events against the ~2.5 µs wire-to-wire budget (µs).

One packet, end to end#

Say an "Add Order: SELL 500 @ 100.25" arrives, and our strategy buys whenever the best ask is at or below 100.30.

wire --> NIC --DMA--> RX ring (hugepage) --> [hot core 3: busy-poll]
                                               | parse (in place)
                                               | book.apply
                                               | strategy.decide
                                               | risk.check (1 branch)
                                               v
wire <-- NIC <--doorbell-- TX descriptor <-- build order (prealloc)
The path of one market-data message. The hot core never sleeps.
What each stage does so nothing is cold or slow. Click a box.

The risk check is the part I keep thinking about:

uint64_t err = risk.check(o);                 // all checks OR'ed into one flag word
if (!err && !dry_run) [[likely]] tx.send(o);
else if (err) [[unlikely]] [&]() __attribute__((noinline, cold)) { handle(err); }();

Five early-returns would be five data-dependent branches to predict. One branch that is almost always "no error" is predicted perfectly, and the handler is pushed out of line so it doesn't take instruction cache.

check A --fail?--> return      branch 1
check B --fail?--> return      branch 2
check C --fail?--> return      branch 3
check D --fail?--> return      branch 4
check E --fail?--> return      branch 5
send
five data-dependent branches for the predictor to track
Same checks, different branch count (schematic).

The dive's illustrative budget is 300 to 500 ns for NIC and PCIe on each side and 100 to 300 ns of software. Firms don't publish real splits, but the hardware hops dominate.

Why cold code is slow code#

Note the dry_run flag above. Every few microseconds to milliseconds (firms don't publish the interval), the loop feeds a synthetic tick through the whole path with dry_run = true: book, strategy, risk, order building, everything except the doorbell.

The reason is one formula. A path touches M cache lines, each hitting or missing at each level:

T_mem ~= M * (L1 + m1*L2 + m1*m2*L3 + m1*m2*m3*L_DRAM)

Warm, m1 is near zero and a line costs about a nanosecond. After other work evicts everything, the miss rates go to 1 and a line costs closer to 80 ns. An idle path's miss rate drifts toward 1.

The dive's C++ lab (Apple M-series laptop) runs the same function 2000 times after trashing the cache, and 2000 times right after a warm-up call:

cold (after cache trash)     p50= 542 ns  p99=1666 ns  p99.9=1875 ns
warm (after warm-up call)    p50=  84 ns  p99= 208 ns  p99.9= 250 ns

6.5x at the median, 8x at p99, purely from whether data and branch predictor remember the code. The prefetcher hides much of the sequential case, which is why it isn't the full 80x. Warm-up forces m1 to zero right before the first real packet after a quiet period.

  • Cold p50542ns
  • Warm p5084ns
  • Cold p991666ns
  • Warm p99208ns
Same function, lab run on an Apple M-series laptop (ns).

Two other lab results:

  • Two threads incrementing counters on one cache line: 1908 ms. Padded onto separate lines: 82 ms, 23x faster.
One line: 1908 mscounter Acounter Bone linethread 1thread 2each write steals the line from the other corePadded: 82 mscounter Acounter Btwo linesthread 1thread 2no sharing, 23x faster
False sharing: two threads' counters on one 64-byte line fight over ownership; padding gives each its own line. Schematic.
  • Reverse-vector book update: 10.9 ns vs 16.9 ns for std::map, with 90% of updates within 5 ticks of the best price. Make updates uniform across levels and the map catches up. Data skew is why the vector wins.

Tails, not means#

A tick passes through maybe six stages. If each is independently slow 1% of the time:

P(at least one slow stage) = 1 - (1 - p)^N

p = 1%, N = 6 gives 5.9% of ticks. N = 100, like a fan-out service, gives 63%. Every stage's p99 matters.

  • N = 6 stages (a tick)5.9%
  • N = 100 (fan-out service)63%
Share of requests that hit at least one slow stage, when each stage is slow 1% of the time.

Measuring it honestly is harder. Gil Tene's "coordinated omission": if a load tester waits for each reply before sending the next request, then when the system stalls, the tester stops sending and records one slow sample instead of all the ones it should have seen. In his example the true p99.99 was about 582 ms and the reported figure was around 35,000x smaller. Wire taps don't wait, so they don't lie this way.

Where it breaks#

A warm-up path that runs the real code might really send. The "don't send" decision is one runtime flag, and a bug, a refactor, or a reused flag can turn practice orders into real ones.

That has a precedent. On 1 August 2012, Knight Capital deployed new code to 7 of its 8 servers. On the eighth, a reused flag woke old "Power Peg" code whose fill-tracking had been broken by a 2005 refactor nobody retested.

1/4Deploy
servers 1-7: new code
server 8:    old code + reused flag
flag meaning: "inert"  -->  "Power Peg"

New code goes to 7 of 8 servers. The eighth is missed.

Knight Capital, 1 August 2012. Step through.

That wasn't a warm-up bug, but it's the same shape: a flag supposed to mean "this code is inert". The dive's defences are structural: send dry runs to a different sink chosen by type, so there's no flag to get wrong; give practice orders a field the exchange will reject; and keep an independent risk check outside the process that kills the session on anything unexpected.

A quieter C++ trap: reinterpret_cast in the parser

Most codebases do reinterpret_cast<const AddOrder*>(buf)->price. There's no AddOrder object at that address, only bytes, so this is undefined behavior under strict aliasing and object lifetime rules. It works for years because compilers usually emit plain loads, until inlining or LTO gives the optimizer a reason to exploit it. The legal versions are memcpy, std::bit_cast, or C++23's std::start_lifetime_as, and they compile to the same loads.

The open question#

Can a general-purpose CPU ever promise a hard upper bound on this latency? Right now, no. System management interrupts are invisible to the OS and can last milliseconds. Microcode assists, memory refresh and power-state transitions belong to the CPU vendor. Even with every isolation flag set, residual timer interrupts show up. Spikes can be made rare, not bounded.

That's partly why the fastest path left the CPU: an FPGA setup set the STAC-T0 record at 13.9 ns tick-to-trade in 2024. C++ moved up a layer, to the 1 to 10 µs strategy and risk code that tells hardware when to fire. So how much does nanosecond C++ still matter? Budish and others argue the races are an artifact of continuous order books, and frequent batch auctions would make most of this obsolete. I don't know which way it goes, but it's strange to learn a craft whose biggest open question is whether the market should need it.

Sources#

© 2026 Bharat Kaurav. Built with Next.js & Tailwind.

>_ bk@netherwatcheresc to close

Welcome, reader. Type help to see what this shell can do.