Skip to content
masdzub.com
~/articles/linux — one from the notebook

Understanding Linux Kernel Tuning with sysctl

Learn how Linux sysctl tuning works, which kernel parameters matter, how to test changes safely, and how to diagnose regressions.

masdzub@website:~$ cat ~/articles/understanding-linux-kernel-tuning-via-sysctl.aspx.md
# 1 file · 17 min read · topic: linux · status: published

Introduction

Linux exposes many kernel runtime parameters through sysctl, a command and configuration interface for reading and changing values in the proc and sys filesystems. These controls govern memory management, networking, file handling, process limits, kernel logging, and virtual memory behavior. The right settings can improve workload behavior, but copying a generic tuning checklist from another server is a poor way to tune production.

A Linux host running an Nginx proxy has a different memory profile from a database server running PostgreSQL. A latency-sensitive API may benefit from different network queue settings than a backup worker. The safest tuning process starts by measuring the current system, identifying a bottleneck, changing one related parameter, and verifying whether the change improved the measured behavior.

This guide explains how sysctl works, how to inspect available parameters, how to persist changes, and how to validate them across Debian, Ubuntu, RHEL, Fedora, and Arch-based systems. It also covers the common failure modes that appear when a tuning change makes performance worse.

What sysctl actually does

sysctl is a user-space tool for reading or writing kernel parameters exposed through files under /proc/sys/ and /proc/sys/. The name parts map to the directory tree. For example, /proc/sys/net/ipv4/tcp_congestion_control corresponds to:

Terminal window
sysctl net.ipv4.tcp_congestion_control

The kernel defines each parameter as a type, a current value, and often a minimum and maximum range. Some parameters are read-only. Others can be changed at runtime, while some changes disappear after reboot. A few parameters also depend on kernel features, compilation options, hardware, or workload behavior.

Kernel documentation generally describes a parameter under /Documentation/admin-parameters/sysctl/ or /Documentation/admin-sysctl/, although the exact path depends on the kernel version. You can also inspect the live system directly:

Terminal window
man sysctl
sysctl --help

The most useful runtime commands are:

Terminal window
# Read one value
sysctl vm.swappiness
# Read all values from a directory
sysctl vm
# Write one value immediately
sudo sysctl -w vm.swappiness=10
# Load settings from a file
sudo sysctl --system
# Show values that differ from defaults
sysctl -a

Run the last command cautiously. On a busy host, sysctl -a can produce a large output and may be inconvenient to capture or compare.

The sysctl command does not create a separate tuning layer. It changes kernel state exposed through procfs. A temporary write changes the running kernel only. Persistent configuration depends on the distribution’s startup mechanism.

Read the current values before changing anything

Before tuning, record the baseline. This makes rollback and comparison possible, especially when several services run on the same machine.

Create a small baseline file:

Terminal window
mkdir -p ~/kernel-tuning
sysctl -a > ~/kernel-tuning/sysctl-before.txt
uname -a > ~/kernel-tuning/kernel-before.txt

Record relevant application and hardware context as well:

Terminal window
lscpu
free -h
df -h
lsblk

For a network-focused investigation, capture interface counters and socket statistics:

Terminal window
ip -s link
ss -s
nstat -az

For memory and storage behavior, use standard Linux diagnostics:

Terminal window
free -h
vmstat 1 10
iostat -xz 1 10
pidstat -dur 1 10

The tools may not be installed by default. On Debian and Ubuntu, install the common diagnostic package set:

Terminal window
sudo apt update
sudo apt install sysstat procps iproute2

On RHEL, Fedora, and compatible distributions:

Terminal window
sudo dnf install sysstat procps-ng iproute

Do not tune from memory alone. A high vm.swappiness is not automatically wrong, and a low value is not automatically an optimization. On a dedicated database server, for example, reducing swap activity can be useful, but forcing an application to use less RAM may still produce worse latency when memory is exhausted.

How to change a sysctl value safely

A runtime change takes effect immediately:

Terminal window
sudo sysctl -w vm.swappiness=10

Verify it separately:

Terminal window
sysctl vm.swappiness

For several related changes, create a dedicated file. The following example is safe to read but should only be applied after measurement and testing:

Terminal window
sudoedit /etc/sysctl.d/90-service-tuning.conf

A minimal file might look like this:

# Reduce routine swap pressure for latency-sensitive services.
vm.swappiness = 10

Then load all system configuration files:

Terminal window
sudo sysctl --system

The command reads configuration in the following order:

/etc/sysctl.conf
/etc/sysctl.d/*.conf
/usr/lib/sysctl.d/*.conf
/usr/local/lib/sysctl.d/*.conf

Files with the same filename in a higher-priority directory replace lower-priority files. For example, /etc/sysctl.d/99-service.conf overrides a file with the same name under /usr/lib/sysctl.d/. Different filenames are merged, with later directories taking precedence for duplicate keys.

On many systemd-based distributions, systemd-sysctl.service applies these settings during boot:

Terminal window
systemctl status systemd-sysctl.service
sudo systemctl restart systemd-sysctl.service

Restarting the service applies configuration, but it does not reset kernel state that cannot be changed after boot. You still need a reboot to test boot-time behavior.

Use sysctl.d files instead of placing unrelated settings in /etc/sysctl.conf. Dedicated files make ownership, review, and rollback clearer.

Distribution differences

The interface for changing parameters is the same across major distributions, but startup paths and file ownership differ.

Debian and Ubuntu

On Debian and Ubuntu, /etc/sysctl.conf is part of /usr/lib/sysctl.d/ and /etc/sysctl.d/. The systemd-sysctl.service unit loads the configuration at boot. Some older systems also use procps service scripts.

Check the effective configuration with:

Terminal window
sudo sysctl --system
systemctl status systemd-sysctl

Avoid editing vendor files under /usr/lib/sysctl.d/. Package updates may replace those files.

RHEL, Fedora, and AlmaLinux

RHEL-family systems commonly use /etc/sysctl.conf and /etc/sysctl.d/. The same systemd unit normally handles boot-time loading. Package-provided defaults may live under /usr/lib/sysctl.d/.

For current and enterprise distributions, compare the installed configuration before making changes:

Terminal window
sudo sysctl --system
rpm -qf /usr/lib/sysctl.d/50-default.conf

Arch Linux

Arch commonly keeps administrator settings in /etc/sysctl.d/. Package defaults may appear under /usr/lib/sysctl.d/. The systemd sysctl service loads the files during boot.

Arch changes more frequently than enterprise distributions, so test kernel updates against workloads that depend on memory reclaim, network queues, or storage behavior.

Kernel parameter categories that matter most

Linux exposes hundreds of sysctl controls. Most administrators only need a small subset for day-to-day troubleshooting. The following categories cover common production concerns, but they are still workload-specific.

Memory management

vm.swappiness controls how aggressively the kernel favors reclaiming anonymous memory and using swap. Lowering it can reduce swap thrashing on servers with enough RAM, while a very low value can make memory pressure worse because the kernel delays reclaim until it has little other choice.

Terminal window
sysctl vm.swappiness
sysctl vm.min_free_kbytes
sysctl vm.dirty_ratio
sysctl vm.dirty_background_ratio

vm.min_free_kbytes provides a reserve used by the kernel during allocation and reclaim. It is not a general-purpose memory pool, and increasing it without understanding the host’s memory size can create early reclaim pressure.

vm.dirty_ratio and vm.dirty_background_ratio control writeback behavior for dirty pages. They matter for workloads that generate heavy write traffic, including databases and bulk file processing. The modern vm.dirty_bytes and vm.dirty_background_bytes controls can be clearer when you know the desired byte thresholds.

A common mistake is changing both byte and ratio variants. Review the kernel documentation and live state before combining them.

Transparent Huge Pages

Transparent Huge Pages can reduce translation lookaside buffer pressure for some memory workloads, but they can also introduce latency during compaction or allocation. Check the current state on both the host and inside containers:

Terminal window
cat /sys/kernel/mm/transparent_hugepage/enabled
cat /sys/kernel/mm/transparent_hugepage/defrag

On a latency-sensitive host, administrators often test with THP disabled:

sudo sysctl -w kernel.mm_transparent_hugepage=enabled

For persistent configuration, the distribution may provide a file such as /etc/default/grub. On systemd systems, the usual process is to edit the GRUB configuration, regenerate the boot image, and reboot. Kernel parameter changes are not the same as sysctl changes.

Do not apply a database-specific recommendation without checking the database vendor’s current support guidance. Performance behavior varies by version, memory allocator, and workload.

Network connection handling

The net.core.somaxconn value sets the maximum length of the completed connection queue for listening sockets. Applications may override it with their own listen backlog, so changing somaxconn does not guarantee that every server uses the new value.

Terminal window
sysctl net.core.somaxconn
sysctl net.ipv4.tcp_max_syn_backlog
sysctl net.ipv4.ip_local_port_range

net.ipv4.ip_local_port_range defines the default range used for ephemeral ports. A narrower range limits available local ports; a wider range increases the port space but can create allocation overhead. The default is usually adequate unless the host has a documented port-exhaustion problem.

For busy servers, inspect the actual application settings:

Terminal window
ss -lnt

TCP congestion control and queueing

The available congestion-control algorithms depend on the kernel build:

Terminal window
sysctl net.ipv4.tcp_congestion_control
sysctl net.ipv4.tcp_available_congestion_control

Changing the default from cubic or bbr does not guarantee better performance. BBR can help on some paths with substantial bandwidth-delay products, but it may behave differently across container networks, proxies, local hostnames, and lossy links. Benchmark the traffic that matters.

Queueing parameters such as net.core.netdev_max_backlog and net.ipv4.tcp_max_syn_backlog often appear in copied tuning guides. Their value depends on whether drops occur in the kernel receive path, the qdisc, the virtual switch, or a hypervisor. A larger queue can reduce some packet drops while increasing latency and memory use.

File descriptor limits

The kernel has a global file descriptor ceiling:

Terminal window
sysctl fs.file-max

This is not the per-process limit. Check the actual soft and hard limits for the service:

Terminal window
systemctl show nginx.service -p LimitNOFILE
cat /proc/$(pidof nginx)/limits

For systemd services, set the limit in the unit rather than relying only on sysctl:

[Service]
LimitNOFILE=65536

Then reload the manager and restart the affected service:

Terminal window
sudo systemctl daemon-reload
sudo systemctl restart nginx

Process and user limits

Kernel process limits can interact with user-level limits configured through PAM or systemd:

Terminal window
sysctl kernel.threads-max
sysctl kernel.pid_max
sysctl kernel.core_pattern

kernel.threads-max is a system-wide ceiling on tasks, not a recommendation for how many threads a service should use. kernel.pid_max determines how high process IDs can rise before wrapping. Neither setting should be changed merely because the current value looks small.

Kernel logging and rate limiting

The printk controls control kernel log output and console behavior. Aggressive rate limits can hide useful diagnostics, while unrestricted logging can flood disks or degrade workloads that emit frequent kernel messages.

Terminal window
sysctl kernel.printk
sysctl kernel.printk_ratelimit
sysctl kernel.printk_ratelimit_burst

For production troubleshooting, temporarily allowing more messages may help, but check disk capacity and journal rotation first.

A practical tuning workflow

A repeatable workflow matters more than the specific parameter values. Start with a hypothesis tied to a measurable symptom.

For example, if a server experiences memory pressure and swap stalls, record memory, reclaim, and I/O behavior:

Terminal window
vmstat 1 30
free -h
sar -W 1 30
sar -B 1 30

If the system is not under meaningful memory pressure, changing vm.swappiness may only hide the current state rather than improve it. Change one variable, ideally in a test environment:

Terminal window
sudo sysctl -w vm.swappiness=10

Then rerun the same workload and measurement commands. Compare throughput, latency, page faults, swap activity, and system responsiveness. Keep the change only if the target metric improves without unacceptable side effects.

For network tuning, capture packet drops and queue pressure before changing anything:

Terminal window
ip -s link
ethtool -S eth0
nstat -az
ss -s

The relevant counters depend on the NIC, driver, virtual network layer, and traffic pattern. A backlog setting should follow evidence that the kernel or device queue is dropping packets.

For storage workloads, use iostat and vmstat to distinguish CPU saturation, memory reclaim, and I/O waiting. Increasing dirty-page thresholds may help a burst workload, but it can move pressure into longer writeback periods and create latency spikes later.

How to persist changes without breaking boot

Persistent configuration should be minimal, commented, and owned by the administrator who understands its purpose. A good file records why a parameter matters and what symptom prompted the change.

Example:

/etc/sysctl.d/70-api-latency.conf
# Set by the API platform team after swap stalls were observed under load.
# Revert if p99 latency regresses after the kernel upgrade.
vm.swappiness = 10

Validate the file before applying it. Some distributions provide sysctl file syntax validation through systemd-analyze, but the simplest check is to load it in a controlled environment and inspect for errors:

Terminal window
sudo sysctl --system

A malformed line may produce errors such as:

sysctl: error setting key 'vm.swappiness': invalid argument

Check the exact key spelling, value type, and whether the parameter is writable in the current kernel.

Avoid using sysctl --system as a blind production deployment step if another administrator may have added files concurrently. Review the files first:

Terminal window
sudo grep -R --line-number --include='*.conf' . /etc/sysctl.d /usr/lib/sysctl.d /usr/local/lib/sysctl.d

Keep rollback instructions next to the configuration or in your infrastructure repository. A simple rollback file can restore the original value:

Terminal window
sudo sysctl -w vm.swappiness=60

The value shown in this example must come from the machine’s recorded baseline. Do not assume 60 is correct for every system.

Validate changes across reboots

A runtime write proves that the kernel accepts the value. It does not prove that the setting will be applied on the next boot. Test the boot path with a controlled reboot window and verify the result:

Terminal window
sysctl vm.swappiness
systemd-analyze cat-config systemd/sysctl.conf

For a non-production host, reboot and run:

Terminal window
sudo sysctl --system
sysctl vm.swappiness

If the value differs after reboot, inspect file ownership and permissions:

Terminal window
ls -l /etc/sysctl.d/70-api-latency.conf
sudo systemd-analyze cat-config systemd/sysctl.conf

Common causes include a misspelled filename extension, an incorrect key, a higher-priority file overriding the setting, or a vendor configuration loaded later.

Container and virtual machine boundaries

Containers share the host kernel. A process inside a container generally cannot change kernel-wide sysctl values unless the administrator grants the required capability. Even when the container can read a parameter, it may be observing a host-level setting that the container is not permitted to modify.

Check the container runtime’s settings and capabilities rather than assuming host commands apply inside the container:

Terminal window
docker inspect <container-name>
podman inspect <container-name>

The practical result is that some parameters must be set on the host, some can be configured by the container runtime, and some remain under host control. Namespaced network parameters often behave differently from global parameters.

Virtual machines have their own guest kernel and therefore their own sysctl namespace. The hypervisor may still impose limits on CPU, memory, storage queues, and network devices, so a guest-level change cannot compensate for a host-level bottleneck.

Do not copy host sysctl values into a container without checking namespaces. A network setting in one namespace may be irrelevant or misleading in another.

Troubleshooting common errors

sysctl: error setting key 'vm.swappiness': permission denied

This error usually means the process does not have permission to write the parameter. Use sudo for a host-level change and confirm that the setting belongs to the host rather than a restricted container namespace.

Terminal window
sudo sysctl -w vm.swappiness=10

sysctl: error setting key 'net.core.somaxconn': invalid argument

This error indicates that the supplied value is outside the accepted range or conflicts with another requirement. Read the current value and inspect the kernel documentation for that parameter:

Terminal window
sysctl net.core.somaxconn
sudo sysctl -w net.core.somaxconn=4096

Use a value that the kernel accepts, then verify it independently.

sysctl: cannot stat /proc/sys/...: No such file or directory

The parameter does not exist under that path in the running kernel. It may have been renamed, removed, compiled out, or exposed under a different namespace. Search the live tree and inspect the kernel version:

Terminal window
uname -r
find /proc/sys -type f | grep 'parameter-name'

A parameter documented for a newer kernel may not exist on an older kernel.

sysctl: permission denied on key 'kernel.xxx'

Some parameters are read-only after boot, either by design or because their initialization requires kernel privileges. Check the documentation and the value under /proc/sys. If the parameter can only be supplied at boot, use the distribution’s kernel-boot configuration rather than a runtime sysctl write.

The value changes, then returns to the old value

Several processes can override a setting after startup. Check for systemd units, scripts, container runtimes, monitoring agents, and cloud-init configuration that write to the same key.

Search systemd and configuration directories:

Terminal window
sudo grep -R --line-number 'vm.swappiness' /etc/systemd /etc/sysctl.conf /etc/sysctl.d /usr/lib/systemd
sudo grep -R --line-number 'sysctl' /etc/cloud /etc/cloud.cfg /etc/cloud.cfg.d

The value may also be changed by a kernel subsystem during a later lifecycle event. Record the value immediately after boot and again after services start.

The system performs worse after tuning

Restore the recorded baseline first. Then identify whether the regression came from the parameter, an unrelated restart, a cache effect, or a workload change. Change one parameter at a time and rerun the same test.

For web services, compare error rate, p50, p95, and p99 latency. For databases, compare throughput, lock waits, I/O latency, and memory pressure. For network services, compare retransmissions, packet drops, throughput, and tail latency.

Reviewing existing kernel tuning

Before changing a host, inspect the current configuration across all relevant directories:

Terminal window
sudo grep -R --line-number --include='*.conf' \
/etc/sysctl.conf \
/etc/sysctl.d \
/usr/lib/sysctl.d \
/usr/local/lib/sysctl.d

Also inspect the live values and compare them with the documented baseline:

Terminal window
sysctl -a > ~/kernel-tuning/sysctl-current.txt
diff -u ~/kernel-tuning/sysctl-before.txt ~/kernel-tuning/sysctl-current.txt

Large diffs are not automatically defects. They can reflect normal service changes, container runtime adjustments, or boot-time kernel initialization. Review each changed key and identify who or what made the change.

Use systemd-analyze cat-config when you need to determine which configuration files systemd sees:

Terminal window
systemd-analyze cat-config systemd/sysctl.conf

For an auditable change, commit the file to configuration management rather than editing it directly on a running server. A minimal Ansible example looks like this:

- name: Configure host kernel parameters
ansible.builtin.template:
src: templates/70-api-latency.conf.j2
dest: /etc/sysctl.d/70-api-latency.conf
owner: root
group: root
mode: "0644"
notify:
- reload kernel sysctl
- name: Reload kernel parameters
ansible.builtin.command: sysctl --system
when: kernel_sysctl_changed

For a systemd unit that uses ansible.builtin.command, run the task with changed_when based on the command result or use a suitable module that reports the actual change.

Choosing values based on evidence

There is no universal “best” sysctl.conf. Parameters interact with each other, with the kernel version, and with the application. The application often determines the outcome more than the kernel parameter does.

A measured tuning decision should include the baseline, the proposed value, the expected effect, the test method, and the rollback condition. For example:

Issue: memory reclaim causes repeated swap activity during peak load.
Baseline: vm.swappiness=60
Change: vm.swappiness=10
Test: replay the same workload for 30 minutes
Accept when: swap-in rate falls and p99 latency stays within the agreed limit
Rollback: restore vm.swappiness=60

This format prevents a temporary experiment from becoming unexplained permanent configuration.

It also helps during kernel upgrades. Record the kernel version with the change, rerun the workload on the new kernel, and compare behavior before keeping the old tuning value. A parameter may have different defaults or semantics after an upgrade.

A minimal production policy

Most systems should start with a small set of administrator-owned overrides and leave the remaining defaults under the distribution and kernel maintainers’ control. Good candidates for a documented override include a host-specific memory setting, a network queue limit tied to observed drops, or a logging change made for a specific incident. Each override should have an owner and a reason.

Avoid shipping large tuning collections copied from blogs. Every extra parameter creates another interaction, another upgrade concern, and another value that can hide the actual cause of a performance problem.

Use sysctl --system only after reviewing the files. Keep a rollback path, test changes under representative load, and verify the values after reboot. The best-tuned host is not the one with the largest buffer or the lowest swappiness value. It is the one whose behavior has been measured, explained, and kept under control.


Sources and further reading

  • Linux kernel documentation: Documentation/admin-parameters/sysctl.txt and Documentation/admin-sysctl/
  • sysctl(8) manual page
  • systemd-sysctl.service(8) manual page
  • proc(5) manual page
  • vmstat(1), iostat(1), sar(1), nstat(8), ss(8), and ethtool(8) manual pages
found this useful? share it →
Written by

Dzubayyan Ahmad

System Administrator, SRE & Technical Support Engineer specialising in web hosting infrastructure — Linux servers, automation, and monitoring. Writing these notes since 2015 so future-me can find the fix again.