# Safe Systems Programming Series II: Network Buffers in Rust

> Implement an UnorderedBuffer in Rust that stores UDP packets of unknown size in one contiguous memory allocation, with constant-time operations.

- Author: Jakub Łabor
- Published: 2025-09-16
- Source: https://suficio.com/blog/2025-09-16-unordered-buffer/

## Network Buffers

Network applications often receive data packets of different sizes, and do not know the size of a packet until they receive it. The buffer that stores these packets must use little memory and add little processing time.

This article will implement an `UnorderedBuffer`, which stores received packets in one contiguous memory allocation.

`UnorderedBuffer` will meet the requirements to receive data from a `UdpSocket` and later consume it within the application:

```rust
let mut socket: std::net::UdpSocket;
let mut buffer: UnorderedBuffer<'_, '_>;

// Receive data into `UnorderedBuffer`
buffer.push_with(MTU, |mut view: PushView<'_, '_>| {
  // Handle fallible operations during push operation
  let written = socket.recv(view.data_mut())?;
  // Handle unknown insertion length
  view.set_length(written as u32);
  Ok(())
});
```

> Recall the requirements for a network buffer:
>
> - The buffer stores network bytes in the same memory allocation
> - The length of a packet is unknown in advance
> - Receiving a packet can fail

> UDP does not guarantee delivery order, so packets can arrive out of sequence. `UnorderedBuffer` stores packets in the order that they arrive. It does not reorder them.
>
> The next article in this series extends the current framework to implement an `OrderedBuffer` that can buffer and reorder sequenced UDP traffic:
>
> [Safe Systems Programming Series III: Managing Reliable Sequenced Data in Rust](https://suficio.com/blog/2026-12-06-ordered-buffer/)

## Network Buffers in Linux

Linux has several interfaces to receive network packets. For our design, the most important of these is `AF_XDP`. An `AF_XDP` socket bypasses most of the kernel network stack. It writes received packets into the UMEM, a contiguous area of memory that the application registers with the kernel. For each packet, the kernel writes a descriptor that holds the offset and length of the packet in the UMEM. The kernel puts the descriptors in a ring buffer, the RX ring.

`AF_XDP` divides a network buffer into two parts:

- **Metadata buffer**: the RX ring, with one descriptor for each packet.
- **Data buffer**: the UMEM, which contains the packet data.

![A metadata buffer with one entry for each packet. Each entry points to the start and the end of its packet in one contiguous data buffer.](https://suficio.com/blog/2025-09-16-unordered-buffer/images/metadata-buffer-01.drawio.svg)

`UnorderedBuffer` uses the same two parts, with one difference. The UMEM divides its memory into frames of fixed size. We put packets of different lengths one after the other in a ring of bytes. When a packet does not fit at the end of the buffer, we add padding. The [Padding Packet Data](#padding-packet-data) section shows this procedure.

Because `UnorderedBuffer` does not put packets back in sequence, its metadata buffer is also a ring buffer.

> Regular sockets receive packets as `struct sk_buff` (socket buffer). Each `sk_buff` holds the metadata of one packet. The kernel allocates a separate data buffer for each packet. The `sk_buff` points into this data buffer with its `head`, `data`, `tail` and `end` pointers. The network stack adds protocol headers in the headroom between `head` and `data`. This does not copy the packet data.
>
> The receive queue of a socket is a doubly linked list of `sk_buff` structures. When the application calls `recv`, the kernel copies the packet data into the buffer of the application. Then the kernel frees the `sk_buff`.
>
> Our buffers receive packets from a regular UDP socket. Thus each packet arrives as an `sk_buff`, and `recv` copies the packet into our data buffer.
>
> ![A receive queue of sk_buff structures in a doubly linked list. Each sk_buff points into a separate data buffer with the head, data, tail and end pointers.](https://suficio.com/blog/2025-09-16-unordered-buffer/images/sk-buff-01.drawio.svg)
>
> For more detail on both designs, see the Linux kernel documentation:
>
> - [struct sk_buff - The Linux Kernel documentation](https://docs.kernel.org/networking/skbuff.html)
> - [AF_XDP - The Linux Kernel documentation](https://docs.kernel.org/networking/af_xdp.html)

## Metadata Buffers

Metadata buffers track the location and length of each packet in the data buffer. `UnorderedMetadataBuffer` uses a ring buffer, `Ring`, because it needs constant-time insertion and removal. Ring buffers also have better memory locality than linked lists.

```rust
/// Metadata for unordered network packets
pub struct UnorderedMetadata {
  storage_index: u32,
  storage_length: u32,
}

/// [`UnorderedMetadataBuffer`] that stores [`UnorderedMetadata`]
pub struct UnorderedMetadataBuffer<'m> {
  ring: Ring<'m, UnorderedMetadata>,
}
```

![Metadata buffer represented as a ring buffer](https://suficio.com/blog/2025-09-16-unordered-buffer/images/network-buffer-01.drawio.svg)

> If you want to learn more about how ring buffers work and how to implement them, read the previous article in this series:
>
> [Safe Systems Programming Series I: Zero-Cost Ring Buffers in Rust](https://suficio.com/blog/2025-09-04-ring-buffer/)

## Unordered Buffer

An unordered buffer combines a metadata buffer and a data buffer. This section shows how it allocates and deallocates packet data.

```rust
pub struct UnorderedBuffer<'m, 's> {
  receive_ring: UnorderedMetadataBuffer<'m>,
  storage_ring: Ring<'s, u8>,
}
```

### Allocating Packet Data

Allocating packet data is a three-phase procedure:

1. Make sure that the data buffer has enough space for a packet of the maximum data size
2. Allocate the packet in the data buffer
3. Allocate a metadata entry in the metadata buffer

The maximum data size is the Maximum Transmission Unit (MTU). The MTU is the largest packet that the network can send. For Ethernet, the MTU is 1500 bytes. The IP and UDP headers use part of the MTU, so the MTU is a safe maximum for the UDP payload. Consider an example with one packet already allocated:

![Metadata buffer and data buffer with single metadata and packet already allocated](https://suficio.com/blog/2025-09-16-unordered-buffer/images/network-buffer-02.drawio.svg)

First, we preallocate an area of the data buffer for the maximum data size:

![Metadata buffer and data buffer with a temporary region pre-allocated encompassed by PushView](https://suficio.com/blog/2025-09-16-unordered-buffer/images/network-buffer-03.drawio.svg)

![Metadata buffer and data buffer with temporary region shortened to actual packet data](https://suficio.com/blog/2025-09-16-unordered-buffer/images/network-buffer-04.drawio.svg)

Then we commit the allocation to the metadata buffer:

![Metadata buffer and data buffer with two packets committed](https://suficio.com/blog/2025-09-16-unordered-buffer/images/network-buffer-05.drawio.svg)

We implement `UnorderedBuffer::push_with` from these steps:

```rust
impl<'s> UnorderedBuffer<'_, 's> {
  /// Push data into receive buffer of [`UnorderedBuffer`]
  pub fn push_with<R, F>(&mut self, max_size: u32, f: F) -> Result<R, std::io::Error>
  where
    F: FnOnce(PushView<'_, 's>) -> Result<R, std::io::Error>,
  {
    let tail_window = self.storage_ring.empty_tail_window();
    // Check if max size will fit in ring tail
    if tail_window >= max_size {
      self.push_with_inner(f)
    } else {
      Err(ErrorKind::WouldBlock.into())
    }
  }
}
```

We also implement `UnorderedBuffer::push_with_inner`. It allocates metadata only if the allocation in the data buffer succeeds:

```rust
impl<'s> UnorderedBuffer<'_, 's> {
  fn push_with_inner<R, F>(&mut self, f: F) -> Result<R, std::io::Error>
  where
    F: FnOnce(PushView<'_, 's>) -> Result<R, std::io::Error>,
  {
    // Allocate metadata conditional on storage allocation succeeding
    self.receive_ring.push_with(|metadata: &mut UnorderedMetadata| {
      // Allocate message in storage
      self.storage_ring.push_many_with(|view: RingManyMutView<'_, 's, u8>| {
        metadata.set_index(view.index());
        let res = f(PushView { metadata, view })?;
        Ok(res)
      })
    })
  }
}
```

> During allocation, we use `PushView`. `PushView` is a temporary view into the buffer. It lets the caller tell the buffer the packet length.
>
> ```rust
> pub struct PushView<'a, 's> {
>   metadata: &'a mut UnorderedMetadata,
>   view: RingManyMutView<'a, 's, u8>,
> }
> ```
>
> ```rust
> impl PushView<'_, '_> {
>   /// Set length of written data
>   pub fn set_length(&mut self, len: u32) -> &mut Self {
>     self.metadata.set_length(len);
>     self.view.set_modified(len);
>     self
>   }
> }
> ```
>
> Recall the usage example of `UnorderedBuffer::push_with`:
>
> ```rust
> buffer.push_with(MTU, |mut view: PushView<'_, '_>| {
>   let written = socket.recv(view.data_mut())?;
>   view.set_length(written as u32);
>   Ok(())
> });
> ```
>
> To learn more about views or the implementation of `RingManyMutView`, read the previous article in this series:
>
> [Safe Systems Programming Series I: Zero-Cost Ring Buffers in Rust](https://suficio.com/blog/2025-09-04-ring-buffer/)

### Deallocating Packet Data

Deallocating packet data is simpler:

1. Deallocate the metadata entry, which holds the number of bytes to deallocate from the data buffer
2. Deallocate these bytes from the data buffer

![Metadata buffer and data buffer with two packets allocated](https://suficio.com/blog/2025-09-16-unordered-buffer/images/network-buffer-06.drawio.svg)

![Metadata buffer and data buffer with the first metadata element deallocated showing that two bytes must be deallocated from the data buffer](https://suficio.com/blog/2025-09-16-unordered-buffer/images/network-buffer-07.drawio.svg)

We can implement the metadata deallocation using `UnorderedMetadataBuffer::pop_with`:

```rust
impl UnorderedMetadataBuffer<'_> {
  /// Pop next metadata from [`UnorderedMetadataBuffer`]
  pub fn pop_with<R, F>(&mut self, deallocated: &mut u32, f: F) -> Option<R>
  where
    F: FnOnce(&UnorderedMetadata) -> Option<R>,
  {
    self.ring.pop_with(|m| {
      let data = m.data();
      let res = f(data)?;
      *deallocated = data.storage_length;
      Some(res)
    })
  }
}
```

![Metadata buffer and data buffer after we deallocate the first packet from both buffers. Deallocated and Modified are both 2.](https://suficio.com/blog/2025-09-16-unordered-buffer/images/network-buffer-08.drawio.svg)

Finally, we implement `UnorderedBuffer::pop_with`:

```rust
impl UnorderedBuffer<'_, '_> {
  /// Pop data from receive buffer of [`UnorderedBuffer`]
  pub fn pop_with<R, F>(&mut self, f: F) -> Option<R>
  where
    F: FnOnce(&[u8]) -> Option<R>,
  {
    // Remove metadata conditional on storage removal succeeding
    let deallocated = &mut 0;
    let res = self.receive_ring.pop_with(deallocated, |m| {
      // SAFE: `storage_index` is a valid index into the storage buffer
      let data = self.storage_ring.get_many(m.index(), m.length()).unwrap();
      f(data)
    })?;
    // SAFE: `deallocated` does not exceed the length of the storage buffer
    self.storage_ring.truncate_many_head(*deallocated).unwrap();
    Some(res)
  }
}
```

### Padding Packet Data

We must also handle one more case. When the tail of the buffer has too little space for a packet, we pad the last element in the data buffer. The buffer then wraps, and the next allocation starts at the head.

![Metadata buffer and data buffer with single packet allocated near the tail of the buffer](https://suficio.com/blog/2025-09-16-unordered-buffer/images/network-buffer-09.drawio.svg)

![Metadata buffer and data buffer. Padding fills the tail of the data buffer after the first packet. The temporary allocation for the next packet starts at the head.](https://suficio.com/blog/2025-09-16-unordered-buffer/images/network-buffer-10.drawio.svg)

![Metadata buffer and data buffer with the second packet allocated at the head of the buffer](https://suficio.com/blog/2025-09-16-unordered-buffer/images/network-buffer-11.drawio.svg)
> To track the padding of each packet, we must add a third field to `UnorderedMetadata`:
>
> ```rust
> pub struct UnorderedMetadata {
>   storage_index: u32,
>   storage_length: u32,
>   storage_padding: u32,
> }
> ```
>
> ```rust
> impl UnorderedMetadata {
>   /// Pad [`UnorderedMetadata`] element with empty padding
>   pub fn pad(&mut self, padding: u32) -> &mut Self {
>     self.storage_padding += padding;
>     self
>   }
> }
> ```
>
> Deallocation must now release the padding together with the packet, so `UnorderedMetadataBuffer::pop_with` adds it to the deallocated length:
>
> ```rust
> impl UnorderedMetadataBuffer<'_> {
>   /// Pop next metadata from [`UnorderedMetadataBuffer`]
>   pub fn pop_with<R, F>(&mut self, deallocated: &mut u32, f: F) -> Option<R>
>   where
>     F: FnOnce(&UnorderedMetadata) -> Option<R>,
>   {
>     self.ring.pop_with(|m| {
>       let data = m.data();
>       let res = f(data)?;
>       *deallocated = data.storage_length + data.storage_padding;
>       Some(res)
>     })
>   }
> }
> ```

> The last metadata entry owns the padding, so `pop_with` frees both together. If the metadata buffer is empty, the padding has no owner and stays allocated:
>
> ![The metadata buffer holds only entry 2, which points to packet 2 at the start of the data buffer. The padding at the tail of the data buffer has no metadata entry.](https://suficio.com/blog/2025-09-16-unordered-buffer/images/network-buffer-12.drawio.svg)
>
> To avoid this, the ring buffer moves its head back to the start when it becomes empty. An empty data buffer then never needs padding. When the buffer empties between packets, each packet also reuses the same cache lines, which improves performance.
>
> ```rust
> impl<'a, T> Ring<'a, T> {
>   /// Remove `len` elements from the head of the ring
>   fn advance_head(&mut self, len: u32) {
>     let head = self.get_idx(len);
>     self.len -= len;
>     // An empty ring moves its head back to the start of the buffer
>     self.head = if self.len == 0 { 0 } else { head };
>   }
> }
> ```

We add the padding to `UnorderedBuffer::push_with`:

```rust
impl<'s> UnorderedBuffer<'_, 's> {
  /// Push data into receive buffer of [`UnorderedBuffer`]
  pub fn push_with<R, F>(&mut self, max_size: u32, f: F) -> Result<R, std::io::Error>
  where
    F: FnOnce(PushView<'_, 's>) -> Result<R, std::io::Error>,
  {
    let tail_window = self.storage_ring.empty_tail_window();
    let head_window = self.storage_ring.window() - tail_window;

    // Check if max size will fit in ring tail
    if tail_window >= max_size {
      self.push_with_inner(f)
    // Check if max size will fit in ring head
    } else if head_window >= max_size {
      // Pad the tail window
      // SAFE: Tail window can always be filled
      self.storage_ring.push_many(tail_window).unwrap();
      // Add padding to the last metadata element. The buffer is not empty, since an
      // empty storage ring has its head at the start and the whole buffer as tail window.
      let last_metadata_index = self.receive_ring.last();
      // SAFE: Buffer is non-empty therefore the last element exists
      let last_metadata = self.receive_ring.get_mut(last_metadata_index).unwrap();
      last_metadata.pad(tail_window);
      // Do not undo the tail padding in the case of failure since `max_size` is not
      // expected to change during runtime as it is often hardware dependent.
      let res = self.push_with_inner(f)?;
      Ok(res)
    } else {
      Err(ErrorKind::WouldBlock.into())
    }
  }
}
```

## Conclusion

In this article, we implemented an `UnorderedBuffer` in Rust to manage network data, especially from UDP sockets. The design uses ring buffers for both the metadata and the packet data. This gives constant-time operations and good memory locality.

The design uses zero-cost abstractions to give an API that is easy to reason about when operations can fail.

In the next article, we will implement an `OrderedBuffer` that reorders sequenced network traffic.
