ringfire ๐ฅ
ringfire is an ultra-low-latency, zero-copy, lock-free Inter-Process Communication (IPC) ring buffer and shared memory state bus for Linux.
It is engineered for high-frequency trading (HFT) engines, real-time market data ingestion, telemetry buses, and performance-critical distributed pipelines where microsecond socket latencies and kernel overhead are unacceptable.
โก Performance at a Glance
Round trip of a 64-byte message between two threads, same machine, same harness
(cargo bench --bench ipc_compare, AMD Ryzen 9 7950X, Linux 6.8, v0.4.0):
| Transport | Round trip | vs. ringfire (spin) |
|---|---|---|
| ringfire, busy-spin readers | 0.32 ยตs | 1ร |
ringfire, FutexWait (sleeps in the kernel when idle) |
2.27 ยตs | 7ร |
| Unix domain socket | 4.76 ยตs | 15ร |
| Pipe | 4.93 ยตs | 15ร |
TCP loopback (TCP_NODELAY) |
10.28 ยตs | 32ร |
xychart-beta
title "64-byte round trip, microseconds (lower is better)"
x-axis ["ringfire spin", "ringfire futex", "Unix socket", "Pipe", "TCP loopback"]
y-axis "ยตs" 0 --> 11
bar [0.32, 2.27, 4.76, 4.93, 10.28]
Hot-path costs (cargo bench --bench throughput, 64-byte messages):
| Operation | Time | Rate |
|---|---|---|
push (no reader attached) |
1.88 ns | 533 M msg/s |
try_recv |
6.4 ns | 156 M msg/s |
recv_batch(32) |
2.3 ns / msg | 431 M msg/s |
push with a reader draining on another core |
41 ns | 24 M msg/s |
| Blackboard read / write (O(1) seqlock) | 2.1 / 1.1 ns | โ |
The last push row is the realistic cross-process figure: it is bound by moving cache lines
between cores, and costs the same with lossless backpressure enabled (+0.8 ns). Every read is
validated against concurrent overwrites; the regression suite verifies zero torn records under
continuous lapping on x86-64 and AArch64. Full numbers: Detailed Benchmarks.
๐ก The Problem: Why Traditional IPC Fails Under High Load
When communicating between processes on the same host, developers usually default to Unix Domain Sockets (UDS), TCP loopback, pipes, ZeroMQ, or broker-based message queues (NATS, Redis). In high-throughput, low-latency environments, these primitives introduce severe architectural bottlenecks:
| IPC Mechanism | Kernel Overhead | Memory Copies | One-way Latency | Backpressure / Crash Behavior |
|---|---|---|---|---|
| Unix Domain Sockets (UDS) | 2 syscalls (send/recv) + context switch |
User $\to$ Kernel $\to$ User (2 copies) | ~2,400 ns measured (RTT / 2) | Socket buffer fills up; blocks producer or drops packets |
TCP Loopback (127.0.0.1) |
Full TCP/IP stack + packetization | Multiple copies + TCP buffers | ~5,100 ns measured (RTT / 2) | Heavy CPU jitter, flow control stalls |
| Pipes / FIFOs | Pipe inode lock + syscalls | Buffer copy through VFS | ~2,500 ns measured (RTT / 2) | Blocking write when pipe buffer (64 KB) fills |
| Message Brokers (Redis / NATS) | Network stack + daemon context switch | Multi-hop serialization | 50,000 โ 500,000 ns (typical, not measured) | High GC/memory pressure, single point of failure |
ringfire (Shared Memory) |
0 syscalls on hot path | 1 copy (payload into the slot) | ~160 ns one-way (measured) | Writer never blocks (lossy) or throttles on the slowest reader (lossless); crash-isolated |
The Three Critical Pain Points:
- The Syscall & Context Switch Tax: Every
write()andread()triggers CPU privilege elevation from user-space to kernel-space and back, polluting CPU L1/L2 caches and branch predictors. - Buffer Bloat & Head-of-Line Blocking: If a consumer process stalls (e.g. garbage collection pause in Python, disk IO hiccup, or debug pause), standard socket buffers fill up immediately, stalling the critical producer or blowing up memory.
- Serialization Overhead: Marshalling data to and from JSON, Protobuf, or even compact binary encoders consumes valuable CPU cycles and allocates memory on the hot path.
๐ฏ The Solution & Vision: What ringfire Solves
ringfire moves the communication fabric directly into physical RAM via POSIX shared memory (/dev/shm):
- Pure Shared Memory (
/dev/shm): Producer and consumers map the exact same physical memory region directly into their virtual address spaces. - Atomic Acquire/Release Synchronization: State is coordinated via 64-bit atomic sequence numbers using CPU-level memory barriers (
core::sync::atomic), completely bypassing the operating system kernel. - Single-Writer Freedom (
LatestWinsPolicy): The producer always writes to the ring. Slow, paused, or dead consumers can never block, stall, or crash the producer. If a consumer falls behind the ring buffer capacity, it detects that it was lapped and skips cleanly to the live stream. - Cache-Line Isolated Layout: Memory structures are aligned to 128-byte cache lines to eliminate false sharing between producer write heads and consumer read heads.
- O(1) State Blackboard: Besides sequential stream events,
ringfireprovides a direct seqlock-synchronized slot table. Consumers can instantly inspect the latest state (e.g., current Best Bid & Offer for 500 coins) in ~2 nanoseconds without replaying historical events. - Polyglot First-Class Support: Because the layout in
/dev/shmis standard C-ABI memory, consumers can be written in Rust, C, C++, or Python (mmap+ctypes/numpy) with zero bridge penalty.
๐ค The Rapidfire Family
ringfire is designed as the cross-process counterpart to rapidfire:
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ IN-PROCESS (Single Process) โ
โ โ
โ rapidfire โ
โ โข Intra-process MPMC / MPSC channels across threads & Tokio โ
โ โข Ultra-low latency (< 15 ns), zero heap allocations โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ CROSS-PROCESS (Multi-Process IPC) โ
โ โ
โ ringfire โ
โ โข Inter-process lock-free ring buffer via /dev/shm โ
โ โข O(1) Shared State Blackboard (Seqlock) โ
โ โข ~160 ns cross-core latency, C11 header, Python bindings โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
๐ Detailed Benchmarks (AMD Ryzen 9 7950X on Linux booster)
Benchmarked using Criterion directly against POSIX shared memory (/dev/shm) on host booster (16 Cores / 32 Threads, Linux 6.8):
Measured with protocol v2 (v0.4.0), 64-byte messages:
| Metric | Measured Value | Rate / Notes |
|---|---|---|
| SPMC Single-Message Push (no reader) | 1.88 ns | 533 Million msgs / sec |
SPMC Non-Blocking try_recv |
6.41 ns | 156 Million msgs / sec |
SPMC Batch Drain (recv_batch(32)) |
74.2 ns (2.3 ns / msg) | 431 Million msgs / sec |
| Push with a reader draining on another core | 41.2 ns lossy / 42.0 ns lossless | Cross-core cache-line transfer; the lossless gate adds < 1 ns |
| Roundtrip Latency (Ping-Pong RTT) | 249.6 ns | ~125 ns one-way cross-thread IPC |
| Blackboard Seqlock Read (O(1)) | 2.13 ns | Tear-free snapshot read |
| Blackboard Seqlock Write (O(1)) | 1.13 ns | Seqlock update |
| Multi-Process Saturation | 1 writer + 8 readers | Zero gaps / zero corruption |
Single-threaded figures measure the instruction path with a warm cache; real cross-process
throughput is bounded by the cross-core transfer shown in the "with a reader" row.
tests/regression_tests.rs checks that no torn record is ever returned under continuous lapping.
๐ฆ Quickstart (Rust)
All snippets below are compiled and run in CI as examples/quickstart.rs (cargo run --example quickstart).
1. Producer: Publish Fixed-Size Binary Records
use RingProducer;
2. Tokio Async Consumer: Cooperative Non-Blocking Streaming
In async bots, busy loops starve the Tokio runtime. AsyncRingConsumer solves this with adaptive fast-path spinning, cooperative tokio::task::yield_now(), and 0% CPU idle sleep:
use AsyncRingConsumer;
async
3. Synchronous Low-Latency Consumer (Dedicated Cores)
use ;
let mut consumer = attach?;
let mut wait = new;
loop
4. Shared State Blackboard (O(1) Snapshot Table)
use ;
// Producer updates snapshot table
let mut bb_prod = create?;
bb_prod.write?; // ~1.1 ns write
// Consumer reads instantaneous current state by asset ID
let bb_cons = attach?;
if let Some = bb_cons.read?
5. Raw Binary Payloads ([u8; N]) & Pointer Casting
You can also operate over raw byte buffers without declaring fixed structs:
use ;
// Producer sends a raw 64-byte binary packet
let mut producer = create?;
let raw_bytes = ;
producer.push;
// Consumer reads the 64 bytes and decodes the struct (byte arrays are not aligned for it)
let mut consumer = attach?;
let bytes: = consumer.recv.await;
let ticker: MarketTicker = unsafe ;
6. Variable-Length Payloads (BlobProducer & BlobConsumer)
For variable-sized messages (e.g. L2/L3 order book snapshots, compressed frames, or variable trade batches), ringfire pairs fixed ring descriptors with a contiguous shared-memory PayloadArena:
use ;
// Create a ring with 65,536 descriptor slots and a 16 MB byte arena
let mut producer = new
.?;
// Push variable-length JSON, protobuf, or raw bytes directly into the arena
let raw_json = br#"{"event":"snapshot","bids":[[82000.5,1.2]],"asks":[[82001.0,0.8]]}"#;
producer.push?;
// Consumer copies metadata + payload out of the arena, validated against overwrites
let mut consumer = attach?;
let mut meta = 0u32;
let mut scratch_buffer = vec!;
if let Some = consumer.recv?
// Or inspect in place: the closure's result is discarded if the arena laps during it
let summary = consumer.view?;
If the arena wraps around before a consumer gets to a message (payloads larger than
arena_capacity / ring capacity on average), that message is skipped and counted in
lapped_count(); size the arena for the backlog you need to retain.
7. Consumer Start Modes & Lock-Free SHM Checkpointing
Consumers can configure where in the stream to begin reading, and persist their read cursors lock-free into /dev/shm (a single atomic store plus a timestamp):
use ;
let mut consumer = new
// Modes: Latest (instant jump), Head (wait for future), Oldest (replay backlog), Sequence(N)
.start_mode
.attach?;
// Or attach with persistent offset checkpoint in /dev/shm:
let mut persistent_consumer = new
.offset_file
.attach?;
// In consumer loop, periodically or per-batch commit offset:
persistent_consumer.commit_offset?;
8. Lossless Backpressure Flow Control
While default ringfire channels operate in LatestWins lossy mode (writer never blocks), streaming pipelines requiring zero message drops can enable LosslessBackpressure:
use ;
let mut producer = new
.flow_control
.?;
// Writer throttles (via spin/yield backoff) if slowest registered reader is about to be lapped:
producer.push;
// Or use non-blocking try_push:
match producer.try_push
What the guarantee covers:
- Only Rust
RingConsumers registered in the ring's reader registry hold the producer back (default 32 slots,RingProducerBuilder::max_readers). On a lossless ring, attaching when the registry is full fails withNoAvailableReaderSlots. Python and C readers do not register and can be lapped. - A reader is protected from the moment the producer observes its registration (the
producer rescans at least every half ring); a reader starting from
Oldeston a busy ring can still find its first messages gone and reports them vialapped_count(). - Reader liveness is checked by PID. Readers in another PID namespace (a different container) look dead to the producer and are dropped from the registry: share the PID namespace when using lossless mode across containers.
- The producer checks the registry only when it approaches the slowest cached cursor, so the lossless hot path has no syscalls and costs under 1 ns over lossy mode.
9. Multi-Channel Multiplexing (RingMultiplexer & AsyncRingMultiplexer)
Multiplex across multiple distinct ring buffer streams with fair Round-Robin or strict Priority scheduling:
use ;
let c1 = attach?;
let c2 = attach?;
let mut mux = new;
mux.add;
mux.add;
// Fair Round-Robin across all channels
if let Some = mux.try_recv_any
// Or Tokio async multiplexing:
// let (idx, ticker) = async_mux.recv_any().await;
10. CLI Diagnostic & Monitoring Tool (ringfire)
The bundled ringfire binary provides real-time terminal monitoring and inspection:
# View buffer configuration, sequence counters, and registered consumer lag
# Machine-readable JSON output for automated telemetry:
# Real-time interactive terminal dashboard with msg/s and MB/s throughput:
# Dump recent slots and payloads in hex or ASCII:
# Clean up dead reader slots from crashed processes:
๐ก๏ธ Memory Safety: Why Raw Pointers into Shared Memory Are Dangerous
In cross-process shared memory with a non-blocking writer (LatestWins), returning a raw pointer (*const T) directly into the mapped /dev/shm buffer is fundamentally unsafe:
- If a consumer holds a raw pointer to slot $K$, and the writer laps the buffer and begins overwriting slot $K$ on another CPU core, the consumer will observe a torn read (half old data, half new data).
- In high-frequency trading and order book streaming, a torn read corrupts prices and sizes, leading to disastrous trading errors.
The ringfire Solution: Slot Seqlock (protocol v2)
ringfire enforces tear-free reads without locks. The writer:
- Stores
SLOT_WRITING(u64::MAX) into the slot sequence, then a release fence. - Copies the payload.
- Stores the message sequence with
Ordering::Release.
The reader:
- Loads the slot sequence $s_1$ with
Ordering::Acquire; proceeds only if $s_1$ is the sequence it wants. - Copies the payload into its own stack/registers.
- Issues an acquire fence and reloads the sequence $s_2$.
- If $s_1 = s_2$, the copy is consistent. Otherwise the writer lapped the reader
mid-copy: the copy is discarded and the reader jumps to the oldest retained message,
counting the gap in
lapped_count().
Before v0.4.0 the writer skipped step 1, so a reader exactly one slot short of being lapped could accept a half-overwritten payload; the regression suite now hammers this case.
[!WARNING] Anti-Pattern: Returning Raw Pointers into Shared Memory (
*const T) Some naive IPC designs attempt to return a direct pointer or slice&[u8]into/dev/shmto claim "zero-memcpy". In a multi-process architecture with a non-blocking writer (LatestWins), this is a dangerous anti-pattern: the writer can overwrite that memory slot at any microsecond while the reader is parsing it, causing undefined behavior, silent data races, and torn reads.
ringfiredeliberately copies the slot payload into the reader's stack/register space inside a seqlock validation boundary (s1 == s2). For modern x86_64/ARM64 architectures, copying 32โ64 bytes takes ~1 CPU clock cycle (viavmovups) and is orders of magnitude faster than recovering from corrupted state or dealing with UB.
โก Wait Strategies
ringfire supports selectable wait strategies depending on CPU budget:
BusySpin: Sub-30ns reaction time. Spins tightly on CPU (core::hint::spin_loop()). Recommended for dedicated HFT cores.YieldBackoff: Spins for $K$ iterations then callsstd::thread::yield_now(). Balanced CPU usage with ~150ns reaction time.FutexWait: Sleeps on Linuxfutexwhen the queue is idle (timed sleep elsewhere). Near-0% CPU while waiting. The producer fast path has no full barrier, so a wake-up can rarely be missed; every sleep is therefore bounded (10 ms when no timeout is set).
๐ Polyglot Access (C / C++ / Python)
- C11 Header: Include
include/ringfire.hin any C/C++ project without linking overhead (header-only consumer), or link thecdylib/staticlibfor the FFI producer, consumer and blackboard. - Python (
python/ringfire):RingConsumer,RingProducer,BlobConsumer(zero-copytry_recvor validatedtry_recv_copy) and the blackboard, viammap+ctypes.Structure.
All bindings speak protocol v2 and locate slots through the header's slots_offset; v1 and
v2 peers refuse each other (VersionMismatch) instead of misreading memory. Python producers
rely on x86-64 store ordering (Python has no fences); use a Rust or C producer on AArch64.
๐ Delivery Semantics at a Glance
| Channel | Producer blocks? | Slow consumer | Delivery |
|---|---|---|---|
RingProducer (default LossyLatestWins) |
Never | Lapped: skips to the oldest retained message, lapped_count() |
At-most-once per reader, in order |
RingProducer + LosslessBackpressure |
When the slowest registered reader is a full ring behind | Holds the producer | Exactly-once, in order, for registered Rust readers |
BlobProducer / BlobConsumer |
Never | Skips messages whose ring slot or arena bytes were overwritten | At-most-once per reader, in order |
MpmcProducer / MpmcQueueConsumer |
Never | Overrun items are dropped, dropped_count() |
At-most-once, each item to one consumer |
BlackboardProducer / BlackboardConsumer |
Never | Always reads the latest value | Latest-value snapshot per key |
๐ฅ Author
Alexander Panasenko
- Email: alex@prod.codes
- GitHub: @alex09x
๐ License
Licensed under either of:
- Apache License, Version 2.0 (LICENSE-APACHE)
- MIT License (LICENSE-MIT)
at your option.