# Safe Systems Programming Series III: Managing Reliable Sequenced Data in Rust

> Implement an OrderedBuffer in Rust that puts UDP packets back in sequence. A linked list in a ring buffer reorders packets and rejects duplicates.

- Author: Jakub Łabor
- Published: 2026-12-06
- Source: https://suficio.com/blog/2026-12-06-ordered-buffer/

## Reliable Network Buffers

UDP does not guarantee delivery order, so packets can arrive out of sequence. A reliable protocol, like TCP, must reorder the packets that it receives. For this, we need a network buffer that stores packets of different sizes and puts them back in sequence.

This article will implement an `OrderedBuffer` that meets the requirements to consume data from a reliable protocol over UDP:

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

// Receive data into `OrderedBuffer`
buffer.push_with(MTU, |mut view| {
  let written = socket.recv(view.data_mut())?;
  let data = Message::from_bytes(&view.data()[0..written]);
  view.set_sequence_number(data.sequence_number);
  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
> - Packets may arrive out of order

> This article is the final part in the series on designing network buffers. To learn how to implement a simple ring buffer and `UnorderedBuffer`, read the previous two articles in the series:
>
> - [Safe Systems Programming Series I: Zero-Cost Ring Buffers in Rust](https://suficio.com/blog/2025-09-04-ring-buffer/)
> - [Safe Systems Programming Series II: Network Buffers in Rust](https://suficio.com/blog/2025-09-16-unordered-buffer/)

## Network Buffers in Linux

`OrderedBuffer` uses the same two parts as `AF_XDP`: a metadata buffer and a data buffer. [Safe Systems Programming Series II: Network Buffers in Rust](https://suficio.com/blog/2025-09-16-unordered-buffer/#network-buffers-in-linux) explains this design. The RX ring of an `AF_XDP` socket gives the descriptors in the sequence that the packets arrive. The application must put the packets back in the order of their sequence numbers. `OrderedBuffer` does this with a metadata buffer that is a linked list in a ring buffer. The ring buffer gives better memory locality.

![Metadata buffer represented as a linked list indexing into a ring buffer of packets](https://suficio.com/blog/2026-12-06-ordered-buffer/images/metadata-buffer-01.drawio.svg)

## Ordered Metadata Buffers

Metadata buffers track the location and length of each packet in the data buffer. `OrderedMetadataBuffer` is a linked list, because a linked list inserts, removes and reorders entries in constant time. A ring buffer, `Ring`, stores the linked list.

```rust
/// Metadata for ordered network packets
pub struct OrderedMetadata {
  sequence_number: u32,
  storage_index: u32,
  storage_length: u32,
  storage_padding: u32,
  metadata_next_index: u32,
}
```

Each `OrderedMetadata` entry holds its own sequence number. `OrderedMetadataBuffer` holds the index of the first and the last entry for efficient insertion and removal.

```rust
/// [`OrderedMetadataBuffer`] that stores [`OrderedMetadata`] as a
/// singly linked list backed by a circular [`Ring`]
#[derive(Debug)]
pub struct OrderedMetadataBuffer<'m> {
  first_index: u32,
  last_index: u32,
  ring: Ring<'m, OrderedMetadata>,
}
```

![Ordered metadata entries in a ring buffer. Each entry points to the next entry. The first index and the last index point to the two ends of the linked list.](https://suficio.com/blog/2026-12-06-ordered-buffer/images/network-buffer-01.drawio.svg)

### Metadata Insertion

`OrderedMetadataBuffer::push_with` allocates an entry in the ring buffer and gives it to the closure. Then `insert_metadata` links the entry into the list. The ring buffer commits the entry only if both steps succeed:

```rust
impl<'m> OrderedMetadataBuffer<'m> {
  pub fn push_with<R, F>(&mut self, f: F) -> Result<R, std::io::Error>
  where
    F: FnOnce(&mut OrderedMetadata) -> Result<R, std::io::Error>,
  {
    // Allocate new metadata conditional on linked list insert success
    self.ring.push_with(|mut view| {
      let res = f(view.data_mut())?;
      Self::insert_metadata(&mut view, &mut self.first_index, &mut self.last_index)?;
      Ok(res)
    })
    // ...
  }
}
```

`insert_metadata` handles four cases. The first three cases take constant time.

When the buffer is empty, we insert the first packet at the head of the buffer:

![An empty metadata ring buffer. The first index and the last index point to the first slot.](https://suficio.com/blog/2026-12-06-ordered-buffer/images/network-buffer-02.drawio.svg)
![Entry 1 in the first slot of the metadata ring buffer. The first index and the last index point to entry 1.](https://suficio.com/blog/2026-12-06-ordered-buffer/images/network-buffer-03.drawio.svg)

`index` is the slot of the new entry. The new entry is at the head of the ring only when the buffer is empty:

```rust
impl<'m> OrderedMetadataBuffer<'m> {
  fn insert_metadata(
    view: &mut RingMutView<'_, 'm, OrderedMetadata>,
    first_index: &mut u32,
    last_index: &mut u32,
  ) -> Result<(), std::io::Error> {
    let index = view.index();
    let ring = view.ring_mut();
    let sequence_number = ring.get(index).unwrap().sequence_number;

    // The buffer is empty if the new element is at the head of the ring
    if ring.head() == index {
      *first_index = index;
      *last_index = index;
      return Ok(());
    }
    // ...
  }
}
```

Next, we receive a packet with a sequence number larger than the sequence number at the last index. We rearrange the linked list so that the last index points to the new packet:

![The ring buffer allocates entry 2 in the second slot. The first index and the last index still point to entry 1.](https://suficio.com/blog/2026-12-06-ordered-buffer/images/network-buffer-04.drawio.svg)
![Entry 1 points to entry 2. The last index now points to entry 2.](https://suficio.com/blog/2026-12-06-ordered-buffer/images/network-buffer-05.drawio.svg)

```rust
fn insert_metadata(/* ... */) -> Result<(), std::io::Error> {
  // ...
  // Insert after the last element
  let last = ring.get_mut(*last_index).unwrap();
  match sequence_number.cmp(&last.sequence_number) {
    Ordering::Less => {}
    Ordering::Equal => return Err(ErrorKind::AlreadyExists.into()),
    Ordering::Greater => {
      last.metadata_next_index = index;
      *last_index = index;
      return Ok(());
    }
  }
  // ...
}
```

Similarly, we can receive a packet with a sequence number smaller than the sequence number at the first index. We insert this packet at the start of the linked list:

![Entry 2 points to entry 3. The ring buffer allocates entry 1 in the third slot. The first index points to entry 2 and the last index points to entry 3.](https://suficio.com/blog/2026-12-06-ordered-buffer/images/network-buffer-06.drawio.svg)
![Entry 1 points to entry 2. The first index now points to entry 1, and the last index still points to entry 3.](https://suficio.com/blog/2026-12-06-ordered-buffer/images/network-buffer-07.drawio.svg)

```rust
fn insert_metadata(/* ... */) -> Result<(), std::io::Error> {
  // ...
  // Insert before the first element
  let first = ring.get_mut(*first_index).unwrap();
  match sequence_number.cmp(&first.sequence_number) {
    Ordering::Less => {
      ring.get_mut(index).unwrap().metadata_next_index = *first_index;
      *first_index = index;
      return Ok(());
    }
    Ordering::Equal => return Err(ErrorKind::AlreadyExists.into()),
    Ordering::Greater => {}
  }
  // ...
}
```

A packet can also have a sequence number between the sequence numbers at the first and the last index. Then we must rearrange multiple metadata entries:

![The linked list holds entries 1, 2 and 4 in this order. The first index points to entry 1 and the last index points to entry 4.](https://suficio.com/blog/2026-12-06-ordered-buffer/images/network-buffer-08.drawio.svg)
![The ring buffer allocates entry 3 in the fourth slot. The linked list still goes from entry 1 to entry 2 to entry 4.](https://suficio.com/blog/2026-12-06-ordered-buffer/images/network-buffer-09.drawio.svg)

This is the only case that walks the linked list. We start at the first index, because the receiver usually waits for the packets near the start of the list:

```rust
fn insert_metadata(/* ... */) -> Result<(), std::io::Error> {
  // ...
  // Walk the linked list from the first element to find the position
  let mut prev_index = *first_index;
  let mut current_index = *first_index;
  loop {
    let current = ring.get_mut(current_index).unwrap();
    match sequence_number.cmp(&current.sequence_number) {
      Ordering::Less => {
        ring.get_mut(index).unwrap().metadata_next_index = current_index;
        ring.get_mut(prev_index).unwrap().metadata_next_index = index;
        return Ok(());
      }
      Ordering::Equal => return Err(ErrorKind::AlreadyExists.into()),
      Ordering::Greater => {}
    }
    prev_index = current_index;
    current_index = current.metadata_next_index;
  }
}
```

If the insertion succeeds, we commit the new metadata entry to the metadata buffer:

![Entry 2 points to entry 3, and entry 3 points to entry 4. The linked list now holds entries 1, 2, 3 and 4 in sequence.](https://suficio.com/blog/2026-12-06-ordered-buffer/images/network-buffer-10.drawio.svg)

Each case returns `ErrorKind::AlreadyExists` when the sequence number is already in the list. Then `push_with` returns the error, and the ring buffer does not commit the entry. Thus the buffer stores each sequence number only once:

![The ring buffer allocates a second packet with sequence number 3 in the fifth slot. It does not commit this entry, because entry 3 is already in the linked list.](https://suficio.com/blog/2026-12-06-ordered-buffer/images/network-buffer-11.drawio.svg)

### Metadata Removal

`OrderedMetadataBuffer` removes entries in the order of the linked list. But the ring buffer can only free entries at its head, and these entries are in the order of arrival. Consider packets that arrive in the order 3, 1 and 2:

![The metadata ring buffer holds entries 3, 1 and 2 in the order of arrival. The linked list goes from entry 1 to entry 2 to entry 3. The head of the ring points to entry 3 and the first index points to entry 1.](https://suficio.com/blog/2026-12-06-ordered-buffer/images/network-buffer-12.drawio.svg)

`pop_with` gives the entry at the first index to the closure. If the closure returns `Some`, `pop_with` moves the first index to the next entry:

```rust
impl OrderedMetadataBuffer<'_> {
  pub fn pop_with<R, F>(&mut self, deallocated: &mut u32, f: F) -> Option<R>
  where
    F: FnOnce(&OrderedMetadata) -> Option<R>,
  {
    let first = self.peek()?;
    let res = f(first)?;
    let sequence_number = first.sequence_number;
    self.first_index = first.metadata_next_index;
    Self::pop_inner(&mut self.ring, deallocated, sequence_number);
    Some(res)
  }
}
```

When we pop 1 and 2, the first index moves to entry 3. The ring buffer cannot free entries 1 and 2 yet, because entry 3 is still at its head:

![The receiver popped entries 1 and 2, but they stay allocated behind entry 3. The head of the ring and the first index point to entry 3.](https://suficio.com/blog/2026-12-06-ordered-buffer/images/network-buffer-13.drawio.svg)

`pop_inner` frees the entries at the head of the ring while their sequence numbers are not larger than the popped sequence number. The receiver pops in sequence order, so it already popped each of these entries. `deallocated` collects the length and padding of each freed entry:

```rust
fn pop_until_inner(ring: &mut Ring<'_, OrderedMetadata>, deallocated: &mut u32, sequence_number: u32) -> u32 {
  let mut count = 0;
  ring.pop_many_with(|entries| {
    for m in entries.iter().take_while(|m| m.sequence_number <= sequence_number) {
      count += 1;
      *deallocated += m.storage_length + m.storage_padding;
    }
    count
  });
  count
}
```

`Ring::pop_many_with` only gives the entries from the head to the end of the ring. When the freed entries continue past the end, `pop_inner` does a second pass from the start of the ring:

```rust
fn pop_inner(ring: &mut Ring<'_, OrderedMetadata>, deallocated: &mut u32, sequence_number: u32) {
  *deallocated = 0;
  let window = ring.full_tail_window();
  let count = Self::pop_until_inner(ring, deallocated, sequence_number);
  // The freed entries continue at the start of the ring
  if count == window {
    Self::pop_until_inner(ring, deallocated, sequence_number);
  }
}
```

> `pop_inner` must read `Ring::full_tail_window` before the first pass. The first pass moves the head of the ring, so the window that it returns after the pass is a different window. If the second pass compares against that window, it can skip entries that are ready to free. Then the list is empty, but the ring still holds entries, so `peek` follows a stale index.

When we pop 3, the ring buffer frees all three entries together:

![The ring buffer freed all entries. The head of the ring points to the fourth slot.](https://suficio.com/blog/2026-12-06-ordered-buffer/images/network-buffer-14.drawio.svg)

> Without a reset, the head of the empty ring stays at the fourth slot. The ring buffer moves its head back to the start when it becomes empty, so the next entries reuse the same cache lines. [Padding Packet Data](https://suficio.com/blog/2025-09-16-unordered-buffer/#padding-packet-data) explains the concept.
>
> ![The empty metadata ring buffer. Its head is back at the first slot.](https://suficio.com/blog/2026-12-06-ordered-buffer/images/network-buffer-15.drawio.svg)

## Ordered Network Buffers

`OrderedBuffer` combines `OrderedMetadataBuffer` with a data buffer, in the same way as `UnorderedBuffer`. The data buffer stores the packets in the order of arrival. The metadata buffer links them in sequence order:

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

![A metadata ring buffer above a data buffer. The data buffer holds packets 3, 1 and 2 in the order of arrival. Each metadata entry points to the start and the end of its packet. The linked list goes from entry 1 to entry 2 to entry 3.](https://suficio.com/blog/2026-12-06-ordered-buffer/images/ordered-buffer-01.drawio.svg)

`OrderedBuffer::push_with` handles the tail of the data buffer in the same way as `UnorderedBuffer::push_with`. [Padding Packet Data](https://suficio.com/blog/2025-09-16-unordered-buffer/#padding-packet-data) explains this procedure. The only addition to `PushView` is the sequence number, which the closure reads from the packet:

```rust
impl PushView<'_, '_> {
  /// Set sequence number of element
  pub fn set_sequence_number(&mut self, sequence_number: u32) -> &mut Self {
    self.metadata.set_sequence_number(sequence_number);
    self
  }
}
```

The data allocation happens inside the metadata allocation, so that the closure can write the packet and set its sequence number together:

```rust
impl<'s> OrderedBuffer<'_, '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
    let res = self.receive_ring.push_with(|metadata| {
      self.storage_ring.push_many_with(|view| {
        metadata.set_index(view.index());
        f(PushView { metadata, view })
      })
    });
    // ...
  }
}
```

> The data buffer commits the packet before `insert_metadata` runs. If `insert_metadata` rejects a duplicate, the metadata buffer does not commit the entry, but the packet stays in the data buffer. No metadata entry owns these bytes:
>
> ![Entries 1 and 3 own their packets in the data buffer. The bytes of a duplicate packet 3 follow them, but the metadata buffer rejected its entry, so no entry owns these bytes.](https://suficio.com/blog/2026-12-06-ordered-buffer/images/ordered-buffer-02.drawio.svg)
>
> `push_with` must release the bytes that the rejected packet left at the end of the data buffer:
>
> ```rust
> fn push_with_inner(/* ... */) -> Result<R, std::io::Error> {
>   // The length of the data buffer before the allocation
>   let storage_len = self.storage_ring.len();
>   // ...
>   if res.is_err() {
>     let leaked = self.storage_ring.len() - storage_len;
>     self.storage_ring.truncate_many_end(leaked).unwrap();
>   }
>   res
> }
> ```

`OrderedBuffer::pop_with` reads the packet at the first index. Then it frees the bytes that `pop_inner` collected in `deallocated`:

```rust
impl OrderedBuffer<'_, '_> {
  pub fn pop_with<R, F>(&mut self, f: F) -> Option<R>
  where
    F: FnOnce(&[u8]) -> Option<R>,
  {
    let deallocated = &mut 0;
    let res = self.receive_ring.pop_with(deallocated, |m| {
      let data = self.storage_ring.get_many(m.index(), m.length()).unwrap();
      f(data)
    })?;
    self.storage_ring.truncate_many_head(*deallocated).unwrap();
    Some(res)
  }
}
```

After we pop 1 and 2, the data buffer still holds their bytes, because packet 3 is at its head:

![The receiver popped entries 1 and 2 and their packets, but they stay allocated behind entry 3 and packet 3.](https://suficio.com/blog/2026-12-06-ordered-buffer/images/ordered-buffer-03.drawio.svg)

When we pop 3, `deallocated` holds the length of all three packets, and the data buffer frees them together.

## Receiving Ordered Messages

The receiver pushes each packet into `OrderedBuffer`. Then it pops packets while the first entry holds the next sequence number, `next_sequence_number`:

```rust
fn receive(socket: &mut UdpSocket, buffer: &mut OrderedBuffer<'_, '_>) {
  let mut next_sequence_number = 1;
  loop {
    // Receive a packet into the buffer, as in the first example
    let res = buffer.push_with(MTU, |mut view| {
      let written = socket.recv(view.data_mut())?;
      let data: &Message = from_bytes(&view.data()[0..written]);
      view.set_sequence_number(data.seq);
      view.set_length(written as u32);
      Ok(())
    });
    if let Err(err) = res {
      match err.kind() {
        std::io::ErrorKind::WouldBlock | std::io::ErrorKind::AlreadyExists => {}
        _ => return,
      }
    }

    // Deliver every message that is next in sequence
    loop {
      let res = buffer.pop_with(|message| {
        let data = Message::from_bytes(message);
        match data.sequence_number.cmp(&next_sequence_number) {
          // Already received this sequence number, returns `Some`
          // so `pop_with` removes the stale packet
          Ordering::Less => Some(()),
          Ordering::Equal => {
            next_sequence_number += 1;
            Some(())
          }
          // Missing packet, closure returns `None` so packet stays
          // in the buffer until the missing packet arrives
          Ordering::Greater => None,
        }
      });
      if res.is_none() {
        break;
      }
    }
  }
}
```

> This receiver cannot recover a lost packet. If a packet never arrives, the receiver keeps the later packets in the buffer until the buffer is full. A reliable protocol must also request and retransmit lost packets, for example with negative acknowledgements (NACK).
>
> - [RFC 5401](https://www.rfc-editor.org/rfc/rfc5401) describes the building blocks of multicast protocols that use NACK.

## Testing

Our integration test runs the receivers on an unreliable network. A transmitter sends numbered messages to two receivers. One receiver uses `OrderedBuffer`, and the other receiver uses `UnorderedBuffer`. On the way, `netem` delays the messages, changes their order and copies some of them:

![transmit_ordered sends through netem to the multicast group 239.255.0.1:4444. receive_ordered and receive_unordered receive from this group.](https://suficio.com/blog/2026-12-06-ordered-buffer/images/integration-test-01.drawio.svg)

The test does not drop messages, because our receiver cannot recover a lost message yet.

> `netem` (Network Emulator) is a queueing discipline of the Linux traffic control tool, `tc`. It changes the packets that leave a network interface. It can delay, drop, duplicate, corrupt and reorder packets. The transmitter adds `netem` to its network interface:
>
> ```sh
> tc qdisc add dev eth0 root netem delay 20ms 10ms reorder 25% 50% duplicate 20%
> ```
>
> - `delay 20ms 10ms`: Each packet waits for 20 ms plus a random jitter. The jitter adds or removes up to 10 ms from the delay. Thus each packet gets a different delay, and the jitter alone reorders packets.
> - `reorder 25% 50%`: `netem` sends 25% of the packets without the delay. These packets arrive before packets that the transmitter sent earlier. The second value is the correlation with the previous packet.
> - `duplicate 20%`: `netem` sends a second copy of 20% of the packets.
>
> For example, `netem` can change the order of six packets like this:
>
> ![Six packets sent in the order 1 to 6 arrive in the order 1, 3, 2, 3, 5, 4 and 6. The second copy of packet 3 is a duplicate.](https://suficio.com/blog/2026-12-06-ordered-buffer/images/netem-01.drawio.svg)

In one run, the transmitter sends 20 messages. `UnorderedBuffer` delivers the messages in a mixed order:

```text
received | { seq: 4 }
received | { seq: 6 }
received | { seq: 12 }
...
received | { seq: 1 }
received | { seq: 5 }
```

`OrderedBuffer` delivers each message once and in the correct order:

```text
received | { seq: 1 }
received | { seq: 2 }
received | { seq: 3 }
...
received | { seq: 19 }
received | { seq: 20 }
```

## Conclusion

In this article, we implemented an `OrderedBuffer` that puts UDP packets back in sequence. Its metadata buffer is a linked list in a ring buffer. Thus it inserts packets in any order, and frees memory in the order of arrival.

The receiver delivers each sequence number once and in order, and `netem` lets us test this behavior on an impaired network. A reliable protocol must also recover lost packets, for example with negative acknowledgements and retransmission.
