Introduction
High CPU usage can increase request latency, reduce throughput, and leave less capacity for other services. Start by measuring CPU activity over time and distinguishing application execution from kernel work, I/O waits, interrupts, and virtual-machine steal. Then identify the responsible process or service, capture a profile if needed, and apply a reversible mitigation before changing application or kernel settings. High load or a single top snapshot alone is not enough to diagnose CPU saturation.
Initial Triage and Load Analysis
Before modifying configurations, establish a baseline using the uptime or top command. The three numbers representing the load average correspond to the last 1, 5, and 15 minutes. Load average includes runnable tasks and tasks in uninterruptible sleep, so it is not a CPU-utilization percentage. On an 8-CPU system, a sustained load above 8 is a reason to investigate, not proof that CPU is the bottleneck; compare it with per-core utilization, CPU state, and blocked-task evidence.
Understanding CPU States
The top CPU summary separates CPU time into states. These are clues to investigate, not automatic diagnoses:
- us (user): Time executing application code in user space. Look for processes doing computation, such as compression, encryption, or rendering.
- sy (system): Time in kernel code. Causes include syscall-heavy workloads, networking, filesystem activity, and kernel contention. Profile before assigning a cause.
- id (idle): Time when the CPU is idle. High idle time points away from CPU saturation; check storage, network, locks, and external dependencies.
- wa (I/O wait): Accounting for outstanding I/O while a CPU is otherwise idle. It is not a disk-utilization metric. Compare it with device latency and process state.
- hi (hardware interrupts) and si (software interrupts): Time spent handling interrupts. Check rates, device behavior, and kernel networking before assuming hardware failure.
- st (steal time): In a VM, this is time the hypervisor did not schedule a runnable guest vCPU. Sustained steal may point to host contention. It does not prove overprovisioning; discuss the evidence with your provider.
Compare per-core activity with mpstat -P ALL 1 from sysstat. Use vmstat 1 to watch runnable and blocked tasks alongside context switches. Ignore its first sample. Capture several intervals to see whether a spike persists.
To get a non-interactive snapshot of the top 10 CPU-consuming processes, use the following command:
ps -eo pcpu,pid,user,args --sort=-pcpu | head -10This output helps identify if a single process is “runaway” or if many small processes are collectively exhausting resources.
Deep Dive with Pidstat and Strace
Once a specific Process ID (PID) is identified, you need to understand what it is doing internally. The pidstat utility, part of the sysstat package, allows you to monitor the CPU usage of individual threads within a process.
Monitoring Thread Activity
Run the following to see thread-level CPU consumption every 2 seconds:
pidstat -t -p <PID> 2In multi-threaded applications like Java (JVM) or Node.js, one specific thread might be stuck in an infinite loop while others remain idle. If you see high sy (system) time for a PID, use strace to observe the system calls.
strace -c -p <PID>The -c flag summarizes system-call counts and time during the trace. A high count for futex() or select() is a prompt to inspect the workload, not proof of lock contention or inefficient polling; correlate with thread stacks, application metrics, and a CPU profile. strace can perturb timing, especially when tracing many calls, so keep captures short and targeted.
Profiling Kernel and User Symbols with Perf
When process-level CPU samples do not explain the bottleneck, perf can sample instruction pointers and show which functions account for CPU cycles. Profiling has overhead and may require privileges; use a time-bounded capture, keep the data access-controlled, and check local kernel and distribution guidance before collecting system-wide samples.
Record and inspect a bounded sample
Install the distribution’s perf package if needed, then capture a short interval:
sudo perf record -a -g -- sleep 30sudo perf reportThe -a option samples all CPUs, -g records call chains where supported, and -- separates perf options from the command to profile. Use a process-scoped capture instead when you only need one workload, and confirm that symbols are available for the binaries or kernel you intend to inspect. A missing symbol or stripped binary can limit what the report shows. Remove or protect perf.data after analysis because it can contain sensitive execution details.
Treat report entries as evidence to investigate, not an automatic root-cause label. A kernel function near the top indicates sampled CPU time attributed to that function or call path; it does not alone prove a lock is the cause. Compare the call graph with application metrics, thread activity, and repeat samples before choosing a fix.
Handle perf permissions carefully
If perf reports Permission denied, inspect the policy and follow your distribution’s security documentation:
cat /proc/sys/kernel/perf_event_paranoidThe kernel setting restricts the event types and scope available to unprivileged users; less restrictive values can expose sensitive performance data. Do not lower it globally to make a one-off profile work. Prefer approved privileges or narrowly delegated capabilities, and only change a system-wide setting after a reviewed security decision with a documented rollback.
Remediation: CPU Scheduling and Priority
If you cannot immediately fix the application code, you can use the Linux scheduler to mitigate the impact on other services.
Adjusting Niceness
The nice value ranges from -20 (highest priority) to 19 (lowest priority). Most processes start at 0. To lower the priority of an existing process:
renice -n 10 -p <PID>This tells the Linux scheduler to give this process fewer CPU slices when other processes are demanding time. It does not limit the process if the CPU is otherwise idle.
cpulimit is an optional third-party tool and is not a universal or precise service-level quota. Prefer systemd/cgroup controls for managed services, or a lower scheduler priority for deferrable batch work. If considering cpulimit, check its current upstream documentation and test behavior on the target workload before use; signal-based throttling can disrupt timing-sensitive processes.
Resource Control with Cgroups v2
Modern Linux distributions use cgroups (control groups) to manage resources at the service level. This is the underlying technology used by Docker and Kubernetes, but it can be applied to standard Systemd services.
Limiting a systemd service
For a systemd-managed service, CPUQuota= caps its aggregate CPU time. Unlike nice, a quota also throttles the service when it reaches its allocation. This can protect other units but may increase the service’s queueing and response latency.
Add a drop-in for the confirmed service unit:
[Service]CPUQuota=40%Apply it in a controlled window and check the unit:
sudo systemctl daemon-reloadsudo systemctl restart worker.servicesystemctl show worker.service -p CPUQuotaPerSecUSec -p CPUUsageNSecCPUQuota=40% means a maximum equivalent to 40% of one CPU, not 40% of the whole machine. Values above 100% can allow multiple CPUs. Check for existing drop-ins before changing or removing configuration; removing this setting and reloading systemd restores the unit’s previous effective configuration. Prefer CPUWeight= when the goal is relative sharing under contention rather than a hard cap.
Real-time Monitoring with systemd-cgtop
To see the resource usage of all cgroups in real-time, use:
systemd-cgtopThis provides a cleaner view than top when dealing with containerized workloads or multiple system services, as it aggregates the usage of all child processes within a group.
Handling Interrupt Storms and Softirqs
If top shows sustained high si (software interrupt) time, investigate the interrupt source and workload before changing affinity or enabling services. Network packet processing is one possible cause; compare /proc/softirqs and /proc/interrupts at intervals, and inspect device counters to identify which vectors are increasing. A single snapshot does not show a rate. If one CPU is handling disproportionate interrupt work, determine whether affinity is intentionally configured before changing it.
Some distributions provide irqbalance, but whether it is installed or appropriate depends on hardware and workload. Do not enable it blindly on systems with manually managed affinity or specialized low-latency requirements. Record the original state and compare interrupt distribution and application latency after any change.
taskset can restrict a process to selected CPUs, but pinning is not inherently faster: it can concentrate work on fewer cores, reduce scheduler flexibility, and worsen cache or NUMA locality. Use it only after profiling shows a placement problem, and verify throughput and tail latency. Check online CPU numbering and current affinity first; avoid changing a production process’s affinity without a rollback plan.
Common Case Studies and Troubleshooting
Case 1: High I/O-wait accounting with low CPU use
Suppose top shows low user and system time with substantial wa, while load average is elevated. That combination points to outstanding I/O, but it does not identify the device or prove that storage is saturated. Check process states, storage latency, queue depth, and kernel logs. For example, iostat -xz 1 reports device metrics; interpret %util with the device type and workload. Near 100% can indicate saturation for serial devices, but it does not establish the limit for parallel devices such as modern SSDs or RAID. iotop can help identify processes issuing I/O when it is installed and supported.
Resolve the observed storage or mount problem rather than applying CPU tuning. For an NFS stall, inspect mount and client/server health before attempting recovery; for local storage, check device and filesystem errors before deciding whether a restart or replacement is needed.
Case 2: High load average with idle CPU
A high load average alongside idle CPU can occur when tasks are blocked in uninterruptible sleep (D state). It is not, by itself, proof of a hung NFS mount or a faulty driver.
List such tasks and inspect their command, wait channel, and kernel logs:
ps -eo pid,stat,wchan:32,comm,args | awk '$2 ~ /D/ {print}'journalctl -k --since '-10 min'A task in uninterruptible sleep may not respond to signals until its kernel wait completes; repeated kill -9 attempts do not fix the underlying I/O or driver issue. Identify the resource it is waiting on and follow the relevant storage, filesystem, or driver recovery procedure. A reboot is a last-resort recovery step after assessing impact and data integrity.
Case 3: Web-service CPU saturation
If request latency rises while worker processes consume CPU, measure per-process CPU, request rate, error rate, and latency over the same interval. Compare worker counts and queue depth with configured limits, and profile application work before changing PHP-FPM pm.max_children or adding a cache. Raising worker counts can increase memory use and contention; a cache helps only when profiling identifies repeated work that is safe to cache. Validate any change under representative traffic and check both CPU and memory pressure.
Troubleshooting Error Messages
perf_event_open permission denied
When perf reports Permission denied, the kernel policy may restrict the requested event or scope for this user. Check the current perf_event_paranoid value and your distribution’s documentation. Do not set it to -1 globally without a reviewed security exception; use approved privileges or a narrower capability where possible.
”Fork: Cannot allocate memory”
When the system cannot start new processes, inspect memory pressure and process limits as well as CPU. Use free -h, vmstat 1, and ps -e --no-headers | wc -l; compare process counts with the relevant service’s TasksMax or cgroup pids.max rather than assuming a global PID exhaustion. Swap activity can add latency and I/O load, but swap use alone does not prove a CPU problem. Identify the constrained resource and the responsible service before changing limits or stopping workloads.
Apply a Mitigation You Can Measure and Reverse
When a service is confirmed as the source of sustained CPU saturation, decide whether the priority is protecting other workloads, preserving request latency, or completing a batch job. Record a baseline first: CPU use per core, service throughput, error rate, and latency. Change one setting at a time, keep a rollback path, and compare the same measurements afterward.
Lower priority for non-urgent work
nice and renice change a process’s CPU scheduling priority under contention; they do not impose a hard CPU cap. An operator can lower the priority of a known batch process with renice -n 10 -p <PID>. Confirm the PID and owner before acting, and check the result with ps -o pid,ni,cmd -p <PID>. A lower priority can make the job take longer, so use it only when delaying that work is acceptable.
Set a service-level CPU quota with systemd
For a systemd-managed service, a CPU quota can cap its aggregate CPU time. Unlike nice, a quota also throttles the service when it reaches its allocation. This may protect other units but can increase the service’s queueing and response latency.
Create a drop-in for the exact service after confirming the unit name and existing resource settings:
[Service]CPUQuota=40%Then apply and inspect it during a controlled window:
systemctl daemon-reloadsystemctl restart worker.servicesystemctl show worker.service -p CPUQuotaPerSecUSec -p CPUUsageNSecCPUQuota=40% means a maximum equivalent to 40% of one CPU, not 40% of the whole machine. Values above 100% can allow multiple CPUs. Removing the drop-in and reloading systemd restores the prior unit configuration; check for other drop-ins before removing files. Prefer CPUWeight= when the goal is relative sharing under contention rather than a hard cap.
Avoid automatic process killing
Do not put kill, kill -9, or service restarts into a CPU threshold script. A high-CPU process can be a legitimate database query, compiler, or traffic spike; killing it can interrupt work or cause data loss. Monitor and alert first, include the process/service identity and a time window, and require an operator or an application-specific health policy to decide remediation.
Kernel and Firmware Settings: Change Only for a Measured Cause
Kernel and CPU-frequency settings are not general fixes for a busy server. Availability and behavior vary with kernel, driver, firmware, power policy, and hardware. Capture current values and workload metrics, check the vendor and kernel documentation, change one policy at a time, and define how to restore the original state.
Transparent Huge Pages
Transparent Huge Pages (THP) can help some workloads and hurt others. Do not disable THP just because CPU use is high or because khugepaged is visible. Check the application and database vendor guidance, kernel documentation, and latency or CPU profiles first. If testing THP policy, use the distribution-supported mechanism, measure under representative load, and make the change reversible; writing directly to sysfs is temporary and may not persist across reboot.
CPU frequency policy
The performance governor requests the highest frequency allowed by the policy limits; it does not guarantee a fixed maximum frequency, and it can increase power use and heat. The available governors depend on the driver and platform. Do not set every CPU policy to performance by default. Compare the current policy, frequency, thermal state, and workload latency, then test any supported policy change against the machine’s power and cooling constraints.
Optimizing Application Context Switching
High context switching occurs when the CPU spends more time switching between tasks than actually executing them. This is visible in vmstat.
vmstat 1The cs column counts context switches, while in counts interrupts. Interpret both as rates over a known interval, then compare them with CPU use and application behavior. A large context-switch count alone does not show that switching dominates CPU time, and it does not identify the cause. Thread-pool sizing depends on the workload: CPU-bound work, blocking I/O, runtime design, and downstream limits all matter. Measure queueing, throughput, latency, and CPU before changing worker counts; there is no worker-count formula that applies to every workload.
A Practical Diagnostic Sequence
- Confirm the symptom. Capture CPU use over several intervals with
mpstat -P ALL 1; compare the trend with request latency, throughput, and error rates. - Separate CPU work from waiting. Inspect
topCPU states,vmstat 1, load average, and blocked tasks. High load is not synonymous with CPU saturation. - Find the workload. Sort processes with
psortop, then group activity by service or cgroup withsystemd-cgtopwhere available. - Inspect relevant threads. Use
pidstat -t -p <PID> 1to see whether one thread or many contribute. Capture the interval while the symptom is present. - Profile only when needed. A short, access-controlled
perfsample can identify hot code paths. Usestracefor a focused system-call question, not as a substitute for a CPU profile. - Mitigate reversibly. Lower the priority of deferrable work or set a systemd CPU quota only when its impact on latency is acceptable. Preserve the prior configuration and measure the result.
- Escalate with evidence. If kernel, storage, hypervisor, or hardware signals remain, collect the relevant logs and counters and involve the responsible provider or application owner.
A useful incident record includes the time window, affected service, CPU and latency trends, process or cgroup identifiers, commands used, changes made, and rollback result. This makes it easier to distinguish a recurring code path from a one-off traffic burst and avoids repeating risky tuning without evidence.
CPU use is one signal among several. A sound diagnosis connects it to workload behavior, service impact, and measurements gathered during the same interval; a mitigation is successful only if it improves the service objective without shifting the problem elsewhere.