5 min read

Low-latency C++ patterns, and what survives the move to TypeScript

Notes on Bilokon and Gunduz's paper on C++ design patterns for HFT, read from the V8 side: which techniques have a real equivalent in TypeScript, which are replaced by something else, and which do not exist.


Paul Bilokon and Burak Gunduz's paper C++ Design Patterns for Low-latency Applications Including High-frequency Trading does three things: it collects low-latency programming techniques into a benchmarked repository, applies them to a statistical-arbitrage pairs strategy, and implements the LMAX Disruptor in C++ as the messaging layer of an order management system.

Nobody builds a tick-to-trade path in TypeScript. But a large part of a trading stack is TypeScript: pricing and blotter UIs, market-data gateways, the Node.js services between them. Those have latency budgets too, in milliseconds and frame times instead of nanoseconds. Reading the paper with that in mind, the techniques fall into three groups: those that translate, those where the same goal needs a different mechanism, and those with no equivalent. Pretending the last group exists is how misleading "HFT patterns in JavaScript" examples get written.

Cache warming becomes JIT warming

In C++, cache warming keeps the instructions and data of the rarely taken order-sending path in the CPU caches, so the one time it matters it does not start with a run of misses.

A JavaScript program cannot control cache contents, but it has a larger cold-start problem of the same shape. V8 starts a function in the interpreter and only compiles it with the optimising tiers after it has run enough times with stable types. The first executions of a path are the slow ones, and the first execution of the order path happens when there is an order.

The equivalent technique is to run the real code path at start-up with representative inputs, before connecting to anything: decode recorded messages, update a book, build and discard orders. A memoisation table filled with precomputed results is sometimes presented as "cache warming"; that is a lookup table, a different technique with a different purpose.

Compile-time dispatch becomes monomorphism

C++ removes virtual calls with templates and CRTP so the compiler can resolve and inline the target. TypeScript's types are erased and decide nothing at run time. Passing a function as an argument is the dynamic dispatch the paper is removing.

What V8 offers instead is speculative: each call site and property access records the object shapes it has seen. A site that has only seen one shape is monomorphic and can be inlined; after a handful it becomes polymorphic and slower; beyond that megamorphic, with a generic lookup. So the practical rules are:

  • construct hot objects in one place, with the same fields in the same order, and never add or delete properties afterwards;
  • do not push several message types through one generic handler on the hot path; a separate handler per type keeps each site monomorphic;
  • avoid changing a field between integer and floating-point values or undefined.

The effect is the same as compile-time dispatch, direct inlined calls, but it is earned at run time and can be lost by one differently shaped object.

SIMD does not exist, layout still matters

JavaScript has no SIMD API. A loop over two Float32Arrays is compiled as a scalar loop. If vector instructions are needed, the route is WebAssembly, whose SIMD extension provides fixed-width 128-bit operations and can be compiled from C++ or Rust.

What does carry over is the data-layout half of the argument. An array of objects is an array of pointers to separately allocated objects. Parallel typed arrays (prices: Float64Array, sizes: Float64Array) are contiguous, unboxed, and produce no garbage when updated. For an order book ladder or a tick buffer feeding a chart, that change is usually worth more than any micro-optimisation of the loop body.

The Disruptor: possible, with caveats

The Disruptor is a preallocated ring buffer with sequence counters instead of locks. A plain array with two indices on one thread is a queue, not a Disruptor; the pattern only means something between threads. In Node.js that requires SharedArrayBuffer and Atomics, with fixed-width records in typed arrays because objects cannot be shared.

A single-producer, single-consumer version:

// Single-producer, single-consumer ring of fixed-size Float64 records.
class SpscRing {
  private idx: Int32Array; // [0] = head (consumer), [1] = tail (producer)
  private data: Float64Array;
  private mask: number;

  constructor(
    sab: SharedArrayBuffer,
    capacity: number,
    private width: number,
  ) {
    this.idx = new Int32Array(sab, 0, 2);
    this.data = new Float64Array(sab, 8, capacity * width);
    this.mask = capacity - 1; // capacity must be a power of two
  }

  static bytes(capacity: number, width: number) {
    return 8 + capacity * width * 8;
  }

  // Producer only. Returns false when full: the caller decides what to drop.
  push(a: number, b: number): boolean {
    const tail = Atomics.load(this.idx, 1);
    if (((tail - Atomics.load(this.idx, 0)) | 0) > this.mask) return false;
    const at = (tail & this.mask) * this.width;
    this.data[at] = a;
    this.data[at + 1] = b;
    Atomics.store(this.idx, 1, (tail + 1) | 0); // publish after the write
    return true;
  }

  // Consumer only. Copies into `out` so nothing is allocated per message.
  pop(out: Float64Array): boolean {
    const head = Atomics.load(this.idx, 0);
    if (head === Atomics.load(this.idx, 1)) return false;
    const at = (head & this.mask) * this.width;
    out[0] = this.data[at];
    out[1] = this.data[at + 1];
    Atomics.store(this.idx, 0, (head + 1) | 0);
    return true;
  }
}

With a worker thread producing five million [sequence, value] records and the main thread busy-spinning on pop, every record arrived in order with no gaps, at four to five million messages per second on Node.js 22 on a 4-vCPU VM. Treat that figure as proof that it works, not as a benchmark.

Three honest caveats. Head and tail sit in the same cache line here, so producer and consumer invalidate each other's line on every operation; the real Disruptor pads its sequences to avoid exactly this false sharing. A busy-spinning consumer cannot also run an event loop, so it needs a dedicated thread. And the multi-consumer dependency graph that makes the Disruptor useful in an OMS is considerably more work than this.

Allocation is the latency source C++ does not have

The paper has no section on garbage collection because C++ has none. On V8 it is the dominant cause of tail latency, so the most important pattern is one the paper does not need: allocate nothing per message. Reuse objects, decode into preallocated typed arrays, avoid closures and intermediate arrays in the per-tick path, and keep long-lived state stable so it is not rescanned. Short-lived garbage is cheap individually; the pauses come from volume and from objects that survive long enough to be promoted.

Benchmarking: distributions, not timers

The paper uses Google Benchmark. The TypeScript equivalent is not console.time around a loop, which reports one number that includes JIT warm-up and hides the tail. Measure after warm-up, record each observation with process.hrtime.bigint() into a histogram (perf_hooks.createHistogram() is built in), and report p50, p99, p99.9 and the maximum.

When measuring a service under load, generate requests on a fixed schedule and time each from when it should have been sent. A load generator that waits for each response before sending the next stops measuring exactly when the system stalls, and reports a tail far better than the real one. Gil Tene named this coordinated omission.

Networking: where the comparison ends

The paper's networking section concerns kernel bypass and NIC-level techniques. None of that is reachable from Node.js, which sits on the kernel TCP stack through libuv. A WebSocket client is not a low-latency networking technique.

The choices that are available at this level: disable Nagle's algorithm (socket.setNoDelay(true)) on request/response links, use binary encodings with fixed layouts instead of JSON on high-rate streams, batch writes per event-loop tick instead of per message, and conflate per instrument before the socket instead of after.

What to take from it

The paper's method transfers better than its code: decide what the latency-critical path is, give it a budget, benchmark every change, and distrust intuition. In TypeScript the specific techniques become JIT warm-up, shape stability, typed-array layout, zero allocation per message and honest percentile measurement. When those are not enough, the remaining latency is in the runtime, and the fix is to move that component to a language without one.