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
53 min read

CPU Spike? Rapidly Pinpoint the Culprit Process & Thread with top, perf & jstack

This comprehensive guide walks through a systematic CPU spike troubleshooting workflow: confirm anomaly with top/htop, identify the top-consuming process and thread, analyze thread activity via strace, perf, jstack, py-spy, or pprof, correlate with monitoring metrics, and resolve common scenarios like infinite loops, lock contention, frequent GC, slow queries, cron jobs, and malware.

Problem Background

Production servers often experience sudden CPU spikes from 20-30% to 80-100%, causing slow responses, API timeouts, and user complaints. Causes include code bugs, infinite loops, resource leaks, external attacks, or misfired cron jobs. Ops/DevOps engineers must locate the offending process, thread, or even function call within minutes to stop the bleeding, restore service, then root-cause.

This article presents a complete, battle-tested CPU anomaly investigation process covering initial assessment, process identification, thread isolation, system-call analysis, code hotspot profiling, common scenario handling, risk control, and rollback plans.

Applicable Scenarios

Business service CPU suddenly spikes

Overall system CPU high, unknown process

Process CPU normal but system CPU abnormal

Multiple processes consuming CPU, unclear priority

Java, Python, Go, Node.js high-level language CPU anomalies

Cron jobs or batch scripts causing periodic CPU spikes

External attacks, malicious processes, or cryptominers

Core Concepts

3.1 CPU Usage Composition

Linux CPU usage breaks down into: us (user): user-space CPU time, business code execution sy (system): kernel-space CPU time, syscalls, context switches ni (nice): low-priority process CPU time id (idle): idle CPU time wa (iowait): CPU waiting for I/O hi (hardware interrupt) si (software interrupt) st (steal): CPU stolen by hypervisor in virtualized env

High us usually indicates business code issues; high sy suggests frequent syscalls or context switches; high wa points to disk/network I/O.

3.2 Processes, Threads & CPU

A process contains multiple threads

Threads are the basic CPU scheduling unit

In multi-threaded apps, a single hot thread may not be visible at process level

Java, Go, etc. have different thread models, requiring different investigation approaches

3.3 Context Switch Overhead

Frequent context switches raise sy. Common causes:

Excessive thread count

Intense lock contention

Frequent I/O operations

Signal handling

Excessive system calls

3.4 Soft Interrupts

Network packet processing, disk I/O completion trigger soft interrupts; high si may indicate heavy network traffic or disk I/O overload.

Overall Troubleshooting Flow

1. Confirm CPU anomaly (top/htop/monitoring)
2. Identify top CPU-consuming process (top/ps)
3. Identify top CPU-consuming thread within process (top -Hp PID)
4. Analyze what the thread is doing (strace/perf/pstack/jstack)
5. Correlate with business logs, metrics, code logic to find root cause
6. Execute stop-gap actions (restart, rate-limit, kill process)
7. Fix code or configuration
8. Verify fix effectiveness
9. Postmortem summary

Practical Steps

5.1 Initial CPU Anomaly Confirmation

5.1.1 top for Overall CPU

top

Focus on the %Cpu(s) line, e.g.:

%Cpu(s): 85.3 us,  8.2 sy,  0.0 ni,  5.1 id,  0.5 wa,  0.0 hi,  0.9 si,  0.0 st

Interpretation: us > 70%: business code high CPU, prioritize app processes sy > 30%: frequent syscalls/context switches, possibly too many threads, lock contention, or syscall-heavy workload wa > 20%: CPU waiting on I/O, investigate disk/network si > 10%: high soft interrupts, likely heavy network traffic or disk interrupts id near 0: no idle CPU, system under high load

5.1.2 uptime for System Load

uptime

Example output:

13:25:42 up 15 days,  3:42,  2 users,  load average: 8.52, 6.31, 4.28

Three values = 1-min, 5-min, 15-min average load (runnable + running processes). On a 4-core box, load > 4.0 means overload. If 1-min >> 15-min, it's a sudden spike; if all three high and close, sustained load.

Check core count:

cat /proc/cpuinfo | grep "processor" | wc -l
# or
nproc

If 8 cores: load < 8 normal, 8-16 high, >16 severe.

5.1.3 htop for Real-time Process View

htop

Advantages: per-core usage, sortable process list, tree view, color coding, direct signal sending. Watch for per-core balance, any core stuck at 100%, top processes, process states (R/S/D/Z).

