Nitride.xyz
Receivers

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:

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:

terminal
1python3 -c 'import socket; s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
2for want in (100000, 8 << 20):
3 s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, want)
4 print(want, s.getsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF))'
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:

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 and Go receivers 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 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:

terminal
cat /proc/net/udp
nstat -az UdpInDatagrams UdpRcvbufErrors UdpInErrors
output
1 sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode ref pointer drops
2 8921: 00000000:2328 00000000:0000 07 00000000:00034500 00:00000000 00000000 0 0 3121403615 2 00000000dfd44e36 4907
3
4UdpInDatagrams 0 0.0
5UdpInErrors 4907 0.0
6UdpRcvbufErrors 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 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 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.

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:

batch.c
1// batch.c: gcc -O2 -o batch batch.c && ./batch 9000
2#define _GNU_SOURCE
3#include <netinet/in.h>
4#include <stdio.h>
5#include <stdlib.h>
6#include <string.h>
7#include <sys/socket.h>
8
9#define BATCH 64
10#define MAX_DATAGRAM 1228
11
12static char bufs[BATCH][MAX_DATAGRAM];
13
14int main(int argc, char **argv) {
15 int port = argc > 1 ? atoi(argv[1]) : 9000;
16 int fd = socket(AF_INET, SOCK_DGRAM, 0);
17 if (fd < 0) { perror("socket"); return 1; }
18
19 // SO_RCVBUFFORCE ignores rmem_max but needs CAP_NET_ADMIN; fall back to SO_RCVBUF
20 int want = 8 * 1024 * 1024;
21 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &want, sizeof want) < 0)
22 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &want, sizeof want);
23 int got = 0;
24 socklen_t optlen = sizeof got;
25 getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &got, &optlen);
26 fprintf(stderr, "rcvbuf=%d\n", got);
27
28 struct sockaddr_in addr = {0};
29 addr.sin_family = AF_INET;
30 addr.sin_port = htons(port);
31 addr.sin_addr.s_addr = htonl(INADDR_ANY);
32 if (bind(fd, (struct sockaddr *)&addr, sizeof addr) < 0) { perror("bind"); return 1; }
33
34 struct iovec iov[BATCH];
35 struct mmsghdr msgs[BATCH];
36 memset(msgs, 0, sizeof msgs);
37 for (int i = 0; i < BATCH; i++) {
38 iov[i].iov_base = bufs[i];
39 iov[i].iov_len = MAX_DATAGRAM;
40 msgs[i].msg_hdr.msg_iov = &iov[i];
41 msgs[i].msg_hdr.msg_iovlen = 1;
42 }
43
44 unsigned long total = 0;
45 int biggest = 0;
46 for (;;) {
47 // block for the first datagram, then take whatever else is queued, up to BATCH
48 int n = recvmmsg(fd, msgs, BATCH, MSG_WAITFORONE, NULL);
49 if (n < 0) { perror("recvmmsg"); return 1; }
50 for (int i = 0; i < n; i++) {
51 unsigned int len = msgs[i].msg_len; // bytes in bufs[i]
52 (void)len; // hand bufs[i] and len to your parser here
53 }
54 total += n;
55 if (n > biggest) {
56 biggest = n;
57 fprintf(stderr, "largest batch so far: %d (total %lu)\n", n, total);
58 }
59 }
60}

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 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.

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:

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.

Sources#