LMAX Exchange is a trading exchange that processes 6 million orders per second on one thread, in one JVM, on commodity hardware. The data structure that makes it work is called the Disruptor. It’s a ring buffer, and most of this post is about why that beats a queue.
I went down this rabbit hole after hitting performance walls with ArrayBlockingQueue in a project at work. The numbers I found were hard to believe at first: 52 nanoseconds mean latency versus 32,757 nanoseconds for the same pipeline using a standard bounded queue. That’s 630x, close to three orders of magnitude, with the same hardware, the same data and the same logical flow.
The problem with queues
Queues seem like the obvious choice for passing data between threads: the producer writes and the consumer reads. Underneath, a bounded queue needs to track three things: the head pointer, the tail pointer, and the current size. Multiple threads write to these counters, so they have to be protected with locks or CAS operations, and both are expensive.
The LMAX team measured how expensive. They benchmarked a simple 64-bit counter, incremented 500 million times:
| Method | Time | Slowdown |
|---|---|---|
| Single thread, no lock | 300 ms | 1x |
| Single thread, CAS | 5,700 ms | 19x |
| Single thread, lock | 10,000 ms | 33x |
| Two threads, lock | 224,000 ms | 747x |
The same table to scale. The first three bars are all single-threaded.
Two threads contending on a lock made the counter 747 times slower than one thread without a lock.
Locks are slow even when nobody’s fighting over them. A single thread with a lock is 33x slower than without one, because the CPU still has to execute the lock/unlock instructions, issue memory barriers, and flush the store buffer.
CAS operations look better (19x), but they still force the CPU to coordinate across cores through the cache coherence protocol. Every CAS becomes a round trip to main memory if another core recently touched that cache line.
What’s a ring buffer?
Picture a circular array of fixed size, allocated once at startup. A producer writes to the next slot and a consumer reads from the next slot. When you reach the end, you wrap around to the beginning.
There are no linked lists and no node allocations, so there’s no garbage collection pressure. The events live in the array forever. Producers mutate the existing objects in place and never create new ones.
The Disruptor’s ring buffer uses a power-of-2 size, so finding the array index from a sequence number becomes a bitwise AND instead of a modulo:
// slow: involves integer division
int index = sequence % bufferSize;
// fast: single CPU instruction
int index = sequence & (bufferSize - 1);
It’s a small thing, but small things stack up when you do them millions of times per second.
No shared writes
In a queue, the head and tail pointers are shared mutable state. Both the producer and the consumer need to read and write them, and that’s the root of all the contention.
The Disruptor flips this, and it took me a while to get how. Every participant gets its own sequence counter. The producer has a cursor that tracks the latest published event, and each consumer has its own sequence tracking where it’s read up to. The producer only writes to its cursor, each consumer only writes to its own sequence, and nobody shares write access to anything.
To find out whether there’s data available, a consumer reads the producer’s cursor. Reads don’t cause cache invalidation, and multiple cores reading the same cache line is free. To find out whether it’s safe to overwrite a slot, the producer reads the slowest consumer’s sequence. That’s also a read, so there’s no contention.
This is the single-writer principle: every piece of mutable state is written by exactly one thread.
False sharing
CPUs don’t read individual variables from memory. They read entire cache lines, 64 bytes at a time on x86.
If two variables sit on the same cache line and different threads write to them, the CPU invalidates the entire line on every write. Thread A writes the producer cursor, and Thread B’s cached copy of the whole line becomes stale. Thread B writes the consumer sequence, and Thread A’s copy goes stale. This goes back and forth constantly, even though the threads are writing to completely different variables.
This is called false sharing, and it’s brutal. I wrote a whole post on it: CPU Cache: What Every Programmer Should Know.
The Disruptor’s fix is padding. Each Sequence object stuffs 56 bytes of unused longs on each side of the actual value:
// LhsPadding class (Disruptor 3.x)
protected long p1, p2, p3, p4, p5, p6, p7;
// Value class
protected volatile long value;
// RhsPadding class
protected long p9, p10, p11, p12, p13, p14, p15;
7 longs times 8 bytes equals 56 bytes of padding per side (Disruptor 4 gets the same 56 bytes from byte fields), so the value sits alone in its own cache line. With no false sharing, reads from different cores hit L1 cache instead of bouncing to main memory.
The latency difference between L1 and main memory:
| Level | Latency |
|---|---|
| L1 cache | ~1 ns |
| L2 cache | ~3 ns |
| L3 cache | ~15 ns |
| Main memory | ~60-80 ns |
Going all the way to RAM is 60-80x slower, and false sharing forces that penalty on every access.
Wait strategies
When a consumer has caught up to the producer and there’s nothing to read, it needs to wait. The user guide describes four options.
BusySpinWaitStrategy burns CPU in a tight loop. It has the lowest latency, and your electricity bill won’t thank you. Use it when you have dedicated cores and nanoseconds matter.
YieldingWaitStrategy spins but calls Thread.yield() periodically. It’s good for low-latency workloads where you’re OK giving the OS a chance to schedule other threads.
SleepingWaitStrategy spins for a bit, then starts calling LockSupport.parkNanos(1). On Linux that’s about a 60 microsecond pause, which is good enough for async logging or background processing.
BlockingWaitStrategy uses a lock and condition variable. It has the highest latency and the lowest CPU usage. It’s the default, and it’s fine for most applications.
That they offer four ways to wait tells you something about the audience: these are people counting nanoseconds.
Multicast: one write, many readers
Queues are point-to-point. One producer puts an event in and one consumer takes it out. If you want three consumers to process the same event, you need three queues and three copies.
The Disruptor multicasts. Every consumer sees every event and tracks its own position independently, with zero copying. Three consumers processing the same data cost almost nothing extra compared to one.
You can build dependency chains too: C1 and C2 process in parallel, and C3 runs after both finish. The Disruptor DSL makes this look clean:
disruptor.handleEventsWith(handler1, handler2)
.then(handler3);
Under the hood, C3’s sequence barrier watches C1 and C2’s sequences and won’t advance past the minimum of the two. It needs no locks. It reads their sequences (again: reads are free) and waits if either is behind.
Batching
The batching behaviour surprised me.
When a consumer falls behind the producer, multiple events pile up. The consumer grabs them all in one batch and processes them without re-checking the sequence barrier between events.
Under light load, the batch size is 1. Under heavy load, batches grow and throughput increases to match, so the system adapts to pressure without any explicit backpressure mechanism.
Traditional queues do the opposite. Under heavy load, lock contention gets worse, latency grows exponentially, and the system degrades. The Disruptor’s throughput increases while latency stays nearly flat, which is counterintuitive.
The LMAX architecture
The Disruptor is a building block. Here’s how LMAX wires it into a complete trading system.
The input Disruptor runs three consumers in parallel: one unmarshals network messages, one journals events to disk, one replicates to backup nodes. All three process every input event (multicast). The Business Logic Processor waits for all three to finish before consuming.
The Business Logic Processor runs on a single thread, with no locks, no synchronization and no concurrent data structures. All state lives in memory. It processes every order for every customer in every market on one core, at 6 million orders per second.
It’s single-threaded because of what locks cost. A single thread with all data in L1/L2 cache is faster than multiple threads fighting over shared state, and the LMAX team proved it.
The system uses event sourcing for durability. Input events get journaled to disk. If the process crashes, it replays the journal from the last snapshot. A full restart takes under a minute.
Three instances of the Business Logic Processor run simultaneously: two in the primary datacenter, one at the disaster recovery site. All consume the same input events, but only the leader’s output gets published. Failover happens in microseconds.
The numbers
Here’s the Disruptor against ArrayBlockingQueue in a 3-stage pipeline (producer, three consumers in series).
Latency (50 million events, Core i7-2720QM):
| Metric | ArrayBlockingQueue | Disruptor |
|---|---|---|
| Mean | 32,757 ns | 52 ns |
| 99th percentile | ~2.1 ms | 128 ns |
| 99.99th percentile | ~4.2 ms | ~8.2 us |
Mean latency is 630x better, and the 99th percentile is 16,384x better.
Throughput (AMD EPYC 9374F, Linux 5.4, OpenJDK 11, Disruptor v4, from the newer results table in the technical paper):
| Pattern | ArrayBlockingQueue | Disruptor | Speedup |
|---|---|---|---|
| Unicast (1P-1C) | 20.9M ops/s | 160.4M ops/s | 7.7x |
| Pipeline (1P-3C) | 5.2M ops/s | 101.3M ops/s | 19.4x |
| Multicast (1P-3C) | 2.4M ops/s | 70.0M ops/s | 29.7x |
Throughput in millions of operations per second. The queue loses most of its throughput as consumers are added, the Disruptor loses about half.
The more complex the topology, the bigger the gap. Multicast is nearly 30x faster. The queue version needs a separate queue for every consumer, while the Disruptor shares one ring buffer.
What I took away
The Disruptor taught me three things I keep coming back to.
The first is to respect the hardware. Martin Thompson calls this “mechanical sympathy.” Know your cache line size, the cost of a lock, and what false sharing is, and write code that works with the CPU.
The second is to simplify the concurrency model. The Disruptor is built on the idea that the fastest synchronization is no synchronization. The single-writer principle eliminates contention, pre-allocation eliminates GC, and monotonic sequences eliminate the need for a size counter. Every coordination point you remove is a bottleneck you remove.
The third is to measure everything. The LMAX team benchmarked a counter to find out how slow locks are, and they measured latency distributions down to the 99.99th percentile before calling ring buffers fast. The numbers drove every design decision.
The Disruptor is a Java library, but the ideas transfer to any language. Cache-line padding works in C++ and Go, and the single-writer principle and ring buffers work everywhere. If you’re building anything latency-sensitive, it’s worth studying how they did this.
References
- LMAX Disruptor Technical Paper - The official write-up
- The LMAX Architecture - Martin Fowler - Complete system overview
- GitHub: LMAX-Exchange/disruptor - Source code (18k+ stars)
- Performance Results - Official benchmarks
- Dissecting the Disruptor: Why It’s So Fast - Trisha Gee on lock costs
- Mechanical Sympathy Blog - Martin Thompson’s hardware-aware programming blog