5.2 Locate Top CPU-Consuming Process

5.2.1 top Sorted by CPU

In top, press P (Shift+P) to sort by %CPU descending.

PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND
 1234 app       20   0 2048000 524288  10240 R  85.3  6.4  12:35.67 java
 5678 www       20   0  102400  20480   5120 R  12.1  0.2   1:23.45 nginx
 9012 mysql     20   0 1638400 819200  16384 S   8.5 10.1  45:12.34 mysqld

Key fields: PID, USER, %CPU, %MEM, TIME+, S (state), COMMAND. Focus on processes >50% CPU, multiple same-name processes, unknown names (possible malware), state D (uninterruptible sleep, likely I/O stuck).

5.2.2 ps for Process CPU

ps aux --sort=-%cpu | head -n 20

Shows top 20 processes by CPU. For more detail:

ps -eo pid,user,%cpu,%mem,vsz,rss,stat,start,time,command --sort=-%cpu | head -n 20

5.2.3 Process Detail Inspection

Once PID identified (e.g., 1234): ps -p 1234 -f Output shows UID, PID, PPID, C (CPU%), STIME, CMD. Check PPID to see how launched, STIME for start time, full CMD for arguments.

Working directory: ls -l /proc/1234/cwd Open files: lsof -p 1234 Listening ports:

netstat -tnlp | grep 1234
# or
ss -tnlp | grep 1234

5.3 Locate Top CPU-Consuming Thread Within Process

Process-level CPU is aggregate; need thread-level.

5.3.1 top -H for Threads

top -Hp 1234
-H

shows threads, -p specifies PID. Output shows TID (thread ID) in PID column.

PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND
 1240 app       20   0 2048000 524288  10240 R  45.2  6.4   8:12.34 java
 1245 app       20   0 2048000 524288  10240 R  38.5  6.4   7:45.12 java
 1250 app       20   0 2048000 524288  10240 S   1.2  6.4   0:05.67 java

Record top TIDs, whether CPU sustained, whether all threads hot or just a few.

5.3.2 ps for Thread CPU

ps -T -p 1234 -o pid,tid,%cpu,comm | sort -k3 -nr | head -n 20
-T

shows threads, -o custom columns, sort by 3rd column (%cpu) numeric reverse.

5.3.3 Convert TID to Hex for Java

Java thread dumps use hex native IDs.

printf "%x
" 1240
# output: 4d8

Later search nid=0x4d8 in jstack output.

5.4 Analyze What the Thread Is Doing

5.4.1 strace for System Calls

Traces syscalls in real time, works for any language.

strace -p 1234          # whole process
strace -p 1240          # specific thread
strace -c -p 1234       # syscall stats (run 10-30s, then Ctrl+C)

Example strace -c output:

% time     seconds  usecs/call     calls    errors syscall
------ ----------- ----------- --------- --------- ----------------
 85.23    0.124567        1245     10000           read
  8.45    0.012345         123     10000           write
  3.21    0.004689          46     10000           futex
  2.11    0.003087          30     10000           epoll_wait
------ ----------- ----------- --------- --------- ----------------
100.00    0.145688                    40000           total

Interpretation:

High read / write: I/O intensive

High futex: lock contention

High epoll_wait / select / poll: network I/O wait

High rt_sigreturn / sigreturn: frequent signal handling

High clone: frequent thread creation

Risks: strace significantly slows the traced process; use only on specific threads, limit to 10-30 seconds, prefer -c stats mode if syscalls extremely frequent.

5.4.2 perf for CPU Hotspots

perf

is Linux's built-in profiler, pinpoints hot functions.

Install

# CentOS/RHEL
yum install -y perf
# Ubuntu/Debian
apt-get install -y linux-tools-common linux-tools-generic linux-tools-$(uname -r)

Live Hotspot View

perf top -p 1234

Real-time function-level CPU breakdown. Press s to change sampling interval.

Samples: 12K of event 'cycles', Event count (approx.): 3245678901
Overhead  Shared Object          Symbol
 45.23%  [kernel]               [k] _raw_spin_lock
 12.34%  libc-2.31.so           [.] __memcpy_avx_unaligned
  8.56%  app.so                 [.] calculate_hash
  6.78%  app.so                 [.] process_data

Fields: Overhead (%), Shared Object (library/module), Symbol (function), [k] = kernel, [.] = user-space.

Interpretation:

High _raw_spin_lock: severe lock contention

