Learning center

CPU rose 40% after a deploy. More work per request, or more requests?

After a deploy, CPU rises because each request costs more, because there are more requests, or because the release added background work. Extra requests come from retries, a new client or a changed mix of routes; background work is anything no request asks for. Divide CPU seconds by requests for each route, and read CPU while the instance serves nothing. Total CPU per request rises in all three cases, so it cannot separate them; per-route CPU per request rises only for more work, the request count by route rises only for more requests, and idle CPU rises only for background work.

The symptom and three explanations#

A fictional search-api service deployed v42 at 10:00 UTC. Its instances went from about 1.0 core each to about 1.4 cores, and the service's overall request rate rose about 7%, which nobody thought could explain 40%. Three explanations:

  • More work per request. v42 changed the search ranking, and each /search does more computation.
  • More requests. A client released the same morning retries /search on a short timeout, so searches, the expensive route, are a larger share of traffic.
  • A background task. v42 added a cache refresher that runs every few hundred milliseconds whether or not anyone is searching.

The headline metric for this question is usually CPU per request: process CPU divided by all requests. It rose in all three worlds of the lab below, for three different reasons.

What each explanation predicts#

ObservationMore work per requestMore requestsBackground task
Total CPUrisesrisesrises
Process CPU divided by all requestsrisesrises if the extra requests are the expensive kindrises
CPU per request for /search alonerisesflatflat, or up slightly from contention
CPU per request for /item aloneflatflatflat
Request rate of /searchflatrisesflat
CPU with no requestsflatflatrises

Each of the last four rows singles out one explanation. Per-route cost and per-route rate together account for all the CPU that requests use; whatever remains, measured with no requests at all, belongs to work that is not a request.

The lab: measure it, not simulate it#

The script handles 2,200 requests in one thread and measures real CPU. A request hashes 16 KB blocks: 20 for /item and 200 for /search. In the work world a search hashes 360 blocks; in the traffic world 160 extra searches arrive, as retries would; in the background world a thread hashes 1,600 blocks every 30 ms. It reads per-request CPU with time.thread_time(), which counts the CPU time of the current thread, and the whole process with time.process_time(), which counts every thread's user and system time and not time spent asleep. Then it sleeps two seconds with no requests and reads process CPU again. time hashlib releases the GIL while hashing more than 2,047 bytes, so the background thread runs in parallel with the requests. hashlib

import hashlib, random, sys, threading, time

BLOCK = bytes(16_384)

def work(units):                                  # one unit is one 16 KB hash
    for _ in range(units):
        hashlib.sha256(BLOCK).digest()

def handle(route, world):
    units = 20 if route == "/item" else 200
    if world == "work" and route == "/search":
        units = 360                               # the new release does more per search
    work(units)

def background(stop):                             # a periodic task added by the release
    while not stop.is_set():
        work(1600)
        stop.wait(0.03)

if len(sys.argv) < 2 or sys.argv[1] not in ("baseline", "work", "traffic", "background"):
    sys.exit("usage: python3 cpu.py baseline|work|traffic|background")
world = sys.argv[1]
rng = random.Random(42)
routes = ["/item"] * 2000 + ["/search"] * 200
if world == "traffic":
    routes += ["/search"] * 160                   # a client now retries searches
rng.shuffle(routes)

stop = threading.Event()
if world == "background":
    threading.Thread(target=background, args=(stop,), daemon=True).start()

cpu = {"/item": 0.0, "/search": 0.0}
p0, w0 = time.process_time(), time.perf_counter()
for route in routes:
    t0 = time.thread_time()                       # CPU of this thread only
    handle(route, world)
    cpu[route] += time.thread_time() - t0
busy_cpu, busy_wall = time.process_time() - p0, time.perf_counter() - w0

p0 = time.process_time()
time.sleep(2)                                     # no requests at all
idle_cpu = (time.process_time() - p0) / 2
stop.set()

n = {r: routes.count(r) for r in cpu}
print(f"{world:10} requests {len(routes)} (/search {n['/search']}) | process CPU {busy_cpu:4.2f} s in {busy_wall:4.2f} s | "
      f"CPU per request: /item {cpu['/item'] / n['/item'] * 1000:4.2f} ms, /search {cpu['/search'] / n['/search'] * 1000:5.2f} ms | "
      f"idle CPU {idle_cpu * 100:3.0f}% of a core")

Save it as cpu.py. Write down which column will move in each world, then run:

for w in baseline work traffic background; do python3 cpu.py "$w"; done

