One block of memory across five languages

Rust writes a buffer and Python reads the same bytes. A working example of shared memory, followed by ten runs against JSON, protobuf and a raw pipe.

On this page

Rust can write a buffer that Python reads without receiving a second copy. C++, Go and Node.js can use views of the same storage too. That is the useful part of shared memory. The programs can stay separate while their data stays in one place. I want to walk through how this works, then measure what it saves against JSON, protobuf and a raw pipe.

Imagine a Rust program has finished a batch of readings. Python needs to analyse them. A Node.js program needs to display them. A familiar approach is to send messages between the programs. With JSON, Rust turns the values into text and the reader turns that text back into values. Protobuf gives us a binary message format. Both can be useful. But all these programs are on the same machine, and the data is already sitting in memory. Reading that existing storage is another option.

Start with the bytes

A process is a running program with its own view of memory. The operating system, or OS, keeps track of which storage that process can access. Normally, a pointer from one process tells another process nothing useful. Even if both programs use Rust, copying the pointer value across does not give the reader access to the producer's data. The language is only part of the story. We also need the operating system to make the storage available in both processes.

What we are going to do is create a named memory object, map it into two processes, and agree what its bytes mean. Rust will publish four numbers. Python will read them through a view of the mapped storage. The complete example and benchmark include everything needed to run this on Linux or macOS. The code excerpts below leave the helper functions in that download, so we can concentrate on one part at a time.

Three address spaces can reach the same pages

A virtual address is the address a process uses to find memory. The operating system translates it to the backing storage. It manages memory in chunks called pages. With a shared mapping, several processes can reach the same backing pages through their own virtual addresses. The diagram shows three such mappings. The arrows describe which storage the programs can access. They do not show the payload travelling between them.

Three address spaces map the same physical pages Rust processVirtual base A*mut u8 Python processVirtual base Bmemoryview Node.js processVirtual base CBuffer Same resident physical pagesPage 0 · Page 1 · Page 2 · Page 3
Three address spaces map the same physical pages

What we understand from this is that sharing the storage does not require sharing an address. Rust might reach a byte through virtual base A and Python through virtual base B. They find the same byte by using the same shared object and the same offset within it. An offset simply counts bytes from the start. This distinction will matter when we get to the adapters. A pointer stays local to its process. A checked offset can describe a location to all the readers.

Three calls set up the mapping

The setup uses three POSIX calls, standard system interfaces available on Linux and macOS. shm_open creates or opens a named shared memory object and returns a file descriptor, the handle used by the OS APIs. A new object starts with zero length. The creator calls ftruncate to set its size. Then mmap makes that storage accessible through an address in the calling process.

Call What it does here
shm_open Create or find the shared object by name
ftruncate Give a newly created object enough space
mmap Map that storage into this process

The Rust Mapping helper makes these calls in order and checks their results. Here are the OS calls inside it. The complete helper also handles failures, closes the descriptor through OwnedFd, and removes an object if setup fails after creating it. OwnedFd is Rust's owning file descriptor type. Dropping it closes that descriptor.

// name is a CString. length and file_length have already been checked.
// SAFETY: name is live and NUL terminated; flags and mode are valid.
let raw_fd = unsafe {
    libc::shm_open(
        name.as_ptr(),
        libc::O_CREAT | libc::O_EXCL | libc::O_RDWR,
        0o600,
    )
};

if raw_fd < 0 {
    return Err(io::Error::last_os_error());
}
// SAFETY: shm_open returned a new descriptor that this helper owns.
let fd = unsafe { OwnedFd::from_raw_fd(raw_fd) };

// SAFETY: fd is writable and live; file_length fits off_t.
if unsafe { libc::ftruncate(fd.as_raw_fd(), file_length) } < 0 {
    return Err(io::Error::last_os_error());
}

// SAFETY: the backing object now contains length bytes.
let raw = unsafe {
    libc::mmap(
        std::ptr::null_mut(),
        length,
        libc::PROT_READ | libc::PROT_WRITE,
        libc::MAP_SHARED,
        fd.as_raw_fd(),
        0,
    )
};
// The helper checks MAP_FAILED before returning an owning Mapping.

What we did here was ask the OS for a new shared object, give it a size, and request a mapping we can read and write. MAP_SHARED allows changes through this mapping to reach the shared backing storage. MAP_PRIVATE would allow private changes through copy on write. Passing a null address lets the OS choose where to put our mapping. Pages can enter RAM as we touch them, and this does not pin them permanently in physical memory.

There are a few details worth keeping in the helper. O_CREAT | O_EXCL makes creation fail if the name already exists, so this writer does not silently reuse an old object. The mode 0o600 limits access to the creating user, subject to the process mask. After mapping succeeds, the descriptor can close while the mapping remains usable. The unsafe blocks are where Rust relies on facts about these OS calls and the memory they return. The wrapper checks the size and results. The application still has to coordinate access with other processes.

Agree on what the bytes mean

Shared memory contains bytes. It does not tell Python that Rust meant an integer, a string or an image. We need a format. I kept this demo small. The first eight bytes contain OSSLMEM1, a magic value that identifies the format and its version. The next eight contain the number of values. The actual values start at offset 16. Each value takes eight bytes and represents an unsigned 64 bit integer.

Offset Bytes Meaning
0 8 Magic and format version
8 8 Number of values, little endian
16 Count multiplied by 8 Unsigned 64 bit values, little endian

Counts and values use little endian byte order, which puts the least significant byte first. The writer and reader must agree on that ordering as well as the field sizes. This frame is our demo format. It is separate from the library's internal metadata page. We will also check the count before trusting it. Knowing where the payload starts is only useful if its claimed length fits inside the mapping.

Rust creates the mapping and publishes a snapshot

The publisher asks the helper to allocate one system page. It prepares the four values 11, 22, 33 and 44, builds the frame, and writes it into the mapping. The following is the main part of that publisher. Its earlier lines query the system page size and check that the frame fits.

let region = Mapping::create(&name, length)?;
let mut frame = Vec::from(*b"OSSLMEM1");
frame.extend_from_slice(&(values.len() as u64).to_le_bytes());
for value in values {
    frame.extend_from_slice(&value.to_le_bytes());
}

// SAFETY: the mapping is large enough and the buffers do not overlap.
// The reader opens it after publication. The payload stays immutable.
unsafe {
    std::ptr::copy_nonoverlapping(
        frame.as_ptr(), region.as_ptr(), frame.len(),
    );
}
println!("{name} {length}");
io::stdout().flush()?;

// Wait until the reader has released its views and mapping.
io::stdin().read_exact(&mut [0_u8; 1])?;
drop(region);

What we did here was finish the entire frame before telling Python it was ready. The line printed to standard output contains the shared object name and its size. It travels through a pipe. Rust then waits for a one byte acknowledgement on standard input. During that wait, it leaves the frame unchanged. This gives the reader a stable snapshot and keeps the creator alive while Python opens the object.

The helper also owns the cleanup. When the Rust Mapping drops, it calls munmap to release its mapping and shm_unlink to remove the name. The code above contains a copy too. It first builds a private Vec, then copies that frame into shared storage. A producer could generate values directly in the mapping. For now, the part we are proving is that Python can consume the published payload without receiving another full copy of it.

Python reads through a memoryview

Python launches the publisher and waits for its ready line. Its open_mapping helper opens that same name through shm_open, checks the backing object's size, and creates a Python mmap. It uses MAP_SHARED and PROT_READ, since this reader has no reason to modify the frame. The helper calls the OS API through ctypes, Python's interface for calling native functions. Python's mmap documentation describes the mapping object and its buffer access.

if sys.byteorder != "little":
    raise RuntimeError("this native numeric view needs a little endian host")

with subprocess.Popen(
    [sys.argv[1]], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
) as writer:
    name, length = writer.stdout.readline().decode().split()
    with open_mapping(name, int(length)) as region:
        with memoryview(region) as frame:
            if bytes(frame[:8]) != b"OSSLMEM1":
                raise ValueError("unexpected format")
            count = int.from_bytes(frame[8:16], "little")
            if count > (len(frame) - 16) // 8:
                raise ValueError("payload exceeds the mapping")
            with frame[16:16 + count * 8].cast("Q") as values:
                assert sum(values) == 110
                print(" ".join(str(value) for value in values))

    writer.stdin.write(b"D")
    writer.stdin.flush()
    if writer.wait(timeout=5) != 0:
        raise RuntimeError("publisher failed")

What we did here was wrap the mapped bytes in a memoryview. A view gives Python access to storage that already exists. Slicing that view selects the payload range. Casting it with Q tells Python to interpret that range as native unsigned 64 bit integers. It still refers to the mapped bytes. Since our frame uses little endian ordering and the cast uses native ordering, the example checks the host's byte order first. The count check rejects a payload that would run past the end of the mapping.

Python checks the magic value, adds the four numbers and prints them. The sum must be 110. Checking the magic creates a tiny temporary bytes value, and iteration creates Python integer values. The memoryview reference explains how views expose an existing buffer. Here, Python never constructs a separate full array of the payload. The nested context managers release the numeric view, the byte view and the mapping in that order. Python then sends the acknowledgement that lets Rust finish.

To try it, extract the download and enter its directory. These commands build the full Rust helper and publisher, then run the Python reader. The output is 11 22 33 44.

cargo build --release --locked --bins --examples
python3 reader.py target/release/examples/publisher

Zero copy needs a boundary

So what did we avoid? Python did not receive a complete payload through the pipe and did not decode a message into another full numeric array. It read the mapped storage through a view. That is the zero copy boundary in this example. Rust still copied its prepared frame into the mapping. The small ready message and acknowledgement still travelled through a pipe. Calling the whole program entirely copy free would hide work that the code clearly does.

Reading also still costs time. Mapping requires OS calls. First access can bring pages into RAM. Later reads use memory bandwidth and CPU caches. If several cores modify nearby bytes, they can create extra cache traffic. Turning the whole view into bytes, calling tobytes, or building a list of every value creates another representation. What I want from a zero copy claim is a clear account of which copy disappeared and which work remains.

The C ABI connects the adapters to the core

We now have Rust and Python reaching the same storage. C++, Go and Node.js need their own local views of it. A C ABI gives Python, Go and C++ a common way to call the mapping library. ABI means application binary interface. It defines the binary calling contract, including how arguments and results cross a function boundary. The exported header contains operations like these.

typedef void *ZincHandle;

int32_t zinc_open(const char *name, ZincHandle *out);
uint8_t *zinc_ptr(ZincHandle handle);
uintptr_t zinc_capacity(ZincHandle handle);
void zinc_close(ZincHandle handle);

The adapter opens a name and receives an opaque handle. Opaque means it can pass that handle back without needing to understand the object behind it. It asks for a pointer and capacity, builds a view, and eventually closes the handle. All of these function calls happen inside the adapter's own process. The handle and returned pointer stay there too. Our standalone demo calls POSIX directly so we can see the underlying mechanism before adding this layer.

Language Local view of the mapped bytes
Rust Raw pointer, with access coordinated by the surrounding code
C++ std::span<std::byte>, a view borrowing the mapping
Python memoryview over the exported buffer
Go []byte, a slice borrowing the mapping
Node.js Buffer backed by the external mapping

These types are different ways to reach the bytes. They do not make a Rust Vec, Python list or JavaScript object into a shared object that every runtime understands. Node's current addon calls the Rust core directly through Node-API, rather than using the exported C functions above. It retains the region while exposing a borrowed buffer. Node-API supports buffers backed by external storage, which lets JavaScript view the mapped payload.

There are two agreements here. The ABI defines the function calls. Our frame format defines the data. Everyone reading the frame must agree on field widths, offsets, alignment, byte order and version. Rust's C representation can help match a C structure on a target ABI. It does not make a heap pointer valid in another process. If one shared record refers to another, I want it to store a checked offset into the region. Each reader combines that offset with its own mapped base address.

Shared storage still needs turns

Our example works because the writer finishes once and then waits. A program that keeps producing new batches needs another rule. The writer must know when readers have finished with the current buffer before overwriting it, or use a queue that assigns separate storage to work still in use. Without that agreement, a reader could see part of one batch and part of the next. Sharing pages does not make a partly written record ready to consume.

The core's notification implementation uses release and acquire operations around a sequence counter. Those operations establish the ordering needed to publish and observe writes. Linux adds futex waiting, which lets a process wait through the kernel when needed. macOS uses a polling and sleep fallback. A notification announces a change. It does not reserve the payload for a slow reader. Ordinary Python assignments are not a substitute for that native synchronization protocol.

The mapping must also outlive every borrowed view. Our Python code releases the views before closing its mmap, and Rust waits for that cleanup before dropping its owner. For name based opening, the creator must keep the name available until readers have opened it. shm_unlink removes that name, while existing mappings can remain usable until their users release them. Reusing the name creates a different object. Nobody should shrink the original backing object while a reader still expects its old size.

The benchmark includes the whole read

Now we can ask what this saves. I measured a persistent Rust producer and Python consumer using the same numeric data through four paths. JSON and protobuf are formats. A pipe is a transport. To make that distinction visible, the benchmark sends both encoded formats through a pipe and also includes a raw pipe baseline.

  • Shared memory copies the prepared Rust vector into a mapping and sends a small ready notice through a pipe.
  • Raw pipe sends the same numeric bytes, with a length prefix and no JSON or protobuf encoding.
  • JSON encodes the values for each request, sends them through the pipe, and decodes them in Python.
  • Protobuf also encodes for each request, uses the pipe, and parses the message in Python.

Every request changes the first value. Python sums every value and checks the count, sequence and total before asking for the next batch. That prevents an old response from passing unnoticed and makes every path consume the full payload. The timer includes the request, publication, consumption, validation and reader object cleanup. It excludes startup, mapping setup and initial vector construction. The shared case touches its pages before timing and includes the producer's copy into the mapping.

I repeated each path and size across ten runs. Each run uses a fresh producer, 20 warmup requests and 100 timed requests. I calculate its average, then average those ten run averages. With equal request counts, that also gives the average of all 1,000 measured requests for that case. For the p95 column, 95 percent of the measured requests finished in that much time or less. One KiB is 1,024 bytes and one MiB is 1,048,576 bytes. The size labels below describe the raw numeric arrays, before encoding.

Path 1 KiB average in µs 1 MiB average in ms 1 MiB p95 in ms
Shared mapping and numeric view 7.59 1.121 1.202
Raw numeric bytes through a pipe 8.19 1.262 1.396
JSON through a pipe 16.58 7.433 7.915
Protobuf through a pipe 10.08 2.487 2.657

These are measurements from an Apple M2 Pro with 16 GiB of RAM, macOS 26.6.2 and 16 KiB pages. The producer used Rust 1.99.0 in release mode, serde_json 1.0.154 and prost 0.14.4. The consumer used Python 3.14.8 and protobuf 7.36.2 with its upb backend. Case order was shuffled and the processes were not pinned to CPU cores. Averages include all timed requests. I did not select the fastest run.

The raw measurements include all 8,000 timed samples, the ten averages for each case and checksums of the source files used. Before this run, I also rebuilt the Rust programs from the downloadable archive, ran the four number example, and repeated the original benchmark. The download keeps the original five run results and that verification run too. Anyone can recompute the averages or run the same workload. Timings will vary with the machine and what else it is doing.

The protobuf message uses packed fixed64 values, which match the raw eight byte numeric width. Its wire format adds a field tag and payload length. Our one MiB raw batch contains 131,072 values and occupies 1,048,576 bytes. Its protobuf payload occupies 1,048,580 bytes. JSON is smaller for these particular small integers, between 806,396 and 806,397 bytes. Packed uint64 would use variable length integers and change this comparison. The schema below makes that choice explicit.

message Batch {
  repeated fixed64 values = 1 [packed = true];
}

To repeat the benchmark after building the example, create a Python environment and install the pinned protobuf package. The default is ten runs, and the command also names that count explicitly.

python3 -m venv .venv
.venv/bin/python -m pip install -r requirements.txt
.venv/bin/python benchmark.py target/release/shared-memory-post --rounds 10 --output results-local.json

What we can learn from the numbers

For the one MiB array, JSON took about 6.6 times as long as the shared path in this test. The average gap between raw pipe and shared memory was about 0.14 milliseconds. What we can learn from this is that the comparison we choose matters. The JSON path pays for encoding, decoding and a different Python representation. The raw pipe path uses the same numeric layout and the same kind of Python view, making it a closer comparison of the transfer paths.

At one KiB, shared memory and raw pipe were close. I would be careful about treating that small difference as a reason to change an application. Every row still includes Python consuming the data, and different containers have different iteration costs. These are timings for the complete example paths. They are not bare IPC latency measurements, a universal ranking of formats, or a benchmark of the library's adapters and native notification path.

Shared memory makes sense to me when the data already wants to be a buffer and several local programs need to use it. A portable message or communication between machines can make JSON or protobuf a better fit. What we did here was keep the programs separate, agree on the bytes, and let the OS give each program access to that storage. To see the same approach across language adapters, check out Zinc under OSS Labs.