High business function: that function is CPU hotspot

High memcpy / memset: excessive memory copying

High kernel functions: frequent syscalls or context switches

Record & Report

perf record -p 1234 -g -- sleep 30
perf report
-g

captures call stacks. perf report shows hierarchical overhead; press Enter to expand call chains.

Generate flame graph (requires FlameGraph tools):

perf script | FlameGraph/stackcollapse-perf.pl | FlameGraph/flamegraph.pl > flamegraph.svg

Open flamegraph.svg in browser for visual hotspot analysis.

Risks: low overhead but still run off-peak; limit sampling to 10-30s; perf.data can be large, watch disk space.

5.4.3 jstack for Java Thread Stacks

For Java apps, use jstack.

jstack 1234 > /tmp/jstack_1234.txt
# multiple samples to observe state changes
for i in {1..5}; do
  echo "=== Sample $i at $(date) ===" >> /tmp/jstack_1234.txt
  jstack 1234 >> /tmp/jstack_1234.txt
  sleep 3
done

Search for hex TID: grep -A 50 "nid=0x4d8" /tmp/jstack_1234.txt Example output:

"Thread-12" #28 prio=5 os_prio=0 tid=0x00007f8e4c001000 nid=0x4d8 runnable [0x00007f8e3c0ff000]
   java.lang.Thread.State: RUNNABLE
        at com.example.service.DataProcessor.calculateHash(DataProcessor.java:245)
        at com.example.service.DataProcessor.process(DataProcessor.java:123)
        at com.example.controller.ApiController.handleRequest(ApiController.java:67)
        ...

Focus on thread state ( RUNNABLE, BLOCKED, WAITING, TIMED_WAITING), call stack (which class/method), signs of infinite loops, recursion, lock waits.

If BLOCKED, thread waits for a lock:

"Thread-15" #31 prio=5 os_prio=0 tid=0x00007f8e4c002000 nid=0x4e9 waiting for monitor entry [0x00007f8e3b0fe000]
   java.lang.Thread.State: BLOCKED (on object monitor)
        at com.example.service.CacheService.get(CacheService.java:89)
        - waiting to lock <0x00000000e1234567> (a java.util.HashMap)

Multiple threads waiting on same lock indicates contention.

5.4.4 py-spy for Python

pip install py-spy
py-spy top --pid 1234
py-spy record --pid 1234 --output profile.svg --duration 30

Output shows %Own, %Total, function (file:line). Generates flame graph profile.svg.

5.4.5 pprof for Go

Requires app to expose net/http/pprof.

go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30

If pprof not enabled, fall back to perf or bpftrace.

5.4.6 pstack for C/C++

pstack 1234

Output shows thread call stacks. Run multiple times; if same function appears repeatedly, it's the bottleneck.

Thread 10 (Thread 0x7f8e3c0ff700 (LWP 1240)):
#0  0x00007f8e5c00123d in __lll_lock_wait () from /lib64/libpthread.so.0
#1  0x00007f8e5bffe0a3 in pthread_mutex_lock () from /lib64/libpthread.so.0
#2  0x0000000000401234 in calculate_hash ()
#3  0x0000000000401567 in process_data ()
#4  0x0000000000401890 in worker_thread ()

5.5 Correlate with Monitoring Metrics

5.5.1 Process CPU History (Prometheus)

rate(process_cpu_seconds_total{job="node",instance="192.168.1.10:9100",pid="1234"}[5m])
topk(10, rate(process_cpu_seconds_total{job="node"}[5m]))

Grafana dashboards can show trends: periodic spikes (cron), sudden jumps (code change/traffic surge), sustained high (leak/deadloop).

5.5.2 Context Switches

vmstat 1

Key columns: r (runnable processes, > cores = overload), cs (context switches/sec, >100k = excessive), in (interrupts/sec).

Per-process detail: pidstat -w -p 1234 1 Fields: cswch/s (voluntary, waiting I/O/locks), nvcswch/s (non-voluntary, time-slice expiry, preemption). High voluntary = frequent I/O/lock waits; high non-voluntary = too many threads or lock contention.

5.5.3 Soft Interrupts

cat /proc/softirqs
watch -n 1 "cat /proc/softirqs | head -n 10"
sar -I SUM 1

Watch NET_RX (network receive), NET_TX (network send), BLOCK (block device) for rapid growth.

5.6 Common Scenario Analysis & Handling

5.6.1 Java Dead Loop

