Skip to content

What I Learned Online

Technology

Linux Performance Tuning: CPU & Memory – Quick Wins for Faster Servers

Linux Performance Tuning: CPU & Memory

Photo by Franck V. on Unsplash

When a server is under heavy load, the first thing you notice is either a lagging web page or an application that hangs for minutes. In most cases the culprit is not “the code” but the operating system’s handling of CPU and memory resources. This article walks through a practical workflow to identify, diagnose, and fix those bottlenecks on Linux servers.

Audience – System administrators, DevOps engineers, and performance‑tuning enthusiasts who run production workloads on Linux and want actionable guidance without diving into deep kernel internals.
Search intent – “How do I tune CPU and memory on Linux?” or “What tools help me spot bottlenecks in a Linux server?”.
Central question – Which measurable indicators tell me where the real slowdown is, and how can I correct it?


1. Start with a clear hypothesis

Performance problems rarely show up as a single symptom. A sluggish web service could be caused by:

Symptom Possible root causes
High latency on HTTP requests CPU starvation, disk‑bound DB queries, network congestion
Frequent “Out of Memory” logs Over‑committed RAM, memory leaks, huge page usage
Slow batch jobs Cache misses, suboptimal scheduling, I/O wait

Tip: Write down the observed symptom and list all plausible causes. This keeps your investigation focused.


2. Baseline monitoring – the “what is happening” layer

Before you can fix a problem you need to know when it occurs and how resources are being used. A minimal, repeatable baseline set of metrics is essential.

Metric Tool What it tells you
CPU utilisation (per‑core) top, htop, mpstat Overall load vs. capacity; hot cores
I/O wait & throughput iostat, dstat, sar -b Disk saturation, request latency
Memory usage & swap free, vmstat, smem Resident set size (RSS), page‑in/out rate
Process list with CPU/IO ps auxf --sort=-%cpu,-%mem Identify heavy hitters
System logs for OOM or kernel panics dmesg | grep -i oom Immediate memory pressure signals

Practical checklist

  1. Run a 10‑minute baseline with the system idle and then under typical load.
  2. Capture all metrics into a CSV or time‑series database (e.g., Prometheus) for later comparison.
  3. Note any spikes that correlate with user activity or scheduled jobs.

3. CPU bottlenecks – from symptoms to root causes

3.1 Detecting CPU starvation

CPU starvation happens when the scheduler cannot give enough cycles to all processes, often because a few tasks monopolise cores.

What to look for

  • High per‑core utilisation (>90 %) with low context switches → a single process or thread is hogging.
  • Low load average compared to CPU count but still slow → the scheduler may be over‑aggressive or the process has high latency operations (e.g., system calls).

Tools

Tool Use case
top / htop Quick per‑process view
pidstat -d 1 Per‑process CPU and I/O over time
perf top Live kernel‑space stack traces
eBPF utilities (xtop, xstack) Passive, trace‑point free profiling

Fixes

Issue Fix
A single thread uses >95 % CPU Refactor to multi‑thread or async; add a worker queue.
Kernel stalls (e.g., due to a device driver) Update firmware/driver, or disable the problematic hardware if possible.
Scheduler imbalance on NUMA nodes Use numactl --physcpubind or tune vm.nr_hugepages.

3.2 I/O‑bound CPU usage

Sometimes a process appears CPU‑heavy but spends most time in system calls that block on disk/network.

How to spot it

  • High iowait in sar -w or iostat.
  • pidstat -d shows high %wa for the offending PID.
  • perf record -e sched:sched_switch reveals frequent context switches between a process and the kernel.

Remedies

  1. Use asynchronous I/O (io_uring, AIO) if your workload is I/O‑heavy.
  2. Upgrade storage: SSDs or NVMe for lower latency.
  3. Tune filesystem: noatime, barrier=0 on SSDs; adjust vm.dirty_ratio.

4. Memory bottlenecks – when RAM becomes the limiter

4.1 Over‑commit and swap thrashing

Linux allows processes to reserve more virtual memory than physically available (vm.overcommit_memory). When actual demand exceeds RAM, the kernel swaps pages in/out, causing latency spikes.

Indicators

  • High swap_in/swap_out rates in vmstat.
  • Frequent OOM killer logs (dmesg | grep -i oom).
  • free -m shows 100 % used plus non‑zero swap usage.

