Quick revision
The short answer
For tens of microseconds per order, the design rests on a few principles: a single writer thread owns each order book, so matching needs no locks; objects are pre-allocated and reused, for example in ring buffers like the LMAX Disruptor, so the hot path allocates almost nothing; data lives in primitive arrays for cache locality; and hot sequence counters are padded against false sharing. We then trade CPU for latency with busy-spin wait strategies and CPU pinning, and measure with HdrHistogram under realistic bursts.
What to remember
In this answer, we turned a budget of tens of microseconds into design principles. A single writer thread owns each order book, so matching needs no locks and its data stays in one core's cache. Ring buffers and pre-allocated objects keep allocation near zero, as in the LMAX Disruptor. Prices as long ticks, array-based price ladders and primitive maps keep data compact. Padded sequence counters avoid false sharing, busy-spin waiting on pinned cores trades CPU for latency, and HdrHistogram measurements under realistic bursts confirm the tail.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
For tens of microseconds per order, the design rests on a few principles: a single writer thread owns each order book, so matching needs no locks; objects are pre-allocated and reused, for example in ring buffers like the LMAX Disruptor, so the hot path allocates almost nothing; data lives in primitive arrays for cache locality; and hot sequence counters are padded against false sharing. We then trade CPU for latency with busy-spin wait strategies and CPU pinning, and measure with HdrHistogram under realistic bursts.
Why this question is asked
Low-latency trading systems are where Java's reputation for unpredictable pauses meets hard requirements, and well-designed Java systems meet them. The trick is not a magic flag but a set of design principles that respect how CPUs, caches and the garbage collector behave. Interviewers ask this at the senior level to see whether we can turn mechanical sympathy into an architecture and explain the cost of each choice. In this answer, we will set out the time budget, then go through the threading model, allocation, data layout, false sharing, waiting and pinning, and finally how to measure the result.
1What Tens of Microseconds Means
A budget of, say, 20 microseconds per order is tiny. A single main-memory access is about 0.1 microseconds, a contended lock handoff between threads can cost several microseconds, waking a sleeping thread through the operating system often costs tens of microseconds, and one GC pause, even a short one, can cost far more than the whole budget. So the design must avoid locks, avoid waking threads, avoid allocation in the hot path and keep data in the CPU caches.
The work itself, matching an incoming order against the book, is a few comparisons and updates. Everything else in the design exists to stop the surrounding machinery from costing more than that work.
2The Single-Writer Principle
The most important decision is that each order book has exactly one thread that modifies it. That thread, the matching thread, reads incoming orders, matches them, updates the book and emits results. No other thread ever writes to the book's state.
With a single writer, there is no need for locks or compare-and-swap loops on the book, no contention between cores, and no cache lines bouncing between cores. The matching thread's data stays hot in its core's caches. To scale, we shard: different instruments are assigned to different matching threads, each owning its own books. Communication with other threads, such as the network threads that receive orders and the threads that publish results, happens through queues designed for one producer and one consumer.
7 messages in order. Play them, or step through them one at a time.
Each ring has one writer per slot sequence; only the matcher touches the book.
3Pre-Allocation and Ring Buffers
A garbage collector only runs when memory fills up. If the hot path allocates nothing, the collector has nothing to do during trading hours. So instead of creating a new object for each order message, the system pre-allocates a ring buffer, an array of reusable event objects of fixed size. A producer claims the next slot, overwrites its fields and publishes a sequence number; the consumer reads the slot when it sees that sequence. This is the design of the LMAX Disruptor.
Orders resting in the book are handled the same way. They come from a pre-sized pool of order objects or, even better, live in parallel primitive arrays indexed by an order slot number. This is one of the rare places where pooling is right: we have measured that allocation matters, and we accept the complexity of manual lifecycle management in exchange for zero GC activity.
Notice that prices are long ticks, integer multiples of the instrument's tick size, rather than BigDecimal. A BigDecimal allocates on most operations, while integer arithmetic on ticks is exact and free of allocation.
4Data Layout for Cache Locality
The matching thread spends its time looking at the best prices and the orders queued at them. We want those to be in contiguous memory. A price ladder can be an array indexed by tick offset from a reference price, so finding the level for a price is an index calculation rather than a tree lookup, and the levels near the best price are adjacent in memory. Orders at each level can be kept in arrays or intrusive lists over the pooled order slots, and lookups by order id use a primitive map such as Agrona's Long2ObjectHashMap or a long-keyed open-addressing map instead of a HashMap<Long, Order>.
Every reference we avoid is a cache miss we avoid. A TreeMap<BigDecimal, Deque<Order>> is the natural first design, and it is precisely the one that allocates, boxes and chases pointers on every operation.
5Avoiding False Sharing
The ring buffers communicate through sequence counters: the producer's published sequence and the consumer's processed sequence. These are written very frequently by different threads. If two of them sit in the same 64-byte cache line, every write makes the line bounce between cores, which is false sharing, and it can add more latency than the matching itself. The Disruptor pads its sequence fields so that each lives on its own cache line, and our own hot counters, such as per-thread statistics, need the same treatment.
6Wait Strategies and CPU Pinning
When the matching thread has no work, it must wait for the next order. Blocking on a lock or condition variable uses no CPU, but waking up takes tens of microseconds through the operating system. Busy-spinning, looping on the sequence counter, reacts within nanoseconds but burns a whole core all the time. Yielding and sleeping strategies sit in between.
| Strategy | Wake-up latency | CPU when idle | Use for |
|---|---|---|---|
| Busy spin | nanoseconds | one full core | matching thread on a pinned core |
| Yielding | low microseconds | high | busy threads without dedicated cores |
| Sleeping / parking | tens of microseconds | low | non-critical consumers |
| Blocking (lock + condition) | tens of microseconds or more | none | background work, logging |
For a matching engine, busy-spin on the critical threads is usually the right trade: we buy latency with dedicated cores. To make that work, we pin each critical thread to its own isolated core, for example with Linux isolcpus or cgroups plus a thread affinity library, so the scheduler never moves it or runs anything else there. Hyper-threading siblings of those cores are often left idle so they do not share execution resources. GC and JIT threads are kept on other cores, and the JVM is warmed up with realistic traffic before the market opens so the hot code is already compiled.
7Measuring Under Realistic Bursts
An average latency is useless here; we care about the tail. We record per-order latency into an HdrHistogram, which keeps accurate percentiles from microseconds to seconds, and report p50, p99, p99.9, p99.99 and the maximum. The load must come from an open-model generator that sends orders on a schedule, so stalls are not hidden by coordinated omission.
And the test must look like the real market. Markets are bursty: the opening auction or a news event can bring ten times the normal rate in a few milliseconds. So we replay recorded market data or generate bursts deliberately, and we check that the ring buffers never fill, that the tail stays within budget during the burst, and that the GC log shows no collections during the session.
8Follow-up questions
Which garbage collector would you use?
With near-zero allocation in the hot path, the collector matters less, because it rarely runs. Generational ZGC is a good default for its very short pauses; some teams size the heap so that no collection happens during a trading session at all. Either way, the GC log is part of the acceptance test.
Where does durability fit if everything is in memory?
Inbound orders are journaled, written to a sequential log on disk and often replicated to a standby, before or in parallel with matching, so the book can be rebuilt by replaying the journal. Because the matcher is a deterministic single-threaded state machine, replaying the same inputs produces the same state.
Is pooling here not against modern Java advice?
General advice says not to pool ordinary objects because allocation and young collections are cheap. In a system whose latency budget is smaller than a GC pause, the trade-off is different, and we have measured it. The principle is the same: decide from measurements, not from habit.
9Conclusion
In this answer, we turned a budget of tens of microseconds into design principles. A single writer thread owns each order book, so matching needs no locks and its data stays in one core's cache. Ring buffers and pre-allocated objects keep allocation near zero, as in the LMAX Disruptor. Prices as long ticks, array-based price ladders and primitive maps keep data compact. Padded sequence counters avoid false sharing, busy-spin waiting on pinned cores trades CPU for latency, and HdrHistogram measurements under realistic bursts confirm the tail.
Open with
With a budget of tens of microseconds, I have to design away locks, thread wake-ups, allocation and cache misses, because any one of them can cost more than the matching itself.
Then, if they want more
The core principle is single writer: each order book is owned by one matching thread, and instruments are sharded across threads. That thread never shares mutable state, so there are no locks or CAS loops, and its data stays hot in its core's cache.
Network threads hand orders to it through a single-producer ring buffer, and it hands fills to publishers through another, in the style of the LMAX Disruptor.
The ring buffers hold pre-allocated, reusable event objects, and resting orders come from a pre-sized pool or primitive arrays, so the hot path allocates nearly nothing and the GC has no reason to run during trading.
For data layout I use prices as long ticks instead of BigDecimal, a price ladder as an array indexed by tick offset, and primitive maps for order ids, all for locality. The sequence counters between threads are padded to separate cache lines to avoid false sharing.
For waiting, I would busy-spin on the critical threads and pin them to isolated cores, accepting a burned core in exchange for nanosecond reaction. Finally, I measure per-order latency with HdrHistogram, with an open-model load generator replaying realistic bursts like the market open, and check p99.9 and the maximum, not the average.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "You are designing a low-latency order matching component in Java with a target of tens...": https://scrivio-interview-library.netlify.app/java/java-performance/5d05be42e2/