Symptoms: single Java thread at 100% CPU, jstack shows RUNNABLE, stack stuck in business method.

Steps: multiple jstack samples to confirm static stack; inspect source at indicated line for while(true), bad for conditions, recursion; if urgent, restart app; add logging to reproduce; fix code and deploy.

Rollback: revert to last stable version; if impossible, rate-limit or degrade.

Verify: CPU normal, no loop logs, monitoring trend OK.

5.6.2 Lock Contention

Symptoms: multiple threads high CPU, many BLOCKED / WAITING in jstack, waiting on same lock; perf shows high _raw_spin_lock, futex.

Steps: count BLOCKED threads; find lock holder's activity; check lock granularity and hold time; check for deadlock ( jstack prints "Found one Java-level deadlock"); if deadlock, must restart; else optimize: reduce lock scope, use lock-free structures, shorten hold time; if immediate fix impossible, rate-limit.

Rollback: revert version; if not possible, restart + rate-limit.

Verify: BLOCKED count drops, sy decreases, latency improves.

5.6.3 Frequent GC

Symptoms: Java CPU high, jstat -gcutil shows frequent Full GC, GC logs show long pauses, app slow/timeouts.

Steps: jstat -gcutil 1234 1000 to watch live. Example output:

S0     S1     E      O      M     CCS    YGC     YGCT    FGC    FGCT     GCT
  0.00  95.23  78.45  98.67  89.12  87.34   1234   12.345    89   45.678   58.023

Old gen (O) near 100% + frequent Full GC = heap too small or memory leak. Full GC >1s = low GC efficiency.

Heap dump (triggers Full GC + STW, do off-peak, watch disk):

jmap -dump:live,format=b,file=/tmp/heap_dump_1234.hprof 1234

Analyze with MAT or jhat for leaks. Temporary fix: increase heap ( -Xmx4g -Xms4g). Permanent: fix leak (release references).

Rollback: revert version; temporarily increase heap.

Verify: Full GC frequency down, CPU normal, latency improved.

5.6.4 Periodic Cron Job Spikes

Symptoms: CPU spikes on schedule (hourly, daily), specific process spikes then auto-recovers.

Steps: confirm timing pattern with sar; check system crons ( crontab -l, /etc/cron.*, systemctl list-timers); check in-app schedulers ( @Scheduled, ScheduledExecutorService, Quartz); optimize task logic (reduce DB queries, batch, cache, fewer loops); if long-running, shard or async; if ill-tuned (e.g., full scan every minute), adjust frequency/logic.

Rollback: disable cron; move execution to low-traffic window.

Verify: CPU no longer spikes periodically; task duration improved.

5.6.5 Malicious Process / Cryptominer

Symptoms: sustained 100% CPU, unknown process name, weird start dir ( /tmp, /dev/shm), odd user, auto-restarts.

Steps: capture process details ( ps -p PID -f, ls -l /proc/PID/exe, ls -l /proc/PID/cwd, lsof -p PID); check network connections ( netstat -tnp | grep PID) for external data exfiltration; kill ( kill -9 PID); delete binary; check for auto-restart via cron, systemd, supervisord, rc.local, watchdog processes; scan for persistence ( grep -r "malicious_file" /etc/cron* /var/spool/cron/, systemctl list-units | grep malicious); rotate credentials, harden system.

Risks: malware may wipe logs, plant backdoors; consider full reinstall or clean backup restore.

Verify: process gone, CPU normal, no reappearance over monitoring period.

5.6.6 Database Query Causing High CPU

Symptoms: MySQL process high CPU, slow query logs pile up, active connections spike.

Steps: SHOW FULL PROCESSLIST; – watch Time >10s, State = Sending data, Copying to tmp table, Sorting result; check slow log ( tail -f /var/log/mysql/slow.log or query mysql.slow_log); EXPLAIN bad queries – look for type=ALL (full scan), key=NULL (no index), high rows; optimize SQL or add index; if urgent, KILL query_id (may rollback transaction); if app-driven, optimize code or rate-limit.

Rollback: drop index if it causes issues ( DROP INDEX idx_user_id ON orders;).

Verify: MySQL CPU down, slow queries reduced, API latency improved.

Command Cheat Sheet

6.1 System CPU

top
htop
uptime
vmstat 1
sar -u 1
mpstat -P ALL 1

6.2 Process CPU

top
ps aux --sort=-%cpu | head -n 20
pidstat -u 1