What to do

Scenario Action
Swap is active during normal load Increase RAM or lower vm.swappiness.
OOM killer frequently runs Raise ulimit -v for critical processes; isolate them in a cgroup with guaranteed memory.
Memory fragmentation Enable /proc/sys/vm/compact_memory periodically, or use slabtop to find hot slabs.

4.2 Heap and cache leaks

Applications may hold onto memory longer than needed (e.g., due to global caches).

Detection

  • smem -r shows per‑process RSS growth over time.
  • pmap -x <pid> displays private vs. shared pages; a steady rise in private pages indicates a leak.

Mitigation

  1. Profile with Valgrind or AddressSanitizer for C/C++ services.
  2. Use memory pools (jemalloc, tcmalloc) that allow better reclamation.
  3. Implement graceful shutdown hooks to free large caches before restart.

5. Advanced profiling – turning raw data into actionable insights

5.1 eBPF‑based stack sampling (xstack, xtop)

eBPF lets you collect kernel and user‑space stacks without intrusive tracing:

# Sample top CPU consumers over 30 seconds
sudo xstack -p 30

The output shows the exact call paths consuming cycles, helping pinpoint hot functions.

5.2 Kernel performance counters (perf)

perf record -e cpu-clock:ppid=1234 ./myapp records per‑process cycle counts. Combine with perf report to see which kernel functions are being invoked.

When to use

  • Long‑running services where a single function is the bottleneck.
  • Investigating unexplained latency spikes that correlate with specific system calls.

5.3 System‑wide event tracing (sysstat, sar)

Automate collection:

# Collect CPU and memory stats every minute for 24h
sar -u 60 1440 > cpu.txt
sar -r 60 1440 > mem.txt

Then plot with gnuplot or import into Grafana.


6. Tuning strategies – applying what you’ve learned

Problem Quick fix Long‑term strategy
CPU saturation by a single process Add worker threads, reduce algorithmic complexity Refactor code to use async I/O; profile hot paths with eBPF
Disk I/O bottleneck Upgrade to NVMe; enable trim Move to SSD‑only storage; adjust io_scheduler (deadline, noop)
Frequent OOM kills Increase physical RAM; tune vm.swappiness Isolate critical services in cgroups; use memory limits (ulimit)
Memory fragmentation Run echo 1 > /proc/sys/vm/compact_memory Use a slab allocator tuned for your workload (e.g., kmem_cache_reap_threshold)

Remember: Always test changes in a staging environment before production. Small configuration tweaks can have cascading effects.


7. Wrap‑up

CPU and memory tuning on Linux is an iterative dance between observation, measurement, and intervention. By establishing a solid baseline, using targeted tools (top, perf, eBPF utilities), and applying the right fixes—whether it’s adding threads, upgrading hardware, or tightening cgroup limits—you can turn a sluggish server into a responsive, efficient machine.

Takeaway: The most powerful tool in your arsenal is data. Collect it consistently, analyze it thoughtfully, and let the numbers guide your optimisations.

Frequently Asked Questions (FAQ)

What are the most reliable CPU metrics to identify bottlenecks on a Linux server?

Use per‑core utilization (top, htop, mpstat) and I/O wait (iostat, sar -w). High core usage with low context switches usually points to a single process hogging CPU, while high iowait indicates the process is spending time in blocking system calls.

How can I determine if memory pressure is causing performance issues?

Check resident set size (RSS) and swap activity via free, vmstat, or smem. Frequent page‑in/out or a rising swap usage curve signals that the system is over‑committed, which may lead to slowdowns or OOM events.

When should I use eBPF tools like xtop or xstack instead of traditional profilers?

eBPF utilities are lightweight and do not require kernel module loading. Use them when you need low‑overhead, real‑time insight into process behavior or kernel stack traces without disrupting production workloads.

What steps should I follow after identifying a CPU‑starving process?

  1. Profile the offending process with pidstat or perf top.
  2. Refactor to multi‑threading or asynchronous design if it’s a single thread hogging CPU.
  3. If kernel stalls are suspected, update drivers/firmware or disable problematic hardware.

Related Articles

0 0 votes
Article Rating
guest
0 Comments
Oldest
Newest Most Voted
Scroll to Top