Skip to main content
← PROBLEMS / LOW-LEVEL-DESIGN
An end-to-end domain learning journey

Design a Sub-Microsecond MPMC Ring Buffer
for a Financial Matching Engine.

High-frequency matching engines cannot tolerate JVM GC pauses or mutex lock jitter on the order ingress path.
Start the journey2 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

Pre-allocate mutable OrderEvent flyweights inside a 64B-padded power-of-2 ring buffer, claim slots via CAS, and drain batches in consumers.

TL;DR30-second simplified summary
▾

Flyweight object reuse + 64B padding + consumer batching eliminates GC and amortizes CAS/memory-barrier overhead.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Lock-Free Ring Buffer (Disruptor)
Per-slot sequence counters and power-of-2 bitmasking.
Flyweight Pattern
Mutating pre-allocated slot structs in-place to achieve 0 bytes/op heap allocation.
Full walkthrough · 2 stages
01
L4 · FUNDAMENTALS

C & L — Flyweight Slots & Consumer Batching.

16-Producer Matching Engine Ingress

16 Netty/NIOThreadsPadded CAS Claim65536 FlyweightRingBatching ConsumerstryClaim()write in-placedrainBatch()

Instead of passing immutable OrderEvent objects (which still allocate on the heap), pre-allocate OrderEvent[65536] at startup. Producers claim pos, overwrite slots[idx].orderId/price/qty in-place, and publish pos + 1. Consumers read available = highestPublished - readCursor and process entire batches in one L1-warm loop.

02
L4 · FUNDAMENTALS

A & S — Batch Drain & Backpressure in Java.

Producer-Consumer Batching Sequence

IO ThreadRing SlotWorker1. Claim & mutate flyweight2. lazySet(pos+1)3. Drain batch & release
Engineering Decision Framework
Problem
How should the ingress ring handle a slow consumer when all 65,536 slots fill up?
Naive Solution
Allocate an unbounded linked list fallback queue.
Why It Fails
Unbounded queues cause OOM crashes and 100ms+ queuing delays during market bursts.
Alternatives
Bounded ring with non-blocking tryOffer + 503 backpressure,Unbounded ConcurrentLinkedQueue,Blocking put()
Engineering Decision
Keep the ring strictly bounded and return false from tryOffer() so Netty drops/sheds excess market-data ticks or applies TCP backpressure.
Trade-Offs
Requires explicit backpressure handling at the network edge, but guarantees deterministic bounded latency.
Decision Exercise · Make the Call

Why does publishedSeq[idx].lazySet(pos + mask + 1) release the slot for the next wrap-around?

Draining up to maxBatch = 64 ready slots per loop amortizes readCursor updates:

public int drainBatch(int maxBatch, java.util.function.Consumer<T> handler) {
    int count = 0;
    while (count < maxBatch) {
        long pos = readCursor.get();
        int idx = (int) (pos & mask);
        if (publishedSeq[idx].get() != pos + 1) break;
        if (readCursor.compareAndSet(pos, pos + 1)) {
            @SuppressWarnings("unchecked")
            T item = (T) slots[idx];
            handler.accept(item);
            slots[idx] = null; // or reset flyweight
            publishedSeq[idx].lazySet(pos + mask + 1);
            count++;
        }
    }
    return count;
}
Recommended Learning Flow