Investigate CPU hotspots from process selection to perf stacks

Investigate CPU hotspots from process selection to perf stacks

Investigate CPU hotspots from process selection to perf stacks

When an application process keeps consuming CPU and API responses slow down, first identify which process and execution path account for the work. Only then decide whether to change code or configuration. A dedicated server reduces interference from other customers’ workloads, but it does not eliminate lock contention, redundant computation, or queues inside the application. This article uses perf on Ubuntu Server 24.04 to collect time-bounded samples from a running Linux application process, producing evidence that can be reviewed and compared.

1. Establish the baseline and distinguish work from waiting

Before starting, record the application version, start time, request types, concurrency, and error rate. Choose a reproducible workload window rather than directly comparing cache warm-up with steady-state operation. AmdSrv’s EPYC 7543P is a single-socket system with 32 cores and 64 threads. Process CPU percentages may be measured in units of one logical CPU, so a tool reporting 100% does not necessarily mean the entire server is fully utilized.

First obtain the PID from the service manager, then check the command line and threads. Run the following commands in Bash, using the service name from your deployment:

read -r -p 'Service unit: ' UNIT
PID=$(systemctl show "$UNIT" -p MainPID --value)
[[ "$PID" =~ ^[1-9][0-9]*$ ]] || exit 1
ps -p "$PID" -o pid,lstart,etime,pcpu,pmem,args
top -H -p "$PID"

MainPID may refer to a wrapper process while a child process handles the requests. Follow the process tree to identify the worker before sampling. For an application with multiple workers, start with one representative instance, but do not assume its results apply to every instance.

If latency rises without high CPU consumption, investigate waits, downstream response times, and application queues instead. CPU sampling primarily explains code that is executing; it does not reconstruct the full time spent blocked.

A hotspot shows where samples are concentrated, not that the function is defective. Save the workload conditions and application metrics with every report; without them, percentages lack the context needed for a sound judgment.

2. Prepare the tools and collect controlled counters

Install tools that match the currently running kernel. If a new kernel has been installed but the server has not rebooted, match uname -r, not the latest version in the repository.

sudo apt-get update
sudo apt-get install linux-tools-common "linux-tools-$(uname -r)"
perf --version
uname -r
cat /proc/sys/kernel/perf_event_paranoid

If the repository does not provide a matching package, first verify the kernel’s source and its corresponding tools. Do not mix in binaries of unknown origin. If permissions are insufficient, use authorized privilege escalation rather than treating globally relaxed profiling permissions as the default fix.

Start with a fifteen-second counter run to check task consumption and whether hardware events are available:

sudo perf stat -p "$PID" \
  -e task-clock,cycles,instructions,context-switches,cpu-migrations,page-faults \
  -- sleep 15

task-clock is the accumulated CPU time consumed by the monitored task. With multiple threads running in parallel, it can exceed wall-clock time. Context switches and page faults also need to be interpreted against request volume. The ratio of instructions to cycles is not an application performance score, and two results cannot be meaningfully compared without considering their workloads.

If events are unsupported, cannot be counted, or show substantial multiplexing, retain the raw output and reduce the event set. Do not replace missing values with zero. You can initially use a software clock event to locate execution paths.

3. Record time-bounded samples with call stacks

Create a directory accessible only to administrators and give the recording an explicit filename. The frequency and duration below are a starting point for troubleshooting, not a universal capacity guarantee:

sudo install -d -m 0700 /var/lib/perf-evidence
sudo perf record \
  -o /var/lib/perf-evidence/cpu-before.data \
  -e cpu-clock -F 99 \
  --call-graph dwarf,8192 \
  -p "$PID" -- sleep 30

The software event cpu-clock finds hotspots based on CPU execution time. Do not directly compare its sampling results with reports based on other events. DWARF unwinding captures portions of the user stack; it generally costs more than recording instruction addresses alone and produces larger files.

During sampling, monitor application latency, error rate, CPU usage, and available space in the directory. If performance deteriorates unacceptably relative to the pre-sampling baseline, stop the collection. Then reduce the frequency, shorten the duration, or profile only one worker. Do not keep increasing profiling overhead merely to obtain complete call stacks.

If warnings report lost samples, treat the recording as limited evidence. Reduce the sampling volume first, then check for resource pressure. If the service restarts during the recording window, the old PID’s recording does not automatically represent the new instance. Verify the PID again and create a separate file.

4. Read the hotspots, resolving symbol issues first

Use the same recording to inspect functions’ own consumption and their call paths separately:

sudo perf report --stdio --no-children \
  -i /var/lib/perf-evidence/cpu-before.data \
  --sort comm,dso,symbol
sudo perf report --stdio \
  -i /var/lib/perf-evidence/cpu-before.data

The first report disables accumulation from child calls, making it easier to see which functions received samples directly. The second is used to follow calling relationships. A parent function’s accumulated percentage may include its children, so do not add the percentages at each level of a call chain and treat the result as total consumption.

If you see [unknown], raw addresses, or broken stacks, first check whether the executable or shared libraries have been upgraded or replaced. Preserve the build IDs, program files, and debug symbols that correspond to the recording. The same filename does not mean the same build. Debug symbols must match the production binary; do not rebuild the program and force the new symbols onto old addresses.

DWARF unwinding can still be affected by truncated stacks, missing unwind information, and similar limitations. JIT-compiled programs require symbol mappings from the runtime. If a hotspot lies in a runtime or kernel function, follow the call path to find what triggered it rather than immediately changing kernel parameters.

Recordings may contain function names, paths, addresses, and user-stack contents. Handle them as sensitive diagnostic material, and do not upload them to public support-ticket attachments or code repositories.

5. Validate under the same load and keep changes reversible

Change only one variable per iteration, such as removing a redundant serialization step or adjusting one part of an algorithm. Preserve the original configuration and program version, then generate cpu-after.data using the same warm-up procedure, request distribution, concurrency, and sampling parameters.

At a minimum, compare three groups of metrics together: CPU cost per request, request latency and throughput, and error rate. Lower total CPU usage accompanied by lower throughput does not, by itself, demonstrate an improvement. A smaller hotspot percentage may simply mean that other paths are consuming more CPU. When comparing reports, also verify that the event type, number of target processes, and effective recording duration match.

Repeat collection for each version to determine whether the difference exceeds the natural variation within the same version. If the workloads cannot be aligned, document the environmental changes and mark the result as pending validation rather than claiming a confirmed gain.

Finally, archive the sampling commands, version identifiers, application metrics, and conclusions. Remove raw recordings that are no longer needed according to your internal rules for sensitive material. The engineering task is not complete when you have a ranked list of hotspots. It is complete when you can explain what the change addresses, how to reproduce the result, and how to restore the original version if metrics deteriorate.

Frequently asked questions

Should the function with the largest perf percentage always be optimized?

No. The percentage describes the distribution of sampled events. Check request latency, throughput, and the function's purpose before changing it; a CPU profile alone cannot explain waiting.

How should unknown frames be investigated?

Match executable files, shared libraries, and debug symbols to the versions present during recording, then check the unwinding method. JIT applications also need runtime symbol mappings.

AmdSrv Dedicated Server with AMD EPYC 7543P, from $458/month

From deployment notes to configuration checks

Choose a server based on memory, storage, and network requirements. The customer manages the operating system and data backups.