Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content
mortziPublic

About

Lock-free SPSC ring buffer, NASDAQ ITCH 5.0 decoder, and live order book in C++20. Covers memory ordering, cache-line false sharing, binary protocol parsing, and variant-based message dispatch.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

golem

A C++20 pipeline built in three layers: a lock-free SPSC ring buffer, a NASDAQ ITCH 5.0 binary decoder, and a live order book. Demonstrates the C++ memory model, cache-aware data structure design, and low-level protocol parsing.


Components

Ring buffer

Lock-free SPSC queue. Producer and consumer run on separate threads with no mutex. push and pop are O(1), noexcept, and use inline storage — no heap allocation per operation.

ITCH 5.0 decoder

Parses raw NASDAQ ITCH 5.0 binary frames from a std::span<const uint8_t>. Returns a std::variant of typed message structs — zero dynamic allocation, no virtual dispatch. Handles 7 message types: SystemEvent, AddOrder, OrderExecuted, OrderCancel, OrderDelete, OrderReplace, Trade.

Order book

Per-symbol Book maintains aggregated share counts per price level (std::map<Price, Shares>). Best bid/ask is O(log n) via rbegin/begin. A secondary unordered_map<OrderRef, Stock> in BookMap provides O(1) routing of order events that carry no stock field.


Design decisions

acquire / release

push:  head  = head_.load(relaxed)    // only the producer writes head_
       tail_.load(acquire)            // see latest consumer position
       write slots_[head & mask]
       head_.store(head+1, release)   // slot write visible before index advance

pop:   tail  = tail_.load(relaxed)    // only the consumer writes tail_
       head_.load(acquire)            // see latest producer position
       read  slots_[tail & mask]
       tail_.store(tail+1, release)   // slot free; consumer advances index

The release-store on head_ pairs with the consumer's acquire-load — exactly enough ordering to guarantee the slot write is visible before the index advance. relaxed on a thread's own index is safe: no other thread races on that load/store.


Cache-line padding

alignas(64) std::atomic<std::size_t> head_{0};  // producer's cache line
alignas(64) std::atomic<std::size_t> tail_{0};  // consumer's cache line

Without padding, head_ and tail_ share a cache line. Every push invalidates the consumer's copy and vice versa — a coherence round-trip on every operation. The benchmark's UnpaddedRingBuffer variant quantifies this penalty (see results below).


Power-of-two capacity + bitmask indexing

slot = counter & (Capacity - 1)    // bitmask  — one AND
slot = counter % Capacity          // modulo   — one DIV

Enforced at compile time:

template <typename T, std::size_t Capacity>
    requires(Capacity >= 2 && (Capacity & (Capacity - 1)) == 0)
class RingBuffer { ... };

C++20 features used

Feature Where
requires-clause Capacity power-of-two constraint
std::span Decoder input — non-owning view over raw bytes
std::bit_cast Endian-safe integer reconstruction in the decoder
[[nodiscard]] push / pop — caller cannot silently discard failures

Build

Requirements: CMake 3.21+, LLVM Clang 17+ with C++20 support.
GTest and Google Benchmark are fetched automatically via CMake FetchContent.

cmake -B build \
  -DCMAKE_CXX_COMPILER=clang++ \
  -DCMAKE_BUILD_TYPE=Release \
  -DCMAKE_EXPORT_COMPILE_COMMANDS=ON
cmake --build build

./build/tests/test_ring_buffer    # ring buffer tests
./build/tests/test_itch_decoder   # decoder tests
./build/tests/test_order_book     # order book tests
./build/bench/bench_ring_buffer   # benchmarks

ITCH replay tool

Replays a NASDAQ ITCH 5.0 file through the full pipeline and prints final best bid/ask per symbol.

./build/tools/replay <itch-file>              # full file
./build/tools/replay <itch-file> <max-bytes>  # stop after N bytes

Progress and timing to stderr; book state and summary to stdout.


Docker (Linux)

docker build -t golem-bench .
docker run --rm golem-bench                                              # benchmarks
docker run --rm --entrypoint ./build/tests/test_ring_buffer golem-bench  # tests

Benchmark results

Run on target hardware: ./build/bench/bench_ring_buffer
Native build only — virtualised threading distorts cross-core measurements.

x86-64 Linux, 2-core Intel, Clang, Release.

Benchmark Latency Items/sec Notes
BM_RoundTrip_Padded 3.98 ns 252 M/s Single-thread, no contention
BM_RoundTrip_Unpadded 3.92 ns 255 M/s Single-thread, no contention
BM_Spsc_Padded 15.2 ns 66 M/s Two threads, padded
BM_Spsc_Unpadded 37.4 ns 27 M/s Two threads, false sharing active

Single-thread numbers are identical — padding has no effect without cross-core contention. Two-thread results show the false sharing penalty on x86: 2.5× latency, 59% throughput loss for two missing alignas(64).


Limitations

  • SPSC only. One producer, one consumer — MPMC would require a different synchronisation strategy.
  • Fixed capacity. Intentional — backpressure is visible immediately rather than hidden behind unbounded allocation.
  • Decoder covers 7 of ~25 ITCH 5.0 message types. Sufficient for order book reconstruction; remaining types decoded as Unknown.
  • Order book uses std::map. O(log n) per level operation — correct for a replay tool, not for a production matching engine.
  • T must be nothrow-movable. push and pop are noexcept; a throwing move triggers std::terminate.

About

Lock-free SPSC ring buffer, NASDAQ ITCH 5.0 decoder, and live order book in C++20. Covers memory ordering, cache-line false sharing, binary protocol parsing, and variant-based message dispatch.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages