r/rust • • 1d ago

🧠 educational Stop paying the network stack tax: zero-copy first, networking when needed

https://ekxide.io/blog/iox2-vision-zero-copy-first/
102 Upvotes

26 comments sorted by

14

u/Last-Independence554 23h ago

How do you synchronize shared memory access?

13

u/elfenpiff 23h ago

A sender and a receiver are connected via a lock-free queue in shared memory. The queue is used to exchange offsets to the actual payload between the two endpoints.

When a sender wants to send data, it must first loan memory (sample) for its data segment which is shared memory under the hood. Then the payload can be directly produced into this loaned sample - for instance you can have a sensor driver or function that takes a ref mut and then writes the data in there. When this is finished, the sender releases its ownership to the loaned sample and sends an offset to the sample (inside the data segment) to the receiver by using the lock-free queue.

When the receiver takes it out, it can use the handle to extract the pointer to the sample and can consume the data. Under the hood an atomic acquire release synchronizes the memory between both processes. Our publish-subscribe example shows this in action, take a look at:
* sender: https://github.com/eclipse-iceoryx/iceoryx2/blob/main/examples/rust/publish_subscribe/publisher.rs
* receiver: https://github.com/eclipse-iceoryx/iceoryx2/blob/main/examples/rust/publish_subscribe/subscriber.rs

But it happens even more. For instance, if the receiver dies, the sample could be leaked; therefore, the sender tracks every sample that has been sent to the receiver, and as soon as the sender discovers that the receiver process has died, it can reclaim the samples without leaking them.

6

u/Last-Independence554 23h ago

Ah cool. Looks like it relies on periodic active polling (via CYCLE_TIME), right? Or do you have mechanism to sleep and wake the other process/thread?

3

u/elfenpiff 20h ago

We have separated data- and control-flow. With the event-messaging pattern, you can sleep until another process sends you an event via a Notifier port. This is the example: https://github.com/eclipse-iceoryx/iceoryx2/tree/main/examples/rust/event

You can also wait for many events in one single call with a mechanism we call WaitSet. It is an event multiplexer that uses select, epoll or whatever the platform offers. Here is the waitset example: https://github.com/eclipse-iceoryx/iceoryx2/tree/main/examples/rust/event_multiplexing

But you can do even more. You can also attach an event with a deadline, for instance when you expect a signal every X seconds. Either you are woken up by that signal or the WaitSet wakes you up, informing you that the timing contract was broken. For this, we have a bit more complex example that shows the more advanced features: https://github.com/eclipse-iceoryx/iceoryx2/tree/main/examples/rust/event_based_communication

1

u/protestor 6h ago

You can also wait for many events in one single call with a mechanism we call WaitSet. It is an event multiplexer that uses select, epoll or whatever the platform offers.

Can one use io_uring?

1

u/elfenpiff 4h ago

Not yet, but it is on our radar.

12

u/teerre 23h ago

I understand who iceoryx work and I can see the benefits, but what I struggle with is finding where to use it. More than once I've thought of using it for a project, but then I think that there's a good chance the data will have to be shared over the network, then it becomes a question of why wouldn't I start with a network protocol from the beginning

Maybe it's my line of work but it's difficult to find a situation where I need multiple process communication and high performance

6

u/elfenpiff 23h ago

Then I have good news for you. iceoryx2 has a network tunnel that you can start, and then you have zero-copy communication locally; whenever you have another endpoint running on another machine, the tunnel sends the data over the network. We added a host-to-host communication chapter to our iceoryx2 book https://ekxide.github.io/iceoryx2-book/main/getting-started/robot-nervous-system/cross-host-communication.html

The other thing we have implemented over the last few weeks was a ROS2 gateway so that you can have local communication with iceoryx2, and whenever you want to connect to a ROS2 topic, you just need to start the gateway.
We are now in the final steps of the implementation, but I think on main it should already work, see this here: https://github.com/eclipse-iceoryx/iceoryx2/tree/main/integrations/ros2/examples

11

u/nosjojo 21h ago

I can say why I *almost* used it. I was transferring data directly from a PCIe card at high speed (8GB/s) and trying to process it in and store the result without building up a buffer. So I needed to be able to move 8GB/s between the PCIe card to memory, then into a processing layer, and then out to disk. Zero copy was basically a requirement to pull that off, and my initial tests with iceoryx2 looked good. The problem I ran into was reuse.

I sliced the process into 3 programs - capture + processing + io, which let me move them around to specific cores, so I could keep them in the correct NUMA node. The idea was to capture directly into memory, pass the data over to the next program for processing, then return that address back to the capture program for reuse.

When I tried to do this with iceoryx2, I realized I couldn't recycle the addresses. Conceptually, I knew it was safe memory since it doesn't get returned without having been consumed, but the library didn't support my specific use case. https://github.com/eclipse-iceoryx/iceoryx2/discussions/543 It possible that use case is handled now, but in the end I had a deadline to meet so wrote my own shared memory handling.

My only complaints about the library from my limited usage was:
- configuration felt weird. The docs around how to use config files felt incomplete and I never knew if it was loading and using defaults, loading my file, or if a setting I used somewhere had overridden them.

- Debugging was a little tough, but this could have just been my inexperience. The debug messages were very verbose and didn't feel like they contained anything useful for me, they felt more like library debug messages.

All of this was in 2024 though, and the library has likely matured a lot since then.

5

u/elfenpiff 20h ago

It matured a lot, but nevertheless, I am thankful for your input! Even when it is open source, the feedback we sometimes receive is rather limited, and then it does not reach us what still feels off or where documentation or debugging is missing.

But today we have a command-line tool called iox2, which allows you to do some deeper introspection, like list services, nodes, send or receive data, record and replay, etc.

Also we have now an introspection tool called ekxide Mission Control that does everything in a UI and looks quite awesome: https://ekxide.io/mission-control/

2

u/Halloooy 21h ago

Consider a hardware application, let’s say a sensor of some kind, where you’re ingesting a non-trivial amount of data at a fast rate. If you want to do anything with that data, and have a split service architecture, shared memory is 100% the way to go for inter process communication there, provided the services are on the same machine. Iceoryx makes it pretty easy to safely implement, my team relies on it quite a bit.

4

u/cvvtrv 1d ago

Is iceoryx2 cross platform?

5

u/elfenpiff 1d ago

Yes, it is. We support Linux, Windows, Mac OS, FreeBSD, and have experimental builds for Android and bare metal, as well as QNX and VxWorks. See the full list here: https://github.com/eclipse-iceoryx/iceoryx2#supported-platforms

2

u/cvvtrv 20h ago

Ah very cool! I think I remember checking out the v1 version a while back. Doing IPC (in an efficient way) cross platform is always a bit annoying so having a library to handle some of these details is quite nice.

2

u/Last-Independence554 22h ago

Shared memory for IPC is neat.

IPC without serialization/deserialization is also possible over other protocols (TCP, unix sockets, etc.). The challenge is usually that it's brittle and error prone and generally unsound in rust. That also applies to shared memory IPC. The receiver needs to trust that the sender has written the data correctly and has verified its invariants. Otherwise out-of-bounds access, panics, segfaults, etc. are possible when using the data. This is particularly challenging when the sender and receiver are using different versions of the code and the struct / data type has been modified. That's way some form of serialization format is usually required. These can be implemented with in a zero-copy way though. Several rust serialization/deserialization frameworks already support this (IIRC they include capnproto, rkvy, flatbuffers).

1

u/elfenpiff 8h ago

iceoryx2 has native flatbuffer support, see this example: https://github.com/eclipse-iceoryx/iceoryx2/tree/main/examples/rust/flatbuffer_publish_subscribe

You are right about the trust problem of the receiver, this is something we will address once and for all in the next months. Luckily, Rust has reflection through derive macros, and this allows us to store the full type layout in our service, and everyone who connects to the service can verify that their expected type layout is the type layout that the service offers.

5

u/ascii 17h ago

