Canonical: https://nitride.xyz/docs/receiver/linux-sockets

# Linux sockets and buffers

Shreds arrive in bursts and UDP never resends, so a receiver loses whatever does not fit in its socket buffer. These are the kernel settings and counters that decide how much fits and show what was lost.

## How big is the buffer now?
Start by reading the two limits and the buffer your receiver actually holds. With the receiver running on port 9000:

```sh file="terminal"
sysctl net.core.rmem_max net.core.rmem_default
ss -ulmn 'sport = :9000'
```

In the `skmem:(...)` part of the `ss` output, `rb` is the receive buffer in bytes, `r` is how much of it is in use right now, and `d` counts datagrams this socket dropped. If `rb` is far below what your program asked for, the limit cut it down.

## How does SO_RCVBUF work?
A program asks for a receive buffer with the `SO_RCVBUF` socket option. Three rules from socket(7) explain most surprises:

- The request is capped at `net.core.rmem_max`, with no error. Go's `SetReadBuffer`, Python's `setsockopt` and Node's `recvBufferSize` all succeed and still get less.
- The kernel doubles the value it accepts, to leave room for bookkeeping, and reading the option back returns the doubled number.
- A socket that never sets the option starts at `net.core.rmem_default`.

You can see both the doubling and the cap from Python. Here `rmem_max` was 212992:

```sh file="terminal"
python3 -c 'import socket; s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for want in (100000, 8 << 20):
    s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, want)
    print(want, s.getsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF))'
```

```text file="output"
100000 200000
8388608 425984
```

The buffer is a ceiling, and memory is used only while datagrams wait in it. Each datagram is charged more than its payload: on loopback, in our test, a socket with an `rb` of 212992 held 93 datagrams of 1,200 bytes, about 2,300 bytes each. So divide by more than the 1,228-byte maximum when you work out how many shreds a buffer can hold.

## How do I raise the limit?
Raise `rmem_max` so the size your receiver asks for is granted, then restart the receiver, because the size is set when the socket is created:

```sh file="terminal"
sudo sysctl -w net.core.rmem_max=67108864
```

The 64 MiB here is an example, not a measured need. Start with what your receiver requests (the [Python](https://nitride.xyz/docs/receiver/python) and [Go receivers](https://nitride.xyz/docs/receiver/go) ask for 8 MiB), and go higher only while the drop counters below keep rising. A bigger buffer absorbs bursts and short stalls; it cannot save a loop that is slower on average than the stream.

Change `rmem_default` only for a program you cannot modify that never sets `SO_RCVBUF`, since it changes the starting size for other sockets on the host too. Node's `recvBufferSize` option sets `SO_RCVBUF`, so the [Node.js receiver](https://nitride.xyz/docs/typescript) needs only `rmem_max`.

In some containers these files are missing or read-only. Then the limit is set by whoever runs the host.

## What about SO_RCVBUFFORCE?
`SO_RCVBUFFORCE` does the same as `SO_RCVBUF` but ignores `rmem_max`. It needs the `CAP_NET_ADMIN` capability. Inside a container, root often does not have it for this purpose: in an LXC container we tested, root got `EPERM`. Raising `rmem_max` works for every program and every language, so prefer it, and treat the forced option as a fallback, as the C example below does.

## Is the kernel dropping packets?
A datagram that arrives when the buffer is full is dropped and counted in three places. This is real output from a test where a socket on port 9000 stopped reading and 5,000 datagrams were sent to it:

```sh file="terminal"
cat /proc/net/udp
nstat -az UdpInDatagrams UdpRcvbufErrors UdpInErrors
```

```text file="output"
   sl  local_address rem_address   st tx_queue rx_queue tr tm->when retrnsmt   uid  timeout inode ref pointer drops
 8921: 00000000:2328 00000000:0000 07 00000000:00034500 00:00000000 00000000     0        0 3121403615 2 00000000dfd44e36 4907

UdpInDatagrams                  0                  0.0
UdpInErrors                     4907               0.0
UdpRcvbufErrors                 4907               0.0
```

- `/proc/net/udp` has one row per socket. The port is in hex (`2328` is 9000), and the last column, `drops`, counts what this socket lost. IPv6 sockets are in `/proc/net/udp6`.
- `UdpRcvbufErrors` counts datagrams dropped because a receive buffer was full, across all UDP sockets on the host.
- `UdpInErrors` counts every datagram dropped on receive, so each buffer drop shows up here as well, along with other causes such as bad checksums.
- `UdpInDatagrams` counts datagrams handed to programs. It stayed at 0 because the test socket never read.

Run `nstat` twice a few seconds apart and compare; the [command-line checks](https://nitride.xyz/docs/cli#count-drops) page has the same commands. If these counters stay flat but shreds are still missing, the loss happened before your socket, on the network or in the network card; [what causes UDP packet loss](https://nitride.xyz/learn/packet-loss-and-jitter) explains the usual places, and `ip -s link` shows drops at the interface. To find out which shreds are missing, see [detecting gaps and duplicates](https://nitride.xyz/docs/receiver/gap-detection).

## How do I read packets in batches?
`recvmmsg` (Linux 2.6.33 and later) fills an array of messages in one system call, which cuts the per-datagram system call cost. This C receiver blocks for the first datagram, then takes whatever else is already queued, up to 64:

```c file="batch.c"
// batch.c: gcc -O2 -o batch batch.c && ./batch 9000
#define _GNU_SOURCE
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>

#define BATCH 64
#define MAX_DATAGRAM 1228

static char bufs[BATCH][MAX_DATAGRAM];

int main(int argc, char **argv) {
    int port = argc > 1 ? atoi(argv[1]) : 9000;
    int fd = socket(AF_INET, SOCK_DGRAM, 0);
    if (fd < 0) { perror("socket"); return 1; }

    // SO_RCVBUFFORCE ignores rmem_max but needs CAP_NET_ADMIN; fall back to SO_RCVBUF
    int want = 8 * 1024 * 1024;
    if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &want, sizeof want) < 0)
        setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &want, sizeof want);
    int got = 0;
    socklen_t optlen = sizeof got;
    getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &got, &optlen);
    fprintf(stderr, "rcvbuf=%d\n", got);

    struct sockaddr_in addr = {0};
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    if (bind(fd, (struct sockaddr *)&addr, sizeof addr) < 0) { perror("bind"); return 1; }

    struct iovec iov[BATCH];
    struct mmsghdr msgs[BATCH];
    memset(msgs, 0, sizeof msgs);
    for (int i = 0; i < BATCH; i++) {
        iov[i].iov_base = bufs[i];
        iov[i].iov_len = MAX_DATAGRAM;
        msgs[i].msg_hdr.msg_iov = &iov[i];
        msgs[i].msg_hdr.msg_iovlen = 1;
    }

    unsigned long total = 0;
    int biggest = 0;
    for (;;) {
        // block for the first datagram, then take whatever else is queued, up to BATCH
        int n = recvmmsg(fd, msgs, BATCH, MSG_WAITFORONE, NULL);
        if (n < 0) { perror("recvmmsg"); return 1; }
        for (int i = 0; i < n; i++) {
            unsigned int len = msgs[i].msg_len; // bytes in bufs[i]
            (void)len; // hand bufs[i] and len to your parser here
        }
        total += n;
        if (n > biggest) {
            biggest = n;
            fprintf(stderr, "largest batch so far: %d (total %lu)\n", n, total);
        }
    }
}
```

`MSG_WAITFORONE` is what makes the call return as soon as at least one datagram is in. Pass `NULL` as the timeout: recvmmsg(2) warns that the timeout argument does not work as intended and can block forever. In a test that sent 5,000 datagrams to it on loopback, it reported `largest batch so far: 64`. Rust and C programs call it directly; Python's `socket` module and Go's standard library do not expose it.

If the plain socket path still cannot keep up after this, [kernel bypass for a shred receiver](https://nitride.xyz/blog/kernel-bypass-worth-it) looks at busy polling, AF_XDP and DPDK. Running the receiver in a container adds its own limits, covered in [running a shred receiver in Docker](https://nitride.xyz/blog/shred-receiver-in-docker).

## Can several threads share one port?
Yes, with `SO_REUSEPORT`. Set it on every socket, including the first, before `bind`, and run all of them as the same user. The kernel then spreads incoming datagrams over the sockets in the group, one socket per thread or process.

The kernel picks the socket by hashing the sender's address and port together with yours. A stream that comes from one source address and port therefore lands on one socket, and the other threads stay idle. To split a single stream, you can attach a BPF program with `SO_ATTACH_REUSEPORT_CBPF` or `SO_ATTACH_REUSEPORT_EBPF` (UDP since Linux 4.5) that chooses the socket, for example by CPU. The simpler design is one receive thread that only reads, using `recvmmsg`, and hands datagrams to worker threads through a bounded queue.

## How do I keep the settings after a reboot?
`sysctl -w` lasts until the next boot. Put the setting in a file under `/etc/sysctl.d/` with a `.conf` name, and load it now with `sysctl --system`:

```sh file="terminal"
echo 'net.core.rmem_max = 67108864' | sudo tee /etc/sysctl.d/60-shred-receiver.conf
sudo sysctl --system
```

At boot, `systemd-sysctl` reads the same directory. Check the value after the next restart, since a file that sorts later can override it.

## Related
- What the feed sends and what UDP does not do for you: [the UDP wire contract](https://nitride.xyz/docs/udp).
- All setup steps in order, from payment to first packet: the [docs overview](https://nitride.xyz/docs).