6.3 Thread CPU

top -Hp <PID>
ps -T -p <PID> -o pid,tid,%cpu,comm | sort -k3 -nr
pidstat -t -p <PID> 1

6.4 Syscall Tracing

strace -p <PID>
strace -c -p <PID>
strace -p <TID>

6.5 CPU Hotspot Profiling

perf top -p <PID>
perf record -p <PID> -g -- sleep 30
perf report

6.6 Java

jstack <PID>
jstack <PID> | grep -A 50 "nid=0x<HEX_TID>"
jstat -gcutil <PID> 1000
jmap -dump:live,format=b,file=/tmp/heap.hprof <PID>
jmap -histo:live <PID> | head -n 30

6.7 Python

py-spy top --pid <PID>
py-spy record --pid <PID> --output profile.svg --duration 30

6.8 Context Switches

vmstat 1
pidstat -w -p <PID> 1

6.9 Soft Interrupts

cat /proc/softirqs
watch -n 1 "cat /proc/softirqs | head -n 10"
sar -I SUM 1

6.10 Process Details

ps -p <PID> -f
ls -l /proc/<PID>/exe
ls -l /proc/<PID>/cwd
lsof -p <PID>
netstat -tnlp | grep <PID>
ss -tnlp | grep <PID>

Configuration Examples

7.1 Prometheus Process CPU Monitoring

Node Exporter collects process_cpu_seconds_total by default.

rate(process_cpu_seconds_total{job="node"}[5m])
topk(10, rate(process_cpu_seconds_total{job="node"}[5m]))

7.2 MySQL Slow Query Log

In /etc/my.cnf:

[mysqld]
slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 2
log_queries_not_using_indexes = 1

Restart: systemctl restart mysqld. Verify:

SHOW VARIABLES LIKE 'slow_query%'; SHOW VARIABLES LIKE 'long_query_time';

7.3 Java GC Logging

JDK 8:

java -Xmx2g -Xms2g \
  -XX:+PrintGCDetails \
  -XX:+PrintGCDateStamps \
  -XX:+PrintGCTimeStamps \
  -Xloggc:/var/log/app/gc.log \
  -XX:+UseGCLogFileRotation \
  -XX:NumberOfGCLogFiles=5 \
  -XX:GCLogFileSize=20M \
  -jar app.jar

JDK 11+:

java -Xmx2g -Xms2g \
  -Xlog:gc*:file=/var/log/app/gc.log:time,uptime,level,tags:filecount=5,filesize=20M \
  -jar app.jar

Log & Metric Observation

8.1 System Logs

dmesg | tail -n 100
tail -f /var/log/messages
journalctl -u <service_name> -f

8.2 Application Logs

tail -f /var/log/app/app.log
grep -i "error\|exception\|slow" /var/log/app/app.log | tail -n 50

8.3 Prometheus Metrics

# System CPU
100 - (avg by (instance) (irate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)
# Process CPU
rate(process_cpu_seconds_total{job="node",pid="1234"}[5m]) * 100
# Context switches
rate(node_context_switches_total[5m])
# Soft interrupts
rate(node_softirqs_total[5m])

8.4 GC Log Analysis

Tools: GCViewer, GCEasy. Quick CLI:

grep "Full GC" /var/log/app/gc.log | wc -l
grep "Full GC" /var/log/app/gc.log | tail -n 10

Troubleshooting Path Summary

1. Receive CPU alert
  ↓
2. top/htop confirm CPU & load
  ↓
3. Sort by CPU, locate top process
  ↓
4. Record PID, cmd, user, start time
  ↓
5. Unknown process? → malware check → kill → clean → harden
  ↓
6. Business app? → top -Hp PID to find hot thread
  ↓
7. Record TID, convert to hex
  ↓
8. Choose tool by language:
   - Java: jstack + jstat
   - Python: py-spy
   - Go: pprof
   - C/C++: pstack + perf
   - Other: strace + perf
  ↓
9. Correlate logs, metrics, code for root cause
  ↓
10. Classify root cause:
    - Dead loop → fix code
    - Lock contention → optimize lock or use lock-free
    - Frequent GC → increase heap or fix leak
    - Slow query → optimize SQL or add index
    - Cron job → optimize logic or reschedule
    - Malware → kill + clean + harden
  ↓
11. Stop-gap (restart/rate-limit/kill/rollback)
  ↓
12. Verify CPU normal
  ↓
13. Fix root cause (code/config/arch)
  ↓
14. Deploy & verify
  ↓
15. Postmortem

Risk Reminders

10.1 Tool Risks

strace

heavily degrades performance; production use with caution, short duration perf low overhead but still limit sampling time jmap -dump triggers Full GC + STW; off-peak only pstack pauses process briefly; caution under high concurrency

10.2 Process Operation Risks

kill -9

may lose data/rollback transactions; try kill (SIGTERM) first

Confirm no pending tasks/transactions before restart

Notify stakeholders before restart

10.3 Database Risks

KILL

query may rollback transaction

Add indexes off-peak; large table index add may lock

Monitor after parameter changes

10.4 Config Change Risks

Kernel params: wrong values can destabilize system

JVM params: test thoroughly before production

App config: verify effect and side-effects

10.5 Bulk Operation Risks

Confirm process list before bulk kill

Confirm file list before bulk delete

Backup data before bulk DB ops

Verification Methods

11.1 CPU Recovery

top
uptime

Check id back to normal, us / sy down, load average normal.

11.2 Process CPU Recovery

ps -p <PID> -o %cpu

11.3 Thread CPU Recovery

top -Hp <PID>

11.4 Business Recovery

API latency normalized

No error logs

Monitoring dashboards green

User feedback clear

11.5 Root Cause Fixed

Code fix: code review + unit tests

Config fix: confirm applied, no side-effects

Cron fix: wait for next run

Malware: continuous monitoring

Rollback Plans

12.1 Code Rollback

cd /opt/app
git log --oneline -n 10
git checkout <last-stable-commit>
./build.sh
./deploy.sh
systemctl restart app
# or Kubernetes
kubectl rollout undo deployment/app

12.2 Config Rollback

cp /opt/app/config.yaml.bak /opt/app/config.yaml
systemctl restart app

12.3 Database Rollback

DROP INDEX idx_user_id ON orders;

12.4 JVM Param Rollback

vi /opt/app/start.sh
# restore -Xmx -Xms -XX:+UseG1GC etc.
systemctl restart app

12.5 Kernel Param Rollback

sysctl -w <param>=<old_value>
# or edit /etc/sysctl.conf, remove new lines, then
sysctl -p

Production Environment Notes

13.1 Pre-Op Prep

Notify stakeholders, explain impact

Prepare rollback, ensure quick revert

Schedule in low-traffic window

Have emergency contacts ready

13.2 During Op Monitoring

Watch CPU live

Watch API latency live

Watch error logs live

Keep rollback commands handy

13.3 Post-Op Verification

CPU normalized

Business healthy

Metrics green

Observe for recurrence

13.4 Documentation & Postmortem

Record symptoms, investigation, root cause, fix

Save commands & outputs

Note pitfalls & lessons

Run postmortem meeting

Update runbooks & processes

13.5 Prevention

CPU usage alerts (system & per-process)

Regular cron job audits

Regular slow query reviews

Regular GC log reviews

Regular system log reviews

Code review gates to catch loops/leaks

Load testing before release

Canary/gated rollouts

Continuous performance & stability tuning

Summary

Sudden CPU spikes are among the most common production incidents. Rapid localization and resolution are core skills for Ops/DevOps engineers.

Key takeaways:

Quickly confirm anomaly, distinguish us, sy, wa, si meanings

Rapidly identify top process and thread

Pick right tool per language: jstack, py-spy, pprof, perf, strace Correlate logs, metrics, code for root cause

Execute stop-gap to restore service

Fix root cause, deploy, verify

Postmortem & build prevention

Common scenarios:

Dead loop: code bug → fix code

Lock contention: coarse granularity/long hold → optimize or lock-free

Frequent GC: heap pressure/leak → increase heap or fix leak

Slow query: bad SQL/missing index → optimize SQL or add index

Cron job: heavy logic/bad timing → optimize or reschedule

Malware: compromise → eradicate & harden

Risk control: tools carefully, process ops carefully, config changes carefully, bulk ops carefully.

Verification & rollback: always verify CPU, business, metrics; have rollback ready; monitor post-fix.

Prevention: comprehensive alerting, code review & load test gates, canary releases, regular log/system audits, continuous optimization.

Following this end-to-end process systematizes CPU spike handling, accelerates recovery, and reduces recurrence through postmortems and preventive measures.

For attribution, corrections or content rights, contactadmin@besthub.dev

Report an issue with this article

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion