Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Operations 18 min read

3-Minute Guide to Diagnose 100% CPU Spikes in Production

A practical 3-minute framework for diagnosing 100% CPU spikes in production: identify the offending process and thread, distinguish user vs system vs I/O wait vs steal time, use perf and strace for call stacks, apply language-specific forensics for Java, Python, and Go, check container CPU throttling, and apply safe mitigations like rate limiting, scaling, and controlled rollbacks with verification.

0–3 Minutes: Confirm Impact Boundary

First determine whether the spike affects a single instance, a single node, a single Pod, or the entire service. CPU metrics must be broken down into user, system, iowait, steal, and softirq; load average includes tasks waiting for CPU and uninterruptible I/O, so high load does not directly mean insufficient CPU capacity.

Run the following commands to capture a baseline snapshot (outputs are examples, not real data):

date -u +'%FT%TZ'
uptime
nproc
# -H shows threads, sorted by CPU. Observe several rounds to avoid a single instantaneous peak
top -H -b -n 3 -d 1 | head -n 80
# Sample every second for 10 seconds: us, sy, wa, st correspond to user, kernel, I/O wait, and stolen time
mpstat -P ALL 1 10
# List top 20 processes by CPU; RSS helps identify processes with memory issues
ps -eo pid,ppid,user,stat,pcpu,pmem,rss,etime,cmd --sort=-pcpu | head -n 21
Example output
PID      USER   %CPU  ELAPSED  CMD
18234    app    386.0 00:18:02 java -jar service.jar

On multi-core hosts a single process can exceed 100%, indicating it uses multiple logical CPUs. Record PID, startup parameters, start time, and parent PID to avoid mistaking cron jobs, backups, log compression, or security scans for business processes.

PID='<PID>'
ps -p "$PID" -o pid,ppid,user,lstart,etime,pcpu,pmem,args
tr '
0' ' ' < "/proc/$PID/cmdline"; echo
readlink -f "/proc/$PID/exe"
# systemd service status, recent logs, and restart history
sudo systemctl status '<service_name>' --no-pager
sudo journalctl -u '<service_name>' --since '15 minutes ago' --no-pager | tail -n 300
# Observe run queue, context switches, I/O, and memory paging
vmstat 1 10
iostat -xz 1 10

If iowait is high, CPU busy is only a symptom; prioritize checking disk latency, remote storage, write amplification, and backup tasks. If steal is high, the issue may be hypervisor resource contention. If softirq is high, check network packet rate and connection storms. Do not simply add CPU for these cases.

# Connection count and TCP states, read-only
ss -s
ss -tan | awk 'NR>1 {state[$1]++} END {for (s in state) print s, state[s]}' | sort
# Pull error, timeout, retry evidence from application logs for the last 15 minutes
journalctl -u '<service_name>' --since '15 minutes ago' --no-pager |
  rg -i 'timeout|retry|exception|error|oom|rate limit' | tail -n 200

Process Located: Find Thread, Call Stack, and Syscalls

When a single process shows high CPU, the next step is to pinpoint the exact thread. Sampling should be short and low-intrusion; production debugging tools themselves add overhead. For latency-sensitive services, run first on a single canary instance and record start and end times.

PID='<PID>'
top -H -b -n 1 -p "$PID" | head -n 40
ps -L -p "$PID" -o pid,tid,pcpu,stat,comm --sort=-pcpu | head -n 20
# perf is a sampling tool requiring kernel permissions and symbol environment; verify availability first
sudo perf --version
sudo perf top -p '<PID>'
# Short sampling to generate call-stack report; run only on approved canary host
sudo perf record -F 99 -p '<PID>' -g -- sleep 30
sudo perf report --stdio | head -n 120

Hot functions in perf report are the evidence. If the hotspot is JSON serialization, regex, compression, or encryption, the optimization path differs completely from a slow database. If the hotspot is network I/O or lock contention, continue verifying the call path; do not guess based solely on function names.

# Short syscall trace; limit time and scope for high-frequency services
sudo timeout 15 strace -f -tt -T -p '<PID>' \
  -e trace=network,desc,process 2>&1 | tail -n 200
strace

can confirm loops of connect, poll, read, write, futex, or failed retries, but it adds runtime cost and must not stay attached to critical production processes for long. Command output is only sampling evidence; cross-validate with logs and metrics.

# Check file descriptors, connections, and executable to rule out handle leaks or abnormal child processes
sudo lsof -p '<PID>' | head -n 100
ls -l "/proc/<PID>/fd" | wc -l
# View cgroup constraints; paths vary by cgroup v1/v2 and runtime
cat /proc/<PID>/cgroup
systemd-cgls --no-pager | head -n 120

Java, Python, and Container Forensics

Typical JVM CPU evidence is matching high-CPU thread IDs (TIDs) with thread dumps. Convert decimal TID to hexadecimal, then match nid in jstack. Thread dumps contain business class names and possible parameter data; store them per company data policy.

PID='<Java PID>'
top -H -b -n 1 -p "$PID" | head -n 30
printf 'tid decimal=%s hex=0x%x
' '<thread TID>' '<thread TID>'
jcmd "$PID" Thread.print > "threads-$(date -u +%Y%m%dT%H%M%SZ).txt"
# Multiple samples are more reliable than a single dump; do not restart app between samples
PID='<Java PID>'
for i in 1 2 3; do
  jcmd "$PID" Thread.print > "threads-$i.txt"
  sleep 10
done
# GC, heap, and runtime flags; jcmd subcommands depend on JDK version
jcmd '<Java PID>' GC.heap_info
jcmd '<Java PID>' VM.flags
jstat -gcutil '<Java PID>' 1000 10

