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 and bottleneck evidence. 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. Remote memory has higher latency and can make otherwise identical runs vary.
First inspect the topology and the placement of the running process:
numactl --hardware
numastat -p PID
Where the working set fits on one NUMA node, keep its CPUs and memory local. A preferred policy can fall back to another node if local memory is exhausted; a strict bind can't:
numactl --cpunodebind=0 --preferred=0 q hdb.q -s 8
numactl --cpunodebind=0 --membind=0 q hdb.q -s 8 # strict; size first
On a larger host, running one q process per NUMA node is often easier to predict than making one process span every socket. If one process must span nodes, benchmark an interleaved policy against the default:
numactl --interleave=all q hdb.q -s 32
Don't set vm.zone_reclaim_mode or interleave memory from a blanket recommendation. Zone reclaim trades local allocation against reclaim work and page-cache retention; the result depends on the kernel and whether the process is confined to a node. KX recommendations have also changed across kernel generations. Follow the KX Linux production notes for the deployed kernel, then verify with numastat, page-fault, swap, and query-latency measurements.
File system¶
The same device can produce different KDB-X results under different file systems. KX's nano file-system tests 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 unless a benchmark shows a benefit.
Different storage tiers 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:
- 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:
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:
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, 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:
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:
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.MAPretains handles, and compressed files can require additional descriptors. - Raise
vm.max_map_countwhen 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.swappinesscan 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. 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:
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:
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:
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:
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:
# /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 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! 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 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 in .z.po at the server:
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.
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 after each setting change.
- Choose hardware whose sustained capacity matches the workload.
- Run KDB-X in containers and virtual machines with limits that match the tuning.
- Optimize q code and measure its secondary-thread scaling under the final NUMA and CPU policy.