34. Performance Tuning
34.1 CPU Troubleshooting
Section titled “34.1 CPU Troubleshooting”When users complain of sluggish response times, the CPU subsystem is typically the first area analyzed.
1. Load Average vs CPU Utilization
Section titled “1. Load Average vs CPU Utilization”- CPU Utilization (
%): Measures the percentage of time the CPU cores are actively processing instructions. - Load Average: Measures the queue length (demand). It counts processes that are runnable on a CPU plus processes waiting in an uninterruptible sleep state (
TASK_UNINTERRUPTIBLE), typically disk I/O.
Diagnostic Matrix:
Section titled “Diagnostic Matrix:”High Load + High CPU % ──► CPU-Bound Bottleneck (Infinite loops, compute spikes, crypto/compression)High Load + Low CPU % ──► I/O-Bound Bottleneck (Disk queues, blocked NFS shares, slow database writes)Low Load + High CPU % ──► Bursting work on a single thread/core (multithreading not utilized)Commands:
# Check load vs CPU core countuptimenproc
# Check CPU utilization breakdown (us, sy, id, wa)mpstat -P ALL 1 32. Context Switching & Interrupts
Section titled “2. Context Switching & Interrupts”A Context Switch occurs when the Linux scheduler pauses one process/thread and loads another onto the CPU core.
- While context switching is a normal feature of multitasking, excessive context switches (> 50,000 to 100,000+ per second) waste significant CPU cycles merely swapping register state and invalidating CPU L1/L2 caches.
Common Causes of High Context Switching:
Section titled “Common Causes of High Context Switching:”- Too many concurrent threads or processes competing for limited cores.
- High rates of network I/O interrupts.
- Lock contention in multithreaded applications (threads constantly sleeping and waking on mutexes).
# Monitor context switches (cs) and interrupts (in)vmstat 1 5
# Detailed context switch breakdown per processpidstat -w 1 5- In
pidstat -w:cswch/s(Voluntary): The thread surrendered the CPU voluntarily (waiting for I/O or sleep).nvcswch/s(Involuntary): The thread was forcefully preempted by the scheduler because its time slice expired. High involuntary switches mean CPU core starvation!
34.2 Memory Troubleshooting
Section titled “34.2 Memory Troubleshooting”Memory issues degrade system performance long before an application outright crashes with an Out-Of-Memory (OOM) error.
Healthy State: High Page Cache + Steady Resident Memory + Zero Swap Activity
Degraded State: Low Available RAM + Active Swap In/Out (si/so > 0) + High Disk I/O Wait
Critical State: Exhaustion + Kernel OOM Killer Invoked + Process / Container Terminated1. RAM, Swap & Cache Metrics
Section titled “1. RAM, Swap & Cache Metrics”- Resident Set Size (RSS /
RES): The actual non-swapped physical memory allocated to a process. - Virtual Memory (
VIRT): Total memory mapped by a process (including shared libraries and mapped files). Often misleadingly large and not an indicator of real RAM usage. - Page Cache: RAM holding cached file data. If applications need memory, the kernel reclaims page cache instantly without penalty.
2. Thrashing & Swap Contention
Section titled “2. Thrashing & Swap Contention”When physical RAM runs out, the kernel constantly moves pages back and forth between RAM and the swap disk. Because NVMe/SATA disks are orders of magnitude slower than RAM, the system grinds to a halt.
# Check if system is actively paging (si = Swap In, so = Swap Out)vmstat 1 5Rule of thumb: A system with 2GB of used swap is fine if si and so remain 0. If si and so are constantly > 0, the system is thrashing.
3. Diagnosing OOM Kills
Section titled “3. Diagnosing OOM Kills”When the kernel runs out of memory, it scores processes via oom_score (based on RAM percentage and oom_score_adj) and terminates the highest offender.
# Check which process was killed and whysudo dmesg -T | grep -i -E "oom|killed process"
# Check OOM score of a specific running processcat /proc/<PID>/oom_score34.3 Storage Troubleshooting
Section titled “34.3 Storage Troubleshooting”Disk performance is governed by three interconnected metrics: IOPS, Throughput, and Latency.
Throughput (MB/s) = IOPS × I/O Block SizeLatency (ms) = Time taken to complete a single I/O operation1. IOPS vs Throughput vs Latency
Section titled “1. IOPS vs Throughput vs Latency”- IOPS (Input/Output Operations Per Second): Number of individual read/write operations processed each second. Critical for databases (PostgreSQL, MySQL) running random reads/writes.
- Throughput (Bandwidth): Volume of data read/written per second (e.g., 250 MB/s). Critical for large file copies, video streaming, or sequential log writes.
- Latency (Service / Wait Time): The time elapsed between a process issuing an I/O request and receiving the response. This is the single most critical storage metric for end-user experience.
2. Identifying Storage Bottlenecks with iostat
Section titled “2. Identifying Storage Bottlenecks with iostat”# Monitor extended disk stats in MB/s every 1 secondiostat -x -m 1What to Look For:
Section titled “What to Look For:”r/s+w/s: Are you nearing your disk’s provisioned IOPS limit (e.g., AWS EBS gp3 default of 3000 IOPS)?rMB/s+wMB/s: Are you hitting the throughput ceiling (e.g., 125 MB/s on standard cloud volumes)?await(Average Wait Time in ms):< 1-5 ms: Normal / fast NVMe SSD.10-20 ms: Warning / congested disk.> 50 ms: Severe bottleneck. Applications will experience database timeouts.
%util: Percentage of time the disk was servicing requests. If%util > 95%, the disk queue is saturated.
34.4 Network Troubleshooting
Section titled “34.4 Network Troubleshooting”Network performance issues manifest as high latency, dropped packets, connection queue overflow, or bandwidth throttling.
1. Bandwidth Saturation
Section titled “1. Bandwidth Saturation”When network interfaces hit their physical or virtual bandwidth caps, packets are buffered and then dropped.
# Monitor real-time network throughput per interfacesar -n DEV 1 3# or install nload / iftopsudo apt install iftop -ysudo iftop -i eth0- Compare
rxkB/s(receive) andtxkB/s(transmit) against the maximum link speed (ethtool eth0 | grep Speed).
2. Packet Loss & Network Latency
Section titled “2. Packet Loss & Network Latency”- Latency (RTT): The round-trip time for a packet to reach the destination and return.
- Packet Loss: Packets dropped along the network path due to congestion, faulty switches, or rate limits.
# Test packet loss and round-trip timeping -c 20 -i 0.2 target_ip
# Interactive traceroute + ping (combines latency + packet loss per hop)mtr -rw target_domain.com3. Connection Queues & Socket Saturation
Section titled “3. Connection Queues & Socket Saturation”If an application cannot process incoming TCP handshakes fast enough, the OS listen queue overflows and drops incoming SYN packets.
# Inspect socket backlog queuesss -lnt- In
ss -lntfor listening sockets:Send-Q: The maximum backlog size (defined bylisten()backlog ornet.core.somaxconn).Recv-Q: The current number of connections waiting to be accepted by the application.- If
Recv-Q > 0and close toSend-Q: The application’s worker threads are blocked or exhausted, causing user connection timeouts!
34.5 60-Second Performance Checklist
Section titled “34.5 60-Second Performance Checklist”When tasked with diagnosing an active performance degradation on a Linux production node, execute these commands in sequence:
# 1. Check uptime, load average, and process countuptime
# 2. Check kernel ring buffer for OOM kills, hardware failures, or network dropsdmesg -T | tail -n 30
# 3. Check live CPU utilization and process resource hogstop -b -n 1 | head -n 25
# 4. Check memory and paging activityfree -hvmstat 1 3
# 5. Check disk I/O saturation and latencyiostat -x -m 1 3
# 6. Check network socket connection backlogss -sss -lnt