mmapq
A persistent, indexed, replayable inter-process queue — no broker, no daemon, no garbage collector. The queue is just files.
mmapq passes messages between processes on the same Linux machine through
memory-mapped files, with sub-microsecond latency and allocation-free,
syscall-free hot paths. Unlike a transport, the queue is durable state:
every message has a stable index, any process can read at any index at any
time, and a consumer that restarts resumes exactly where it stopped. Unlike
a log framework, it costs a memcpy and one atomic CAS to publish.
What you get:
- ~280 ns median round-trip between two processes on isolated cores
(measured 2026-06-24, commit
d3cfb28; refreshed at the release gate; tables below) - Indexed and replayable — every message is addressable by index; readers can seek, tail, or re-read from zero. Replay is the same mechanism as recovery and replication
- Up to 256 writers per queue, over the queue’s lifetime unless IDs are released, lock-free, one atomic commit per message — no committed message is ever torn or partial
- Batch queues with atomic multi-message commit — append N messages, commit once; consumers never observe a partial batch. A transaction boundary, designed for command → event-batch architectures
- Crash-safe by construction — a killed producer never publishes a
partial message; what it had not committed stays invisible until its
restarted writer decides — the queue never commits it on anyone’s
behalf. Its lane stays occupied until an operator releases it with
mmapq-ids --unset(dead processes only — seedoc/guide/05-crash-and-restart.md) - No infrastructure — two processes and a directory (an optional in-process mapper thread hides mmap latency)
- Linux x86-64/ARM64; both tested in CI (the C suite in both build
loops, ASan, TSan, torture, and the Rust and Python suites). Run
bash scripts/test.shon your own host
Built for event-sourced systems: sequenced command queues, replicated
event logs, deterministic replay — where the answer to “what happened in
production” is re-run it. doc/guide/event-sourcing.md describes the
pattern this library was built to serve.
When to use it — and when not to
Be suspicious of any infrastructure library that doesn’t tell you when to avoid it. Honest edges:
Use mmapq when you need same-host inter-process messaging where the history matters: event-sourced services, sequenced order/command flow, market-data capture, sensor/telemetry logs that a second process analyses, and replay-based testing and debugging.
Use something else when:
- You need network transport. mmapq is same-machine only, by design; the wire path belongs to a network messaging system.
- You want pub/sub with many dynamic topics and no interest in history. mmapq queues are named, persistent streams, not a topic fabric.
- You want a full application framework rather than a storage layer —
see the references in
doc/guide/event-sourcing.md. - You need guaranteed durability through power loss. mmapq writes
reach the page cache, not the platter; the OS persists them eventually.
Queues here are transport-plus-recent-history; long-term data belongs in
the export format (
QueueTransfer) or a database. - You need Windows or macOS.
- You need to share queue files with Java in 0.2.0. Java-written queues are refused at open; read them with the Java library and migrate via export/import.
What you give up relative to the alternatives is scope. What you gain is a system small enough to audit end-to-end: ~10k lines of dependency-free C11, a frozen on-disk format specified in one normative document (generated from the codec headers), and a test suite that runs under the exact release flags that ship.
Stability
The feature set and the on-disk format are frozen within a schema version. This is a design position, not a maturity disclaimer:
Frozen within a schema version. 0.2.0 writes
schema_version=2and refuses 0.1.0 files (schema_version=1) at open. To move 0.1.0 data forward, export with a 0.1.0 library and import into a fresh 0.2.0 queue — the export stream format is unchanged. Each release states the schema versions it reads; a file of any other version is refused at open. A version change is always a clean refusal, never a silent misread. The feature set is frozen and the API grows only for capability already present in the C core.
The normative specification is doc/reference/wire-format.md (installed
with the library at share/doc/mmapq/wire-format.md); the authoritative
implementation lives in the source distribution at
src/internal/header_codec.h and src/internal/queue_meta.h.
If your evaluation horizon is years, this is the property to weigh: the library you audit today is the library you run in five years.
Compatibility
mmapq’s file format derives from Algoteq’s Java implementation (an evolved derivative of tools4j/mmap; not compatible with upstream tools4j). In 0.2.0, C, Rust and Python do not share queues with Java: 0.2.0 refuses Java-written queues at open (schema_version 1), and the Java implementation does not yet follow the 0.2.0 protocol (for example, it does not maintain the archive line). This applies to both queue types. Read Java-written queues with the Java library. Java support is planned at schema 2, under the same protocol contract (see
doc/reference/wire-format.md).
Quick start: single-message
Use a persistent directory (./data, not /tmp or /dev/shm) for
anything you mean to keep; a commit publishes to readers but does not flush
to stable storage. Create the directory first:
mkdir -p ./data
#include "runtime.h"
#include "indexed_queue.h"
#include "indexed_appender.h"
#include "indexed_poller.h"
static MmapqNextMove my_handler(int64_t index, uint8_t appender_id,
const void *data, int32_t length, void *ctx) {
printf("[%ld] %.*s\n", index, length, (const char *)data);
return MMAPQ_NEXT_ADVANCE;
}
int main(void) {
/* Background mapper thread — a process-wide singleton; call once */
MmapqRuntime *rt = NULL;
int rc = mmapq_runtime_region_mapper(&rt);
assert(rc == 0);
/* Open or create a queue; "./data" must already exist */
MmapqIndexedQueue *q = NULL;
rc = mmapq_indexed_queue_create_default("./data", "orders", rt, rt, &q);
assert(rc == 0);
/* Append a message */
MmapqIndexedAppender *a = NULL;
rc = mmapq_indexed_queue_create_appender(q, &a);
assert(rc == 0);
int64_t idx = mmapq_indexed_appender_append(a, "hello", 5);
/* Poll messages */
MmapqIndexedPoller *p = NULL;
rc = mmapq_indexed_queue_create_poller(q, &p);
assert(rc == 0);
MmapqPollResult r = mmapq_indexed_poller_poll(p, my_handler, NULL);
/* Close participants before the queue */
mmapq_indexed_appender_close(a);
mmapq_indexed_poller_close(p);
mmapq_indexed_queue_close(q);
mmapq_runtime_destroy(rt);
return 0;
}
The full producer/consumer is examples/demo.c; build the library and
examples with make. Full walkthrough: doc/guide/02-single-message-queue.md.
Quick start: batch
A batch groups messages under one atomic commit:
#include "runtime.h"
#include "indexed_batch_queue.h"
int main(void) {
MmapqRuntime *rt = NULL;
int rc = mmapq_runtime_region_mapper(&rt);
assert(rc == 0);
/* "./data" must already exist */
MmapqIndexedBatchQueue *q = NULL;
rc = mmapq_indexed_batch_queue_create_default("./data", "events", rt, rt, &q);
assert(rc == 0);
MmapqIndexedBatchAppender *a = NULL;
rc = mmapq_indexed_batch_queue_create_appender(q, &a);
assert(rc == 0);
MmapqMutableBatch *b = NULL;
rc = mmapq_indexed_batch_appender_start_batch_checked(a, &b);
assert(rc == 0);
mmapq_mutable_batch_append(b, "msg0", 4);
mmapq_mutable_batch_append(b, "msg1", 4);
mmapq_mutable_batch_append(b, "msg2", 4);
int64_t batch_idx = mmapq_mutable_batch_complete(b);
mmapq_indexed_batch_appender_close(a);
mmapq_indexed_batch_queue_close(q);
mmapq_runtime_destroy(rt);
return 0;
}
mmapq_mutable_batch_complete() publishes the batch and returns its index;
mmapq_indexed_batch_appender_commit_batch() is only for batches staged
with mmapq_mutable_batch_complete_uncommitted() (see
doc/guide/05-crash-and-restart.md). Full walkthrough:
doc/guide/03-batch-queue.md.
Core concepts
See doc/reference/feature-matrix.md for the full feature matrix across
the C, Rust, and Python implementations, including compatibility scope.
─────────────────────────────────────────────► Header
poll header (1) ▲ ▲ commit header (2)
│ │
POLLER │ │ APPENDER
│ │
resolve payload (2) ▼ ▼ write payload (1)
─────────────────────────────────────────────► Payload
The appender writes the message payload to its private payload lane first (step 1). Only after the payload is fully written does it commit the entry by publishing an 8‑byte header in the shared header lane via an atomic CAS operation (step 2). This ordering guarantees that the payload is always visible before the header — a reader that sees a non‑NULL header is guaranteed to see the complete payload.
The poller (sequential consumer) scans the header lane in index
order. When it finds a committed header (step 1), it decodes the
(appenderId, payloadPosition) from the 8‑byte value, navigates to
the corresponding payload lane at that position (step 2), and delivers
the message to the callback. The reader (random‑access consumer)
follows the same two‑step protocol for any index, without advancing a
cursor.
Multiple appenders coexist with minimal contention because each appender writes to its own private payload file, and the vertical‑walk layout in the shared header lane spreads concurrent CAS operations across different cache lines (512‑byte stride).
| Concept | What it is |
|---|---|
| Appender | A writer. Appends messages to a per-appender payload file and commits an 8-byte header atomically via CAS. Up to 256 writers per queue, over the queue’s lifetime unless IDs are released. |
| Poller | A sequential consumer. Reads headers in index order, follows the payload pointer, and delivers messages to a callback. |
| Reader | A random-access consumer. Reads any entry by index without advancing a cursor. |
| MmapqRuntime | A background thread that maps/unmaps file regions ahead of the hot loop. Absorbs ftruncate, page-zeroing, and MAP_POPULATE costs; normally the hot thread does not stall. A region wrap can still block up to the mapping timeout — the runtime is not a guarantee of zero stalls. |
| Single-message queue | One header commit per message. Maximum throughput for large messages, minimum overhead per message. |
| Batch queue | Groups N messages under one header commit. Higher throughput for small messages (fewer CAS operations). C/Rust/Python only in 0.2.0; Java-written queues are refused at open. |
| Deferred commit | Append payload without committing the header. Commit later, possibly in a different order. Useful for UDP resequencing or pipelined writes. |
| Mixed MmapqRuntime | Use separate runtimes for writing (async) and reading (sync). The writer offloads ftruncate to a background thread; the reader runs without any background interference for minimum latency. |
Performance
~280 ns median round-trip between two processes on isolated cores; tail
percentiles are in the current table below. The table is copied from
doc/guide/08-performance-and-tuning.md at the 0.2.1 release; it
reports date, hardware, and commit. The Java comparison is historical and
is not shown because Java queues are refused in 0.2.0.
Measured 2026-12-02 (0.2.1, commit 3e976c3 — code-identical to the
release apart from the version string), Intel i7-11800H, isolcpus 5,7,9 +
THP as below. Each figure is the median of 6 runs.
Single-message queue — roundtrip to echo server in external process, 20M iterations
| Percentile | C (this library) |
|---|---|
| min (p0) | 184 ns |
| p50 | 284 ns |
| p90 | 332 ns |
| p99 | 389 ns |
| p99.9 | 1705 ns |
| p99.99 | 8461 ns |
| p99.999 | 15454 ns |
| round trips/sec (closed loop) | 3.2 M |
Batch queue — roundtrip to echo server in external process, 20M iterations
| Percentile | C (this library) |
|---|---|
| min (p0) | 225 ns |
| p50 | 281 ns |
| p90 | 344 ns |
| p95 | 367 ns |
| p99 | 425 ns |
| p99.9 | 1629 ns |
| p99.99 | 6477 ns |
| p99.999 | 14847 ns |
| round trips/sec (closed loop) | 3.1 M |
The round-trips row is iterations divided by the wall-clock time of the measured loop, which has one round trip in flight at a time — roughly 1 / mean round-trip latency (the loop’s own per-iteration cost is included). It is not the queue’s capacity: a writer that does not wait for a reply is not bounded by it.
System configuration for best results
- Core isolation — kernel boot parameter
isolcpus=5,7,9(or equivalent) to reserve cores for the client loop, server loop, and region mapper. - Transparent Huge Pages — the library calls
madvise(MADV_HUGEPAGE)on mapped regions to reduce TLB pressure. - VDSO clock — use
CLOCK_MONOTONIC(the library default) to bypass the syscall overhead on timing. - Thread affinity — always spawn background threads before pinning the calling thread; see Anti-Pattern D in
doc/contributing/maintainer_guide.md.
Production features
Queue archiving
Long-running queues accumulate entries over weeks or months. Archiving
logically prunes old entries by advancing the queue’s start_index
without physically deleting data. Only a queue created with archivable
set can be archived; on any other queue, archive_up_to_index() returns
MMAPQ_EINVAL.
Forward archiving (index > current start_index):
Scans headers backwards from index - 1 to the current start, identifies
the last committed payload position per appender, advances past each message
(or exhausts the batch), and writes the new start offsets to per-appender
metadata. Finally, commits the new start_index atomically in the queue
meta — all poll() / read() calls immediately see the boundary.
Backward archiving / undo (index < current start_index):
Restores access to previously archived entries by scanning headers
forward, validating that all required header and payload files still exist
on disk, and rolling back the per-appender start offsets.
Archivable file discovery (archivable_files()):
Lists the files no live entry can need at the time of the call. Copy the
marked files aside if you keep long-term history, then delete the local
copies with reclaim_files(files). reclaim_files() re-lists and unlinks
under one archive-lock hold and is the recommended safe deletion path.
Hand deletion is safe only if no undo runs between the listing and the last
unlink.
Typical usage in production:
- Hourly: call
archive_up_to_index()to log the archive boundary. - Call
archivable_files()to list fully covered files. - Upload those files to S3 or Glacier.
- Delete local copies with
reclaim_files(files)once confirmed uploaded.
Export / import (QueueTransfer)
Export flattens queue data into a portable stream format for backup, migration, or chunked replay. Each stream begins with a 64-byte metadata header (stream version, region size, max file size, start index, entry count, archivable flag, queue type) followed by framed entries.
Chunked export splits a large export into multiple files of
approximately N MB each. Each chunk is a complete, self-contained stream
with its own header and embedded index range in the file name
(base_path_start-end). Chunks can be uploaded independently to object
storage and downloaded on demand during replay.
Import reads a stream and reconstructs the queue. Supports all four cross-over combinations:
| Import function | Stream format | Destination | Behaviour |
|---|---|---|---|
mmapq_queue_transfer_import | flat (single-message) | normal queue | Direct append |
mmapq_queue_transfer_import_batch_stream | batched | normal queue | Flatten batches |
mmapq_batch_queue_transfer_import | batched | batch queue | Direct batch commit |
mmapq_batch_queue_transfer_import_flat_stream | flat | batch queue | 1-msg batches |
Start index mode controls how the stream’s start_index metadata is
interpreted:
- REBASE (default): start index resets to 0.
- PRESERVE: start index matches the source range — useful for exact replica restoration and replay systems that track position by index.
Filters: Optional include/exclude callbacks allow selective export, import, or copy by content or position.
Typical usage in production:
- Every hour, export the queue with chunked export (
chunk_size_mb=64). - Upload each chunk file to S3.
- On restart: download the relevant chunks, import with PRESERVE mode, and replay to the point of interest.
Design
Header layout — the vertical walk
Each queue entry has an 8-byte header in a shared header file. To eliminate false sharing between concurrent appenders, headers use a non-linear striding algorithm that transposes the memory walk from horizontal to vertical across cache lines.
Layout (sectorSize=64, header=8 bytes):
index 0 → byte offset 0 (sector 0, word 0)
index 1 → byte offset 512 (sector 1, word 0) ← new cache line
index 2 → byte offset 1024 (sector 2, word 0) ← new cache line
...
index 63 → byte offset 32256 (sector 63, word 0)
index 64 → byte offset 8 (sector 0, word 1) ← back to sector 0
Sequential indices land on a new cache line every step. Only after 64 indices does the mapping return to a previous sector, now at the next 8-byte word within it. A block is 4096 headers (32 KB); consecutive indices stride 512 bytes and wrap every 64 indices.
The header encodes appender ID and payload position in a single 64-bit word committed via atomic CAS:
bits[63:56] = appenderId (0–255; up to 256 writers over the queue's lifetime)
bits[55:0] = payloadPosition
0 = HEADER_NULL (slot not yet written)
Payload framing
Each message in the payload file is framed as [int32 length][payload bytes].
Batch entries add a [int32 message_count] prefix before the first message.
C/Rust/Python only in 0.2.0; Java-written queues are refused at open.
Visibility and commit
A message is visible to consumers the instant the header CAS succeeds. The atomic release-store on the appender side and the acquire-load on the reader side establish the happens-before relationship that guarantees payload visibility — no locks, no kernel calls on the hot path.
Async region mapping
A background thread (mmapq_runtime_region_mapper) maps and unmaps file regions
in advance. Writers trigger premap at the start of each region (ratio 0.0);
readers trigger premap at the halfway point (ratio 0.5). The writer
extends the file with ftruncate and pre-touches pages via atomic CAS to
absorb dirty-bit penalties before the hot loop reaches the new region.
File layout
<directory>/<queue_name>/
meta queue config (region_size, max_file_size, schema version,
start_index, archivable flag, queue_type)
header_N shared header file (N = file index 0, 1, 2...; the
highest-indexed file is the current active one)
payload_A_N per-appender payload file (A = appender ID 0–255,
N = file index 0, 1, 2...; same pattern)
appender_meta_A per-appender state (start_offset, archive line, intent)
appender_id_pool CAS bitset — allocates appender IDs
All files are plain OS files. The normative byte-level specification is
doc/reference/wire-format.md.
Building
Requires: Linux, gcc, pthread. No external dependencies.
# Build the static library and all binaries
make
# Or build specific targets
make bench echo_server # single-message benchmark tools
make batch_bench batch_echo_server # batch benchmark tools
CMake is also supported:
mkdir -p build && cd build
cmake ..
make -j$(nproc)
CMake builds the library and examples only; scripts/test.sh is the test
runner.
Running the tests
./scripts/test.sh # normal + release-flags loops
./scripts/test.sh --asan # AddressSanitizer
./scripts/test.sh --tsan # ThreadSanitizer (run with ASLR disabled:
# setarch $(uname -m) -R ./scripts/test.sh --tsan)
Running the benchmarks
# Full benchmark suite: single-message + batch, all modes
./scripts/bench.sh
./scripts/batch_bench.sh
# Or via make (runs the scripts above):
make bench-suite
make batch-bench-suite
Or run individual configurations manually:
# Single-message, internal server
rm -rf /tmp/request /tmp/response
sleep 3
./latency_bench 20000000 1000 64 5 7 9
# Single-message, external server
rm -rf /tmp/request /tmp/response
sleep 3
./echo_server /tmp request response 7 9 &
./latency_bench 20000000 1000 64 5 7 9 --external
# Batch queue, internal server
rm -rf /tmp/request /tmp/response
sleep 3
./batch_latency_bench 20000000 1000 64 5 7 9
# Batch queue, external server
rm -rf /tmp/request /tmp/response
sleep 3
./batch_echo_server /tmp request response 7 9 &
./batch_latency_bench 20000000 1000 64 5 7 9 --external
Arguments: <iterations> <warmup> <msg_size> <client_cpu> <server_cpu> <mapper_cpu>
Override defaults via environment variables:
BENCH_ITER=5000000 BENCH_MAPPER=11 ./scripts/bench.sh
API overview
Start here — core functions
| Function | What it does |
|---|---|
mmapq_runtime_region_mapper(&rt) | Get the singleton background mapping thread (call once at startup) |
mmapq_indexed_queue_create_default(dir, name, wrt, rrt, &q) | Open or create a single-message queue |
mmapq_indexed_queue_create_appender(q, &a) | Create a writer |
mmapq_indexed_queue_create_poller(q, &p) | Create a sequential reader |
mmapq_indexed_appender_append(a, data, len) | Write and commit a message |
mmapq_indexed_poller_poll(p, handler, ctx) | Process one message via callback |
mmapq_indexed_batch_queue_create_default(dir, name, wrt, rrt, &q) | Open or create a batch queue |
mmapq_indexed_batch_appender_start_batch_checked() | Begin a new batch (0 or a negative MMAPQ_* code) |
mmapq_mutable_batch_complete() | Finalise the batch and publish it atomically |
mmapq_mutable_batch_append() | Add a message to an in-progress batch |
The authoritative per-function documentation is
doc/reference/api-overview.md
and the installed headers under <prefix>/include/mmapq/.
Documentation
doc/reference/feature-matrix.md— feature coverage across C, Rust, and Python, including compatibility scopedoc/reference/wire-format.md— the normative on-disk and export-stream formatdoc/reference/api-overview.md— the full C API referencedoc/reference/guarantees.md— every guarantee, with the test, model, or argument behind itdoc/guide/01-concepts.md…doc/guide/09-trade-offs-and-limits.md— the user guide: concepts, single-message, batch, resequenced commits, crash and restart, archiving and reclamation, export/import, performance, and trade-offsdoc/guide/event-sourcing.md— building sequenced command/event architectures on mmapqdoc/design/header_layout_design.md— full derivation of the vertical walk, worked example, and verification tracedoc/design/payload_alignment_design.md— payload framing and alignment rationaledoc/contributing/maintainer_guide.md— anti-pattern ledger, performance tuning baseline, thread affinity rules, metadata protocoldoc/RELEASE-NOTES-0.2.0.md— the single source for 0.1.0 → 0.2.0 changesdoc/RELEASE-NOTES-0.2.1.md— 0.2.0 → 0.2.1 changes
Corruption recovery
A SIGKILLed writer never releases its appender ID: the lane stays occupied
and re-acquisition is refused with MMAPQ_EIDCONFLICT. The supported
recovery is mmapq-ids --unset, valid only when the holding process is
dead; see doc/guide/05-crash-and-restart.md.
On open, the appender recovery scan validates the committed stream. If it finds an inconsistency (for example, a committed entry pointing at an empty payload slot), it refuses to open and returns an error instead of risking silent overwrites.
Recovery detects corruption; it does not repair it. The remediation is
always the same: recreate the queue, restoring any needed history from the
export format (QueueTransfer). mmapq-stat --verify reports the exact
location of a framing/header inconsistency for single-message queues. Batch
framing verify is not yet supported.
Platform
Linux x86-64/ARM64; both tested in CI (C suite in both build loops, ASan,
TSan, torture, and the Rust and Python suites). Run bash scripts/test.sh
on your own host.
Bindings
Rust and Python bindings use the same queue files; see the
Rust guide and Python guide. Install them
from crates.io (cargo add mmapq) and
PyPI (pip install mmapq; prebuilt
wheels for Linux x86-64 and ARM64).
License
BSD 3-Clause — see LICENSE.
Copyright (c) 2026, Anton Anufriev, Algoteq Pty Ltd, and contributors.