Python 3.11 on a 4-vCPU Linux VM printed:

baseline   requests 2200 (/search 200) | process CPU 1.03 s in 1.04 s | CPU per request: /item 0.26 ms, /search  2.55 ms | idle CPU   0% of a core
work       requests 2200 (/search 200) | process CPU 1.42 s in 1.42 s | CPU per request: /item 0.25 ms, /search  4.53 ms | idle CPU   0% of a core
traffic    requests 2360 (/search 360) | process CPU 1.43 s in 1.49 s | CPU per request: /item 0.26 ms, /search  2.54 ms | idle CPU   0% of a core
background requests 2200 (/search 200) | process CPU 1.60 s in 1.15 s | CPU per request: /item 0.27 ms, /search  2.80 ms | idle CPU  41% of a core

Process CPU divided by all requests went from 0.47 ms in the baseline to 0.65, 0.61 and 0.73 ms in the three worlds, so that ratio rose every time. The work world alone raised the cost of a search (2.55 to 4.53 ms). The traffic world alone raised the number of searches, by 7% of all requests but 80% of searches. The background world alone used CPU with no requests, 41% of a core.

The search cost in the background world rose about 10% as well, because the two threads competed for the same cores and memory. A background task can make requests a little more expensive, so judge the per-route row by the size of the change, not only its direction.

These are real measurements, so the milliseconds differ by machine and run; across two runs here they moved by under 0.3 ms. The prediction fails if per-route CPU per request moves as much in the traffic world as in the work world, or idle CPU rises outside the background world. Change 360, 160 or 1600 to make each effect larger or smaller.

Read it on a real system#

Prometheus client libraries export process_cpu_seconds_total, the process's total user and system CPU time. Prometheus client library guidelines The first two rows of the table are:

sum by (instance, version) (rate(process_cpu_seconds_total{service="search-api"}[5m]))

sum by (instance, version) (rate(process_cpu_seconds_total{service="search-api"}[5m]))
  / sum by (instance, version) (rate(http_server_request_duration_seconds_count{service="search-api"}[5m]))

The request rate by route answers the "more requests" column directly:

sum by (http_route) (rate(http_server_request_duration_seconds_count{service="search-api"}[5m]))

If the rate of one route rose, split it by client to find who sends the extra requests. Request rate doubled: users or retries?

CPU per request by route needs attribution inside the process, which a process-wide counter cannot give. A CPU profile with route labels does it: in Go, pprof.Do runs a function with labels added to its context, and the CPU profile records those labels with its samples. runtime/pprof In Python, middleware can record time.thread_time() around each request on synchronous workers, as the lab does. Compare the per-route figure between versions over the same minutes.

For idle CPU, read the CPU of the threads that are not serving requests. top -H -p PID shows individual threads instead of a sum per process, and a thread named for a scheduler or refresher that is busy while request threads are idle is the background task. top(1) Quiet hours with near-zero traffic give the same reading for the whole process. Taking one instance out of the load balancer to measure it at zero traffic changes production state, so treat it as a deploy step.

Limits#

A per-route average hides a change in what one route is asked to do. If a client starts sending larger searches, /search costs more per request without any change in the code. Split the route by request size or by client before blaming the release.

More requests and more work can arrive together, especially when the new release makes a route slower and clients retry it. Then both rows move, and the share each contributes is what the fix needs.

Background work that runs only under load, such as a flush triggered by request volume, does not appear in idle CPU. It shows as CPU that does not belong to any route's requests: the gap between process CPU and the sum of per-route CPU. For finding the resource that limits throughput rather than the one that grew, see Find the saturated resource under load. For the method behind the table, see Choose the observation where explanations disagree.

Questions#

How do I measure CPU per request?

Divide the process's CPU seconds by its requests over the same window for a first look, then attribute CPU to routes with a labelled profiler or per-request thread CPU. The whole-process ratio moves with the route mix, so use it to notice a change, not to explain one.

Why did CPU rise when request rate rose only a little?

Because the extra requests can be the expensive kind. In the lab, 7% more requests, all of them searches, raised process CPU by about 40%.

Can a background job make requests slower without using much CPU?

Yes. It can hold a lock that requests need, fill a connection pool or compete for disk. CPU shows only one of those, which is why the investigation of slow requests reads more than CPU. Latency is high while CPU is low

One month of free code review.

New organizations get one calendar month of hosted code review for private and public GitHub repositories. No card or cloud connection required. Eligibility and fair-use terms.

Start free with GitHub

Related reading