If high CPU correlates with frequent Full GC, verify allocation rate, heap size, object lifecycles, and leaks before expanding thread pools. Heap dumps are high-risk, space-consuming, and may contain sensitive data; execute only after approval, available disk, and controlled storage.

# Python service: confirm interpreter, threads, and sampling tool; py-spy requires separate install
ps -p '<Python PID>' -o pid,args
py-spy top --pid '<Python PID>'
# Go service with protected pprof endpoint: collect 30-second CPU profile
curl --fail --silent --show-error \
  'http://127.0.0.1:<pprof port>/debug/pprof/profile?seconds=30' \
  -o cpu.pprof
go tool pprof -top cpu.pprof

The pprof endpoint must not be exposed publicly. If not enabled or protected by network policy, confirm with service owner and use proper access method; do not temporarily open uncontrolled debug ports.

# Kubernetes: explicit namespace, check resource usage, restarts, and events
kubectl -n '<namespace>' top pod '<pod>' --containers
kubectl -n '<namespace>' describe pod '<pod>'
kubectl -n '<namespace>' get events --sort-by=.lastTimestamp | tail -n 80

When a container is CPU-throttled, the application may show high latency while the host still has idle CPU. Simply raising the limit affects node packing and other workloads; first check request, limit, node headroom, HPA behavior, and whether CPU throttling metrics exist.

# Metric names depend on actual kubelet/cAdvisor exports
sum by (namespace,pod,container) (
  rate(container_cpu_usage_seconds_total{namespace="<namespace>",container!=""}[5m])
)
# Metric names depend on actual kubelet/cAdvisor exports
sum by (namespace,pod,container) (
  rate(container_cpu_cfs_throttled_seconds_total{namespace="<namespace>",container!=""}[5m])
)

Contain Impact: Rate Limiting, Scaling, Isolation, and Rollback

Mitigation must be evidence-driven. High traffic with normal per-request latency may need ingress rate limiting or horizontal scaling; a single-instance infinite loop should be drained from the load balancer then restarted; database timeouts triggering retry storms require limiting retries and restoring the dependency, not unbounded application scaling.

# Gracefully drain one instance from Kubernetes Service: verify labels and replica count first
kubectl -n '<namespace>' get pod '<pod>' --show-labels
kubectl -n '<namespace>' label pod '<pod>' '<traffic-label-key>-' --overwrite

This changes traffic matching for the Service; before executing, confirm selector, canary strategy, and label restoration. Rollback means re-adding the original label and observing readiness, error rate, and connection count; do not batch-drain under unknown traffic pressure.

# Scale progressively when downstream has capacity, wait for rollout to complete
kubectl -n '<namespace>' get deploy '<deployment>' -o jsonpath='{.spec.replicas}{"
"}'
kubectl -n '<namespace>' scale deploy '<deployment>' --replicas='<new replica count>'
kubectl -n '<namespace>' rollout status deploy/'<deployment>' --timeout=5m
# Nginx rate-limiting example; define zone in http block first
limit_req_zone $binary_remote_addr zone=api_per_ip:10m rate=20r/s;

location /api/ {
  limit_req zone=api_per_ip burst=40 nodelay;
  proxy_pass http://<upstream_name>;
}

Before config changes, backup, run syntax check, and canary reload. Rate limiting rejects or delays requests; define whitelist, error codes, retry behavior, and business impact; do not paste this snippet into an unknown context.

#!/usr/bin/env bash
set -euo pipefail
CONF='/etc/nginx/nginx.conf'
STAMP="$(date -u +%Y%m%dT%H%M%SZ)"
sudo cp -a "$CONF" "$CONF.$STAMP.bak"
sudo nginx -t
sudo systemctl reload nginx
sudo systemctl status nginx --no-pager

If error rate rises after reload, restore backup config, run nginx -t again, then reload; do not use kill -9 as a substitute for proper config rollback.

# Controlled systemd service restart: only after stack traces, logs, and drain are done
sudo systemctl restart '<service_name>'
sudo systemctl is-active '<service_name>'
sudo journalctl -u '<service_name>' --since '5 minutes ago' --no-pager | tail -n 100

Restart impact depends on statefulness, queue partition ownership, connection migration, and idempotency guarantees. Verify healthy instance capacity and session strategy first; if restart cannot maintain availability, handle via drain or rolling update.

Verification

CPU dropping is not the sole closure condition. Must verify request success rate, P95/P99 latency, run queue, I/O wait, error/retry rates, downstream latency, and whether temporary rate limits or scaling are still needed.

#!/usr/bin/env bash
set -euo pipefail
for i in 1 2 3 4 5; do
  date -u +'%FT%TZ'
  ps -p '<PID>' -o pid,pcpu,pmem,etime,args
  vmstat 1 1 | tail -n 1
  sleep 60
done
kubectl -n '<namespace>' top pod -l 'app=<app label value>' --containers
kubectl -n '<namespace>' logs deploy/'<deployment>' --since=10m |
  rg -i 'panic|fatal|timeout|exception|error' | tail -n 100

After incident, gradually revert temporary scaling, rate limits, or debug switches, observing at least one business cycle per step. Postmortem must record timeline, hot process/thread, call stacks/metrics, root-cause evidence, impact scope, actions taken, and rollback results. Without logs, metrics, config diffs, events, or call stacks, a claim remains a hypothesis, not a root-cause conclusion.

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

KubernetesRate Limitingproduction debuggingperfstraceLinux performanceCPU troubleshootingJava thread dump

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion