# How to tune Linux and the BIOS for KDB-X

_This page explains the Linux and BIOS settings that can affect a KDB-X host. Measure the defaults first, change one setting at a time, and retain a change only when the representative workload improves._

Operating-system tuning can't compensate for a query that reads the wrong partitions or columns. Start with the [data layout](data-layout.md) and [bottleneck evidence](overview.md#find-the-bottleneck). Kernel, firmware, distribution, storage-driver, and cloud-platform versions can change the best setting, so avoid applying an old tuning checklist unchanged.

Record the host state with tools such as `uname -a`, `lscpu`, `numactl --hardware`, `lsblk`, `findmnt`, and `sysctl`. Keep the output with the benchmark so that a result can be reproduced after an upgrade.

## NUMA

On a multi-socket or multi-node host, KDB-X isn't NUMA-aware. Linux decides where the process runs and where its pages are allocated. Memory attached to another node has higher latency and lower bandwidth, and placement can make otherwise identical runs vary.

The figures in this section come from in-memory and mapped NYSE TAQ benchmark queries on a host with two Intel Xeon 6738P processors, each with 32 cores and 256 GB of memory, running KDB-X on Linux 5.14. Measure your own workload before you adopt a placement.

First inspect the topology, the free memory and page cache of each node, the node of each network interface, and the placement of the running process:
```bash
numactl --hardware
numastat -m                                 # per-node MemFree and FilePages
grep . /sys/class/net/*/device/numa_node    # node of each network interface
numastat -p PID
```

Host-wide free memory can hide a full node. A node can have no free pages while another node has hundreds of gigabytes free. A network interface that reports `-1` has no node, for example on a host with one node or in some virtual machines.

### Principles

**Keep each process within one node when it fits.** An in-memory process with 8 secondary threads ran about 34% slower, by geometric mean per query, when Linux placed it than when its CPUs and memory were bound to one node. With all of its heap on the other node, it ran 1.7 times slower in total. With 32 threads on one socket, it was also faster than with 64 threads spread over both sockets, although some heavily multithreaded scans gained from the second socket.

**Size for the peak, not the data.** Queries, sorts, and attributes allocate temporary memory on the heap, and [secondary threads have their own heaps](../basics/memory-management.md#the-heap). A process that held 10.5 GB of tables reached 26 GB of resident memory while it loaded and sorted them. Use the peak, `VmHWM`, when you decide whether a process fits on a node (see [process memory](../basics/memory-management.md#process-memory)).

**A process can't outgrow its memory and keep running.** No q setting makes an oversized query fail while the process carries on. Past the [workspace limit](../../ref/cmdline.md#-w-workspace), q exits with `-w abort`. When the operating system refuses memory, q signals `'wsfull`. When a node or the host runs out, the kernel's out-of-memory killer ends the largest eligible process, which isn't necessarily the one that ran short. **Binding a process to a node therefore trades capacity for speed.**

**Choose what happens when the node runs short.** `numactl` offers two local memory policies:
```bash
numactl --cpunodebind=0 --membind=0 q rdb.q -s 8      # strict
numactl --cpunodebind=0 --preferred=0 q hdb.q -s 8    # falls back to other nodes
```

- **`--membind`** allocates only from the listed node. When the node has no free pages, the kernel reclaims page cache on that node first. If the node's memory is held by processes and can't be reclaimed, the out-of-memory killer ends a process.
- **`--preferred`** uses another node as soon as the preferred node has no free pages, even when page cache that could be reclaimed fills the node. Pages placed on the other node stay there. On the test kernel, an explicit `numactl` memory policy also took the process out of automatic NUMA balancing, which otherwise migrates pages toward the CPUs that use them.

In a test where page cache filled node 0, a process started with `--membind=0` kept its whole heap on node 0 and ran at full speed. With `--preferred=0`, it placed most of its heap on node 1 and ran between 18% and 100% slower across runs. When the heap of another process held node 0, every placement on node 0 ran at about the speed of remote memory; only moving to a node with free memory kept the process local.

**Page cache is shared and placed by the first reader.** Linux keeps one copy of a cached file page, on the node where it was allocated when a process first read the file. Page cache follows the memory policy of that reader, so `--membind` also confines the cache a process creates to its node. Processes on different nodes that read the same files read part of the page cache remotely. For a mapped HDB, a remote heap cost more than a remote page cache: with the page cache on the other node, a process ran 13% slower, while interleaving the heaps of a pool cost about 20%.

**Receive the feed on the node of its network interface.** A network interface writes the packets it receives to memory on its own node. A feed handler or tickerplant on another node reads every message across the link between the sockets. Run the feed handlers and the tickerplant on the interface's node, and keep the interface's interrupt handling on the same node (see [measure the network](#measure-the-network)). Run the RDB on that node too when it fits, so that the updates the tickerplant publishes stay on one node.

**Don't interleave a process that runs on one node.** `--interleave=all` spreads pages across nodes in turn. Combined with a CPU binding to one node, half of the memory is remote for every thread: `numactl --cpunodebind=0 --interleave=all` was as slow as no placement at all.

**q keeps freed memory where it was allocated.** In the default [garbage-collection mode](../basics/memory-management.md#garbage-collection), memory that q frees stays on its heap and is reused by later allocations, so it stays on its node. [`.Q.gc[]`](../../ref/dotq.md#gc-garbage-collect) returns free 64 MB units to the operating system, where page cache and other processes can take them. When the process needs the memory again, the kernel allocates it again, and under `--preferred` it can land on the other node. Collect when other processes on the node need the memory, not by routine.

**Keep the kernel defaults.** Keep `vm.zone_reclaim_mode` at `0`. With zone reclaim enabled, an allocation reclaims page cache on the local node before it uses another node, even when the other node has free memory. That evicts cached HDB data across the host and adds reclaim work to allocations. In tests where page cache filled a node, zone reclaim left an unpinned process's heap only partly local, while `--membind` kept it fully local without the setting. The [kernel documentation](https://docs.kernel.org/admin-guide/sysctl/vm.html#zone-reclaim-mode) recommends leaving it disabled for workloads that benefit from cached data. Older KX notes recommend enabling it on Linux 3.x and later kernels; these measurements don't support that recommendation. Automatic NUMA balancing (`kernel.numa_balancing`) made no measurable difference to processes that Linux placed.

### Placement for common setups

| Setup | CPUs | Memory policy |
| --- | --- | --- |
| [RDB larger than one node](#an-rdb-larger-than-one-node) | Not bound | Default |
| [RDB that fits on one node](#an-rdb-that-fits-on-one-node) | One node | `--membind`, or `--preferred` to survive a query that outgrows the node |
| [HDB pool](#an-hdb-pool) | Half the processes on each node | `--preferred` |
| [HDB pool and RDB](#an-hdb-pool-and-an-rdb) | RDB on cores of its own | RDB `--membind`, HDB `--preferred` |

The examples are for a host with two nodes. Take CPU numbers from `lscpu -e`, which shows the node and core of each CPU; the two hardware threads of a core share a core number.

#### An RDB larger than one node

When an RDB's peak memory exceeds one node, don't bind its CPUs or memory. In a test where an RDB had to use the memory of both nodes, the default policy was about 4% faster than `--interleave=all`.

Consider splitting the data instead across two RDBs, each bound to its own node, with a gateway that combines their results. In the same test, an RDB bound to a node with enough free memory took about 20% less time than one spread over both. Split the data in one of two ways:

- **By table.** Tables that are never queried together split cleanly. A query that joins tables held by different RDBs can no longer run in one process: the gateway, or one of the RDBs, has to fetch the data from the other process first, which adds transfer time, memory, and code to maintain.
- **By instrument.** Each RDB holds all the tables for its share of the instruments, so joins that match on instrument, such as an `aj` of trades to quotes by symbol, still run in one process. The gateway sends a query to the RDBs that hold its instruments and combines their results.

#### An RDB that fits on one node

Bind the RDB to one node, and run other processes, such as a second RDB, on the other node:
```bash
numactl --cpunodebind=0 --membind=0 q rdb.q -s 16 -w 200000
numactl --cpunodebind=1 --membind=1 q rdb2.q -s 16 -w 200000
```

`--membind` gives the fastest queries, but a query that needs more memory than the node has ends the RDB, although the other node could have served it. Set `-w` below the node's memory, leaving room for the symbol pool, mapped files, and other processes on the node, so that q exits with `-w abort` instead of the kernel choosing a process to kill.

Where losing the RDB is worse than a slow query, use `--preferred` instead. A query that outgrows the node then runs, with the memory beyond the node at remote speed. Page cache also makes `--preferred` spill: reading the tickerplant log and writing the database at end of day fill the node's free memory with cached file pages, and later allocations then land on the other node.

Choose the node of the network interface that carries the feed for the RDB and the tickerplant (see [principles](#principles)). A second RDB on the other node that subscribes to the same tickerplant receives its updates across the link between the sockets.

#### An HDB pool

Start half of the HDB processes on each node, behind a [gateway](../interact_with_databases/concurrency.md):
```bash
numactl --cpunodebind=0 --preferred=0 q hdb.q -s 8 -p 5011
numactl --cpunodebind=1 --preferred=1 q hdb.q -s 8 -p 5012
```

Use `--preferred` rather than `--membind`, so that page cache can use the memory of both nodes. Size `-s` so that the processes on a node don't use more threads than its cores. In tests with a pool sharing one database, this placement kept the time of each process within 3% of the others. With four processes, leaving placement to Linux was about 8% slower by geometric mean per query, and interleaving memory was about 30% slower. With eight processes, the mean under Linux placement was similar, but the slowest process took 11% longer; running all eight on one node made the workload 40% slower. Binding only the CPUs, which leaves the memory policy at its default, performed within 3% of `--preferred`.

Where a gateway can route queries by partition or segment, sending a set of partitions to the processes of one node keeps their page cache on that node. Schedule [garbage collection](../interact_with_databases/hdb.md#garbage-collection) so that the pool keeps serving.

#### An HDB pool and an RDB

Bind the RDB with `--membind`. On such a host, HDB page cache fills the free memory of both nodes, and an RDB with `--preferred` then places new memory on the other node.

If the HDB pool can run on one node, give the RDB and the tickerplant the node of the network interface, and the pool the other node. The RDB's CPUs are then isolated from HDB queries, and `--membind` reclaims the HDB page cache on its node when it needs memory:
```bash
numactl --cpunodebind=0 --membind=0 q rdb.q -s 16 -w 200000
numactl --cpunodebind=1 --preferred=1 q hdb.q -s 8 -p 5011
numactl --cpunodebind=1 --preferred=1 q hdb.q -s 8 -p 5012
```

If the pool needs both nodes, give the RDB cores of its own on one node with `--physcpubind`, and run that node's HDB processes on its other cores:
```bash
numactl --physcpubind=0-7,64-71 --membind=0 q rdb.q -s 8 -w 100000
numactl --physcpubind=8-31,72-95 --preferred=0 q hdb.q -s 8 -p 5011
numactl --cpunodebind=1 --preferred=1 q hdb.q -s 8 -p 5012
```

Size the shared node for the peak of the RDB plus the heaps of its HDB processes. Page cache gives way to the RDB; the heaps of other processes don't.

#### Other setups

- **Several nodes per socket.** BIOS settings such as sub-NUMA clustering or nodes per socket can split each socket into two or more nodes. `numactl --hardware` then lists more nodes than sockets, with a smaller distance between nodes of the same socket. Bind a process that doesn't fit on one node to the nodes of one socket, for example `--cpunodebind=0,1 --membind=0,1`, and benchmark it against a single node. On AMD EPYC processors, a socket is built from several compute dies, each with its own L3 cache, so the secondary threads of a process on one node can still run on dies that don't share a cache. A BIOS option that reports each L3 cache as a NUMA domain makes each die a node, which can suit a pool of small processes. Benchmark it against the default before you adopt it.
- **NUMA disabled in the BIOS.** Node interleaving in the BIOS spreads the memory of every process across the sockets, similar to `--interleave=all`. Keep NUMA enabled and place the processes.
- **Containers and virtual machines.** See [containers](containers.md#cpu) for CPU sets and memory nodes.

After a placement change, verify the result with `numastat -p`, and compare query latency, page faults and swap activity under the representative workload.

## File system

The same device can produce different KDB-X results under different file systems. KX's [`nano` file-system tests](https://code.kx.com/q/kb/filesystemTestByNano/) found large differences in concurrent writes, sorting, and applying attributes, while no file system won every read pattern. Treat those results as a shortlist, not a universal ranking.

Common Linux choices include:

- **ext4** and **XFS**: mature journaling file systems supported by the major distributions.
- **Btrfs** and **ZFS**: copy-on-write file systems with checksums, snapshots, and optional transparent compression.
- **F2FS**: a file system designed for flash storage.

Choose with the complete workload:

- **Ingestion and end-of-day writes** can differ much more than cached reads. Include concurrent writers, sorting, attributes, and compression in the test.
- **Cold and warm reads** exercise different paths. Run both, with the actual partition and query sizes.
- **Copy-on-write behavior** affects file rewrites and snapshots. Snapshot convenience can be worth a write cost, but measure it.
- **Operating-system support** determines which file-system versions and repair tools are supportable in production.
- **File-system compression is optional**, including on ZFS, Btrfs, and F2FS. Don't assume it's enabled. Avoid compressing the same data again with [KDB-X file compression](data-layout.md#compress-for-the-measured-access-pattern) unless a benchmark shows a benefit.

Different [storage tiers](../interact_with_databases/tiering.md) can use different file systems. Test each tier with its own read, write, retention, and recovery pattern before formatting it.

## Combine disks

A single device can limit a query that scans columns. Several devices can be combined below KDB-X:

- A **striped LVM logical volume** distributes fixed-size stripes across physical volumes.
- **RAID 0** stripes for performance without redundancy. The failure of one member loses the volume.
- **RAID 1 or RAID 10** mirrors data, trading capacity for redundancy and read options.
- **RAID 5 or RAID 6** stores parity, preserving more capacity but adding write and rebuild work.

Compare this with a [segmented database](../interact_with_databases/segment.md):

- Striping spreads every file across devices, so even one partition can use several devices. KDB-X sees one directory.
- Segmentation places whole partitions on separate file systems. A query uses several devices only when it spans partitions on those segments, but tiers and failure domains can be managed separately.

A segmented database can also use striped volumes as its segments. Benchmark single-partition and multi-partition queries, ingestion, degraded RAID operation, and rebuilds. The stripe size, RAID level, controller cache, and file-system alignment can all change the result.

## Read-ahead

Linux read-ahead fetches blocks that follow a detected sequential read. A larger value can help scans on HDD or high-latency storage. It can waste I/O and page cache for selective or random access.

Show and set block-device read-ahead in 512-byte sectors:
```bash
sudo blockdev --getra /dev/nvme0n1
sudo blockdev --setra 4096 /dev/nvme0n1   # 2 MiB
```

Test cold reads at several values; warm reads do not measure the device setting. With device mapper, LVM, RAID, or network storage, confirm which logical and underlying devices have effective read-ahead. Persist a successful value with the distribution's device or startup configuration rather than an ad hoc command.

## Memory pages

Linux commonly uses 4 KiB base pages on x86-64. transparent huge pages (THP) can reduce address-translation work for a large heap, but promotion, compaction, splitting, and kernel-specific defects can introduce pauses. KX guidance differs by kernel generation, so neither "always disable THP" nor "always enable THP" is a safe general rule.

Inspect both the use and defragmentation policy:
```bash
cat /sys/kernel/mm/transparent_hugepage/enabled
cat /sys/kernel/mm/transparent_hugepage/defrag
```

Start with the supported distribution and KX recommendation for the deployed kernel. If a process shows unexplained latency spikes or CPU spent in memory compaction, compare policies on an isolated host with the full workload and memory pressure. Restart q between tests where the setting requires it.

## Simultaneous multithreading

_Simultaneous multithreading_ (SMT), called Hyper-Threading on Intel processors, exposes two hardware threads per physical core. They share core execution resources and caches.

SMT can improve throughput when threads often wait for memory or storage. It can hurt a compute-bound workload or a latency-sensitive main thread that shares a physical core. Size secondary threads initially from the physical core count, not [`.z.c`](../../ref/dotz.md#zc-cores), which counts each SMT thread as a CPU, then benchmark the workload with SMT enabled and disabled. Pin the main thread or latency-sensitive process away from competing work when isolation matters.

## CPU power and affinity

Frequency scaling and deep idle states save power but can add wake-up latency. For a latency-sensitive process, compare the platform's performance profile with its default balanced profile:
```bash
cpupower frequency-info
sudo cpupower frequency-set -g performance
```

The available controls differ with the CPU driver, firmware, hypervisor, and cloud platform. A maximum-performance policy increases energy use and heat and can reduce sustained turbo frequency if cooling is insufficient. Measure a long run, not only the first seconds.

Use `taskset`, `numactl --physcpubind`, cpusets, or orchestrator CPU reservations to isolate important processes. Keep CPU affinity consistent with NUMA memory placement. Don't pin more busy q threads to a CPU set than it can run.

## Resource limits and swap

A partitioned database can touch many files and mappings. Check the limits before a broad query or [`.Q.MAP`](code-optimization.md#keep-partitions-mapped):
```bash
ulimit -n
sysctl vm.max_map_count vm.swappiness
```

- Raise the open-file limit for the service account when the measured workload needs more descriptors. `.Q.MAP` retains handles, and compressed files can require additional descriptors.
- Raise `vm.max_map_count` when the process maps more areas than the default permits. Derive the requirement from partitions, tables, columns, compression, and concurrency, and leave headroom.
- Size RAM so the q heaps and essential page cache do not swap under normal load. Lowering `vm.swappiness` can make anonymous-memory swapping less eager, but it doesn't create memory or guarantee that swap is never used.
- Use a workspace limit and cgroup or container memory limit deliberately. Leave room outside the q heap for mapped resident pages, libraries, the symbol table, the operating system, and service sidecars.

Disabling swap entirely changes an overload from severe latency to an earlier out-of-memory kill. Choose that failure policy explicitly and test recovery instead of treating it as a performance toggle.

## Network

Linux autotunes TCP buffers within configured limits. Increase the maximum receive or send buffer only when measurement shows that a connection can't fill the bandwidth-delay product and the application is socket-buffer limited.

### Socket buffers for ingestion

A feed handler, tickerplant, or real-time subscriber that receives bursts can be limited by kernel socket buffers. When a receiver's buffer is full, the sender's buffer fills next; after that, a q publisher keeps the pending asynchronous messages in its own memory, visible per handle in [`.z.W`](../../ref/dotz.md#zw-handles). Larger buffers absorb longer bursts, but they also hold more data in flight and use more kernel memory per connection.

q doesn't set `SO_RCVBUF` or `SO_SNDBUF` on its IPC sockets, so the kernel defaults and autotuning apply. Inspect the current values:
```bash
sysctl net.ipv4.tcp_rmem net.ipv4.tcp_wmem net.core.rmem_default net.core.wmem_default \
       net.core.rmem_max net.core.wmem_max net.ipv4.udp_mem net.unix.max_dgram_qlen \
       net.ipv4.tcp_timestamps net.ipv4.tcp_low_latency
```

| Parameter | What it controls | Ingest notes |
| --- | --- | --- |
| `net.ipv4.tcp_rmem` | TCP receive buffer: minimum, initial, and autotuning maximum, in bytes | The maximum bounds how far a q TCP connection's receive buffer can grow. It is not capped by `net.core.rmem_max`, which limits only explicit `SO_RCVBUF` requests. |
| `net.ipv4.tcp_wmem` | TCP send buffer: minimum, initial, and autotuning maximum, in bytes | The maximum bounds how much a publisher can queue in the kernel before data stays in q's `.z.W` queue. |
| `net.ipv4.tcp_mem` | Total memory for all TCP sockets: minimum, pressure, and maximum, in **pages** | Above the pressure value, the kernel shrinks TCP buffers on every connection. Check it when raising the per-socket maximums on a host with many connections. |
| `net.core.wmem_default`, `net.core.rmem_default` | Default send and receive buffer for non-TCP sockets that do not set their own, in bytes | q's Unix domain socket connections (`` `:unix://port ``) are stream sockets. Queued data counts against the **sender's** send buffer, so `wmem_default` bounds how much a q publisher can queue in the kernel; raising only `rmem_default` does not change it. `rmem_default` also sets the buffer of UDP receivers that do not set `SO_RCVBUF`. |
| `net.core.rmem_max`, `net.core.wmem_max` | Largest buffer that an application can request with `SO_RCVBUF` or `SO_SNDBUF` | Matters for a feed handler or library that sets its own buffer size, such as a UDP or multicast market-data receiver. A request above the maximum is silently reduced to it. |
| `net.ipv4.udp_mem` | Total memory for all UDP sockets: minimum, pressure, and maximum, in **pages** | q IPC does not use UDP. Check this limit for UDP feed handlers on the same host. |
| `net.ipv4.udp_rmem_min`, `net.ipv4.udp_wmem_min` | Buffer each UDP socket keeps even when `udp_mem` is under pressure, in bytes | Raising it protects receivers during host-wide UDP memory pressure. It does not raise a socket's normal buffer, which comes from `rmem_default` or `SO_RCVBUF`. |
| `net.unix.max_dgram_qlen` | Maximum queued datagrams on a Unix domain datagram socket | Applies only to `SOCK_DGRAM` sockets, such as a feed handler that hands off packets locally over a datagram socket. It does not limit q's Unix domain socket IPC. |
| `net.ipv4.tcp_timestamps` | TCP timestamp option | Adds 12 bytes per segment and supports round-trip measurement and protection against wrapped sequence numbers on fast links. Keep it enabled unless a test shows a benefit from disabling it. |
| `net.ipv4.tcp_low_latency` | Former TCP prequeue switch | Ignored since Linux 4.14. Changing it has no effect on current kernels. |

Buffers larger than 64 KiB also require TCP window scaling (`net.ipv4.tcp_window_scaling = 1`, the default).

For a TCP feed between hosts, the limits that matter are the `tcp_rmem` maximum on the **receiving** host and the `tcp_wmem` maximum on the **sending** host. Size each at about twice the bandwidth-delay product:
```text
max buffer ≈ 2 × bandwidth (bytes/s) × round-trip time (s)
```

The factor of two allows for the kernel's packet overhead: with `net.ipv4.tcp_adv_win_scale = 1`, the default up to Linux 6.5, only half the receive buffer is advertised as TCP window. In local tests, raising the maximum beyond this level gave no further gain, because the window then no longer limits throughput. For example:

| Path | Round trip | 2 × bandwidth-delay product |
| --- | --- | --- |
| 10 Gb/s, same data center | 0.2 ms | 0.5 MB |
| 10 Gb/s, metro link | 2 ms | 5 MB |
| 10 Gb/s, cross-region | 20 ms | 50 MB |
| 25 Gb/s, metro link | 2 ms | 12.5 MB |

On a low-latency path, the distribution defaults are usually enough; this test host's defaults already allow 6 MiB to receive and 4 MiB to send. Measure the round trip with `ping` or the `rtt` field of `ss -ti` under load, not idle, because queuing raises it.

Raise only the maximum and leave the minimum and initial values unchanged. Autotuning grows a connection's buffer toward the maximum when the connection needs it (`net.ipv4.tcp_moderate_rcvbuf = 1`, the default). A buffer size is a limit, not an allocation: memory is used only for data waiting in the queue. Raising the initial value, or `net.core.*mem_default`, raises the limit for every connection, including small control connections, so many slow consumers can each hold more. Check the host-wide `tcp_mem` limit and memory headroom either way.

Larger buffers don't help a consumer that can't keep up. If a subscriber is slower than the feed on average, a larger buffer only delays the moment its queue grows in the publisher's `.z.W`.

While the workload runs, compare the buffer each connection uses with the limits. In the `skmem` field, `rb` and `tb` are the current receive and send buffer sizes, and `r` and `t` are the bytes queued:
```bash
ss -tmi '( sport = :5010 or dport = :5010 )'   # TCP
ss -xm | grep -A1 kx.5010                       # Unix domain socket
nstat -az TcpExtTCPRcvQDrop UdpRcvbufErrors UdpSndbufErrors
```

On a test host running KDB-X on Linux 5.14, a q TCP subscriber receiving a burst of asynchronous messages autotuned to the `tcp_rmem` maximum (6 MiB), and the publisher to the `tcp_wmem` maximum (4 MiB), although `net.core.rmem_max` was 208 KiB. The same transfer over a Unix domain socket stayed at the `net.core.*mem_default` size of 208 KiB.

If `rb` or `tb` stays at the maximum while `r` or `t` stays high, or the UDP error counters increase, raise the relevant limit, then re-run the ingest test and compare throughput, latency, and memory.

### Packet backlog and connection limits

Before a packet reaches a socket buffer, the kernel processes it from a per-CPU backlog in software interrupts. Loopback traffic between q processes on the same host also passes through this backlog. At high packet rates, packets can be dropped there even when the socket buffers have room.

| Parameter | What it controls | Ingest notes |
| --- | --- | --- |
| `net.core.netdev_max_backlog` | Packets queued per CPU before the kernel drops input | Raise it when the second column of `/proc/net/softnet_stat` (drops) increases. |
| `net.core.netdev_budget`, `net.core.netdev_budget_usecs` | Packets, and microseconds, that one receive-processing cycle can handle before yielding the CPU | Raise them when the third column of `/proc/net/softnet_stat` (time squeezes) increases. A larger budget lets network processing hold a CPU longer, which can delay a q process on that CPU. |
| `net.core.somaxconn` | Upper limit on any listening socket's queue of accepted connections | A q listener requests a queue of 1000 connections, so values above 1000 do not lengthen it. Check `nstat -az TcpExtListenOverflows` when many clients connect at once, such as after a restart. |
| `net.ipv4.tcp_max_syn_backlog` | Half-open connections queued per listener while the handshake completes | Matters with a burst of new connections. With `tcp_syncookies` enabled, the default, an overflow falls back to SYN cookies instead of dropping connections. |
| `net.ipv4.ip_local_port_range` | Ephemeral ports for outbound connections | Widen it on a gateway or client that opens many connections to the same destination. If the range includes q listening ports, reserve them in `net.ipv4.ip_local_reserved_ports` so that an outbound connection can't take a port before q binds it. |
| `net.ipv4.tcp_ecn` | Explicit Congestion Notification | The default `2` accepts ECN only when the peer requests it; `1` also requests it on outgoing connections. ECN helps only where switches and routers mark congestion rather than drop packets. |
| `net.ipv4.tcp_mtu_probing` | Path MTU discovery without ICMP | `1` starts probing after it detects that large packets are disappearing, for example where ICMP is blocked. It does not raise throughput on a working path. |

Watch the counters during the representative ingest and burst-reconnect tests. Each row of `/proc/net/softnet_stat` is one CPU, in hexadecimal:
```bash
cat /proc/net/softnet_stat
nstat -az TcpExtListenOverflows TcpExtListenDrops
```

Persist a retained value in a file under `/etc/sysctl.d/` and load it with `sysctl --system`, rather than with an ad hoc `sysctl -w`. Record why each value was changed and the measurement that justified it. For example, a host that receives bursty multicast and high-rate TCP feeds might keep:
```ini
# /etc/sysctl.d/90-kdbx-ingest.conf
net.core.netdev_max_backlog = 16384    # softnet_stat drops during bursts
net.core.rmem_max = 25165824           # feed handler sets SO_RCVBUF = 24 MiB
net.ipv4.tcp_rmem = 4096 131072 25165824   # receiving side: 2 x 10 Gb/s x 10 ms
net.ipv4.tcp_wmem = 4096 16384 25165824    # sending side: same path
net.core.wmem_default = 1048576        # q publishers over Unix domain sockets
```

These values come from one workload. Derive your own from the `softnet_stat` and `nstat` counters shown above.

### IPC compression

q compresses an eligible outgoing IPC message to a remote peer by default. The [compression rules](../io_and_communication/ipc-protocol.md#compression) include a minimum size of 2000 bytes, and the compressed message must be under half the original size. Compression trades CPU at both ends for fewer bytes. It helps when the network is the bottleneck and can reduce throughput on a fast path. Compressing one compressible 8 MB vector with [`-18!`](../../ref/internal.md#-18x-compress-bytes) took about 6 ms on a test host, so a single connection could compress only about 1.3 GB/s.

From KDB-X 5.0.20260706, use the two-argument form of [`.Q.ipc`](../../ref/dotq.md#ipc-ipc-settings) to choose per handle. Each side compresses only what it sends, so set it at both ends: on the handle from `hopen` at the client, and on [`.z.w`](../../ref/dotz.md#zw-handle) in [`.z.po`](../../ref/dotz.md#zpo-open) at the server:
```q
h:hopen `:tp.svc:5010
.Q.ipc[h;([z:0b])]                      / client: do not compress what it sends
.z.po:{.Q.ipc[.z.w;([z:0b])]}           / server: do not compress replies or published updates
```

Processes in different containers on the same host usually see each other as remote, so q compresses between them although the data never leaves the host. See [IPC compression in containers](containers.md#ipc-compression).

Enabling compression with `([z:1b])` also applies to a connection through `localhost` or a Unix domain socket. Use it when such a connection does reach a slower network, for example through a sidecar proxy or an SSH tunnel.

Compare throughput, latency, and CPU at both ends with compression enabled and disabled, using the workload's own messages. Compression depends on the data: random floats rarely compress to under half their size, so q sends them uncompressed anyway, after spending the time trying.

### Measure the network

Use `ss -ti` to inspect congestion, retransmission, and window behavior, and a tool such as `iperf3` to separate the network path from q serialization. For remote storage, test the storage protocol and query workload as well: a network throughput test doesn't include metadata requests or storage-controller limits.

At high packet rates, receive-side scaling, interrupt affinity, and NIC queues can compete with latency-sensitive q cores. Inspect per-CPU interrupt and softirq load before changing them, and keep any IRQ affinity consistent with NUMA placement.

Synchronize clocks with the platform's supported NTP or PTP service when latency is measured across hosts. Otherwise, one-way timings can report clock error rather than application latency.

## Next steps

- Re-run the [baseline workload](overview.md#establish-a-baseline) after each setting change.
- [Choose hardware](hardware.md) whose sustained capacity matches the workload.
- [Run KDB-X in containers and virtual machines](containers.md) with limits that match the tuning.
- [Optimize q code](code-optimization.md) and measure its secondary-thread scaling under the final NUMA and CPU policy.