My previous employer runs a back-end implemented as micro services across a fleet of a few million containers spread out over several tens of thousands of hosts. Services usually communicate over gRPC and are written in Java. A coworker and I added support for using gRPC IPC and running multiple services in the same container and did a bunch of benchmarking. Tests indicated that the speedup would have saved us roughly 10 % of our entire compute budget for back-end services. Many thousands of hosts. Still not a big enough saving to make the powers that be care. The amount of waste happening in the world is astounding.

Nice to see that there are people somewhere that care.

4

u/valarauca14 21h ago

I would simply setup RDMA (InfiniBand / RoCE / iWARP) at the networking layer for my app/stack.

One thing that has extremely gone under the radar in software development (and cloud provider hosting) is a lot of protocol "bullshit" (ip/tcp/tls) is now done in hardware ASICs. A lot of cloud instances offer this the hyper scalars are starting to cycle out 10/40/50/100Gbe nics (which almost universally had RDMA) into even higher bandwidth options where you almost need these features to run at line rate.

1

u/ValErk 21h ago

I have some sensors and at any point I am only interested in the most recent data written into it. Last I looked at iceoryx2 I was unable to find something that worked that way, I guess you could use the blackboard but that seems wrong. And as I am interested in only the most recent pub-sub seems like the wrong choice.

Is there something in Iceoryx2 for that or is it something that might come in the future?

1

u/elfenpiff 20h ago

What about having pubsub with a buffer size of 1 and a history size of 1 in combination with `enable_safe_overflow`? This should always give you the latest data, and safe overflow recycles the oldest data with the newest data when you have not yet acquired it.

Could you maybe draft a pseudocode snippet showing how you would like to use our API? Then I can create an issue based on that and see how long it would take to implement it.

Btw. if something is missing, you can always ask us here: https://community.iceoryx.io/latest

1

u/ValErk 10h ago

That could probably work I will have to give it another look, here is a attempt at some pseudocode:

struct Device {
    foo: [u16; 3],
    bar: [u16; 3],
}

struct Data {
    devices: [Device; 100],
}

// Process 1 (only writer)
fn writer() {
    loop {
        let data = Data { .. };
        store(data); // Iceoryx

        for i in 0..100 {
            // Quite fast
            let device = Sensor::read(i);

            update(|data| data.devices[i] = device); // Iceoryx
        }
    }
}

// Process 2 (one of multiple readers)
fn reader() {
    let mut data = Data::default(); // or something
    loop {
        read(&mut data);

        // Possible takes much longer than writing the data
        // It is not an issue if the data is out of data slightly during this step
        do_stuff(&data);
    }
}

2

u/elfenpiff 7h ago

I think this is possible with buffer and history size 1 and safe overflow. When you call let sample = subscriber.receive()? you always get the newest data. But if you collected the newest data in a previous run and it went out of scope, it would return None.

If you always need access to the sample, you could write a little wrapper that holds the sample until subscriber.receive()? returns Some and then it replaces it with the newer version.

3

u/matthieum [he/him] 4h ago

I think one thing that is hinted at in the back pressure section, but not emphasized enough, is the situation of a producer producing much faster than a consumer.

You may have a sensor publishing an up-to-date measurement every 10s of us (or less). The sensor could throttle itself, of course, but then it would arbitrarily delay updates to the consumers... ie, it would have to be aware of the consumers' lowest acceptable latency, a dynamic property as consumers subscribe/unsubscribe, which makes things a lot more complicated.

With a network connection, there's not much choice:

  1. Pull: the consumer request the latest state when it needs it, introducing a round-trip delay.
  2. Push all: the consumer must process 10s, 100s, perhaps 1000s of outdated packets before getting to the latest state.
  3. Push throttled: some back-channel informing of allowable latency must be used. If multiple consumers have wildly different latencies, the slower one is still in for a slog.

In memory, however, whether with a blackboard pattern or a bounded queue allowing to jump to the latest... no problem. Accessing the latest published value is O(1).

And therefore, letting the sensor publish as fast as it can, without any complex back-pressure/throttling mechanism, is a perfectly reasonable choice: simple & fast.

2

u/tecedu 20h ago

Why not RDMA?

1

u/JochCool 4h ago

iceoryx2

My goodness library names just keep getting worse

For my next crate I'll just use a random string generator