The symptom and three explanations#
A fictional orders-api service, a JVM with a pool of request workers, went from a p50 of 40 ms to about 800 ms at 15:10 UTC. Its CPU stayed below a quarter of one core and the error rate did not change. In the incident channel:
- A pool exhausted by a slow downstream. The
inventoryservice it calls got slow, every worker is waiting for a reply, and new requests queue for a free worker. - Lock contention. A recent change wraps the ledger update in a lock, and requests now take turns.
- CPU throttling. The container's CPU limit is lower than the process needs in bursts, so the kernel pauses it every scheduling period even though average usage looks low.
All three keep CPU low and raise latency. For the first and second, the CPU is idle because threads are asleep; for the third, the process wants the CPU and is not allowed it. The CPU graph cannot tell asleep from not allowed.
What each explanation predicts#
| Observation | Slow downstream holds the pool | Lock contention | CPU throttling |
|---|---|---|---|
| Latency up, CPU low | yes | yes | yes |
| Workers busy against pool size | all busy | all busy | not necessarily |
| Thread dump: where workers are | reading from a socket to the downstream | one holds the lock, the rest wait to enter it | running application code |
| Java thread state of waiting workers | RUNNABLE in a socket read, or WAITING | BLOCKED on one monitor | RUNNABLE |
| Downstream client latency | up | normal | normal or up slightly |
nr_throttled in the cgroup's cpu.stat | flat | flat | rises with periods |
The thread dump row separates the pool from the lock, and the throttling counter separates the CPU limit from both. Pool occupancy confirms that requests are waiting for workers, but it is full for the first two explanations alike.
The lab: two thread dumps and a CPU limit#
The first script runs 100 requests through a pool of eight worker threads, arriving over one second. In the downstream world each request waits 200 ms for a reply from a slow service. In the lock world each request takes a shared lock and holds it for 25 ms. Halfway through, the script takes a thread dump with sys._current_frames(), which maps each thread to its topmost stack frame, and prints where each worker is. sys It uses only the standard library; the queue length comes from a private attribute of ThreadPoolExecutor, which is fine for a lab.
import collections, concurrent.futures, statistics, sys, threading, time, traceback
if len(sys.argv) < 2 or sys.argv[1] not in ("downstream", "lock"):
sys.exit("usage: python3 pool.py downstream|lock")
world = sys.argv[1]
LEDGER_LOCK = threading.Lock()
def read_from_inventory():
time.sleep(0.2) # stands in for a socket read from a slow downstream
def update_ledger():
with LEDGER_LOCK: # every request needs the same lock
time.sleep(0.025) # and holds it across a short wait
def handle(submitted):
read_from_inventory() if world == "downstream" else update_ledger()
return time.perf_counter() - submitted
pool = concurrent.futures.ThreadPoolExecutor(max_workers=8, thread_name_prefix="worker")
c0, w0 = time.process_time(), time.perf_counter()
futures = []
for _ in range(100): # 100 requests arrive over one second
futures.append(pool.submit(handle, time.perf_counter()))
time.sleep(0.01)
dump = collections.Counter() # a thread dump: where is each worker right now?
for ident, frame in sys._current_frames().items():
name = next((t.name for t in threading.enumerate() if t.ident == ident), "?")
if name.startswith("worker"):
top = traceback.extract_stack(frame)[-1]
dump[f"{top.name}: {top.line.split('#')[0].strip()}"] += 1
waiting = pool._work_queue.qsize() # private, but fine for a lab
latencies = [f.result() for f in futures]
cpu = (time.process_time() - c0) / (time.perf_counter() - w0)
print(f"world={world}: p50 {statistics.median(latencies) * 1000:.0f} ms, CPU {cpu:.0%} of a core, "
f"{waiting} requests queued for a worker at the dump")
for where, count in dump.most_common():
print(f" {count} in {where}")
Save it as pool.py. Before running it, write down what the dump will show in each world: how many workers in which line. Then:
python3 pool.py downstream; python3 pool.py lock
Python 3.11 printed:
world=downstream: p50 909 ms, CPU 1% of a core, 57 requests queued for a worker at the dump
8 in read_from_inventory: time.sleep(0.2)
world=lock: p50 760 ms, CPU 1% of a core, 52 requests queued for a worker at the dump
7 in update_ledger: with LEDGER_LOCK:
1 in update_ledger: time.sleep(0.025)
Both worlds have a median near 800 ms, about 1% of a core and more than 50 requests queued for a worker. The dumps differ: all eight workers sit in the downstream call in one, and seven of eight wait at the same with LEDGER_LOCK: line behind one holder in the other. Latencies and queue lengths come from real sleeps, so they vary by a few percent between runs; the dump lines did not change across runs here. The prediction fails if the lock dump shows workers spread across lines, or the downstream dump shows workers waiting on the lock.
For the third explanation, run a busy loop under a CPU limit of 0.2 cores and read the cgroup's counters. This needs Docker:
docker run --rm --cpus 0.2 python:3.12-slim sh -c '
python3 -c "
import time
t = time.perf_counter()
while time.perf_counter() - t < 3: pass
print(\"3 s of wall time, CPU used:\", round(time.process_time(), 2), \"s\")"
cat /sys/fs/cgroup/cpu.stat 2>/dev/null || cat /sys/fs/cgroup/cpu/cpu.stat'
On this host, which uses cgroup v1, it printed:
3 s of wall time, CPU used: 0.62 s
nr_periods 32
nr_throttled 32
throttled_time 2503227247
nr_bursts 0
burst_time 0
The loop wanted all of three seconds and got 0.62 s of CPU: about a fifth of one core and essentially all of its 0.2-core quota. It was throttled in every one of 32 periods, for 2.5 seconds in total (throttled_time is in nanoseconds on cgroup v1). The kernel's bandwidth documentation describes these fields, and on cgroup v2 the same counters appear as nr_throttled and throttled_usec in cpu.stat. CFS bandwidth control ยท cgroup v2
Read it on a real system#
Take two or three thread dumps a few seconds apart; a thread that sits in the same place in each is waiting there. On the JVM, jstack PID prints the stack traces of the process's Java threads. jstack A thread BLOCKED is "blocked waiting for a monitor lock"; many of them on the same monitor, with one thread holding it, is contention. A thread waiting in a socket read can show as RUNNABLE, because that state includes threads "waiting for other resources from the operating system", so read the stack, not only the state. Thread.State
In Python, faulthandler.register(signal.SIGUSR1) installs a handler that dumps the traceback of all threads when the process receives that signal; it has to be in the code before the incident. faulthandler In Go, the net/http/pprof handlers serve the goroutine profile under /debug/pprof/goroutine, and debug=N with N above 0 returns it as plain text. net/http/pprof
Read the pool's own counters for occupancy: active workers or connections against the maximum, and how many requests wait for one. A database connection pool has its own version of this question. Pool acquire timeout: a busy pool or a struggling database?
For throttling, read the container's cpu.stat twice, a minute apart, and compare the change in nr_throttled with the change in nr_periods:
cat /sys/fs/cgroup/cpu.stat; cat /sys/fs/cgroup/cpu.max # cgroup v2, from inside the container
cpu.max holds the quota and the period, which defaults to 100,000 microseconds. The cgroup v2 documentation notes that the throttling counters in cpu.stat count only throttling from this cgroup's own limit, not from a limit set on a parent. cgroup v2
Limits#
A thread dump is a snapshot. A lock held briefly by many threads in turn may show one waiter in one dump and none in the next, while still adding latency. Take several dumps, or use the runtime's contention profiling, before ruling contention out.
The pool and the lock can be the same thing. A connection pool is a lock with N slots, and a synchronised client wrapper can turn a slow downstream into what looks like monitor contention. Follow the holder of the lock: if it is itself in a socket read, the downstream is the cause.
Throttling shows up as a ratio, not as a thread state. A process throttled in only a small share of periods can still hold a request until the next period starts, up to most of the 100 ms default period, so compare throttled periods with the slow requests' timestamps. When none of the three explanations fits, look for the resource whose queue grows with load. Find the saturated resource under load A process that stops answering altogether, rather than slowly, has its own guide. A service hangs: deadlock or busy loop? For the method, see Choose the observation where explanations disagree.
Questions#
Why is latency high when CPU usage is low?
Requests are waiting for something other than CPU: a free worker, a connection, a lock, a reply, or permission to run under a CPU limit. A thread dump shows which for the first four, and the cgroup's throttling counters show the last.
How do I read a Java thread dump for lock contention?
Look for many threads BLOCKED waiting on the same monitor, and find the one thread that holds it. Its stack shows what the lock is held across. If the holder is in a socket read, the contention is a slow downstream behind a lock.
Does low CPU usage rule out CPU throttling?
No. A container limited to a fraction of a core can be throttled in most scheduling periods while its average usage looks low. In the lab the process used a fifth of a core and was throttled in all 32 periods.