Contents
- Baseline Before You Tune
- The Average Is Lying to You
- The USE Method, Resource by Resource
- RED: The View From the Service
- Finding the Real Bottleneck
- The Ceiling Is Usually Software
- Why 80% Utilization Is a Cliff
- Load Testing That Resembles Reality
- Forecasting, Headroom, and Right-Sizing
- Common Analysis Mistakes
- The Bottom Line
Baseline Before You Tune
A finance application server runs at 22% average CPU. The dashboard is green. The average response time is 200 ms. Users open a ticket every Monday morning saying the system "hangs." Someone proposes doubling the vCPU count, because that is the knob everybody knows how to turn. Six weeks and a change window later, the average response time is 195 ms and users still open the ticket every Monday.
Nothing about that story is unusual. It happens because the team started tuning before it had a baseline, and because the only number it looked at was an average. This article assumes you already have telemetry — metrics scraping, log aggregation, dashboards, whatever your stack is. The hard part is not collecting data. The hard part is deciding which number is the bottleneck and which number is a passenger.
A baseline is not a screenshot of a dashboard. It is a recorded set of measurements at known load, with known configuration, over a period long enough to include your real cycles. For most business applications that means at least one full week, because the Monday 08:00 login storm, the Friday batch run, and the month-end close all look nothing like Wednesday at 14:00. If you tune against Wednesday, you have tuned against the load profile that was never the problem.
The baseline needs to capture four things per tier: request rate, latency distribution, resource utilization, and error rate. And it needs a config snapshot alongside it — JVM heap flags, thread pool sizes, connection pool maximums, kernel tunables, hypervisor reservations. Without the config snapshot you cannot answer the only question that matters after a change: did this help, and by how much?
Rule of Thumb: Change one variable per test cycle, and re-run the same measured workload. If you change three tunables at once and throughput improves 15%, you have learned nothing except that one of the three helped and possibly that another one hurt.
The Average Is Lying to You
Return to that 200 ms average. Suppose the p99 is 4 seconds. Those two numbers describe a broken system, not a healthy one. If you serve 5 million requests a day, the slowest 1% is 50,000 requests over four seconds — and they are not randomly distributed across users. Slow requests cluster: on the largest accounts, on the reports with the most rows, on the sessions that hold the most state. A relatively small group of users experiences your application as consistently unusable while your average says everything is fine.
It gets worse when a page fans out. If rendering one screen requires ten backend calls and each has a 1% chance of hitting the slow tail, roughly one in ten page loads includes at least one slow call. The Google SRE book makes this point directly: the tail latency of a component becomes the typical latency of anything that depends on several instances of it.[1] Averages also hide bimodality. A workload that is 90% cache hits at 5 ms and 10% cache misses at 2 s averages out to about 205 ms — a value that describes zero actual requests.
Track percentiles, and track them at the right granularity. A p99 computed over a 24-hour window smooths away the fifteen-minute window where everything fell apart. Compute over 1-minute or 5-minute buckets and look at the maximum of those buckets over the day. Also be careful how percentiles are aggregated: averaging the p99 of ten servers does not give you the p99 of the fleet. That requires merging the underlying distributions, which is what histogram-based metrics exist for.
Note: Define your service level objective — the SLO, the performance target you have committed to and will be held to — on a percentile and a threshold together, not on an average. "99% of requests under 500 ms, measured in 5-minute windows" is testable and arguable. "Average under 300 ms" is neither — it can be met by a system that is on fire.
The USE Method, Resource by Resource
Brendan Gregg's USE method gives you a checklist that finishes. For every resource, check utilization, saturation, and errors.[2] Utilization is the percentage of time the resource was busy. Saturation is the degree to which work is queued waiting for it. Errors are error events. The insight that makes the method valuable is that saturation, not utilization, is what users feel — a disk at 100% utilization with a queue depth of 1 is fine, and a disk at 60% utilization with a queue depth of 12 is not.
The method is deliberately quick: it is designed to eliminate healthy resources fast so you stop looking at them. Work through the table below in ten minutes and you will usually be left with one or two suspects.
| Resource | Utilization | Saturation | Errors |
|---|---|---|---|
| CPU | Per-core busy % from mpstat -P ALL; ignore the fleet average | Run queue length (vmstat column r) vs core count; pressure stall /proc/pressure/cpu; hypervisor steal time | Machine check exceptions, thermal throttle counters |
| Memory | Anonymous/RSS in use vs total, excluding page cache | Swap in/out rate (si/so), page scan rate, /proc/pressure/memory, direct reclaim | OOM kills in dmesg; allocation failures; GC OutOfMemoryError |
| Disk | %util from iostat -x — treat as a rough signal on NVMe, which is parallel | Average queue size aqu-sz and await/latency percentiles; I/O pressure stall | SMART reallocated sectors, controller/path errors, filesystem errors in the journal |
| Network | Throughput vs link speed and packets/sec vs realistic PPS ceiling | NIC ring buffer drops, qdisc backlog drops, TCP retransmits, listen backlog overflows | Interface error counters, CRC errors, carrier changes |
Two entries in that table catch people out. First, memory utilization: on Linux, "free memory is near zero" is normal and healthy, because the kernel uses spare RAM as page cache. The number that indicates memory pressure is reclaim activity and swap traffic, not the free counter. Second, network on virtualized or cloud instances: you can be nowhere near the advertised bandwidth and still be at the ceiling, because the real limit for small-packet workloads is packets per second, not gigabits per second. Cloud vendors document per-instance-type network and I/O credit limits explicitly, and those limits are frequently the invisible wall an application hits.[3]
RED: The View From the Service
USE is bottom-up, from the resource. RED is top-down, from the service: Rate (requests per second), Errors (failed requests per second), Duration (latency distribution). Popularised by Tom Wilkie, it maps cleanly onto the Google SRE "four golden signals" of latency, traffic, errors, and saturation.[1]
You need both. RED tells you whether users are suffering and which service is responsible. USE tells you which resource inside that service is the cause. Investigating with only RED gets you as far as "the order service is slow"; only USE gets you "disk queue depth is 14 on node 3" without knowing whether anyone cares. Start with RED to pick the service, then run USE inside it.
Split every RED metric by endpoint. Aggregate service latency is a mix of a health check that returns in 2 ms and a report that runs for 8 s, and their ratio changes with traffic mix. When the aggregate p99 moves, the first question is always whether the underlying request mix moved rather than the system getting slower.
Finding the Real Bottleneck
Here is the ten-minute sweep on a Linux application server. Start with vmstat, because in a single line it separates CPU-bound, memory-bound, and I/O-wait-bound.
$ vmstat 1 5
procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
r b swpd free buff cache si so bi bo in cs us sy id wa st
14 0 0 412332 98244 6122880 0 0 0 24 8421 19244 61 12 4 22 1
16 2 0 409120 98244 6122912 0 0 0 112 8677 20113 59 14 3 23 1
Reading it:
r = 14 runnable threads on an 8-core box. Run queue is ~2x cores: CPU saturated.
b = threads blocked on uninterruptible I/O.
wa = 22% of CPU time waiting on I/O. High wa with high r means two problems, not one.
st = steal time. Anything sustained above ~1-2% means the hypervisor is
descheduling this guest; no amount of in-guest tuning fixes that.
si/so = 0. No swapping. Memory is not the issue here.
High wa sends you to the disk. The important columns in iostat -x are latency and queue size, not utilization.
$ iostat -x 1 Device r/s w/s rkB/s wkB/s r_await w_await aqu-sz %util nvme0n1 180.0 2140.0 11520.0 274300.0 0.31 18.44 38.2 99.4 sda 2.0 6.0 16.0 48.0 0.42 0.55 0.01 0.8 Reading it: w_await 18ms on an NVMe device that should answer in well under 1ms. aqu-sz 38 means ~38 requests are outstanding on average: deep queueing. %util 99 on NVMe does NOT by itself mean "full" - the device handles many I/Os in parallel, so utilization saturates long before throughput does. The pair that proves saturation is rising await AND rising aqu-sz together. 2140 writes/sec at ~128kB each: this is a flush-heavy workload. Check the database checkpoint interval and the filesystem barrier settings before buying faster storage.
If the disk is clean but latency is still bad, look at the network. ss -ti exposes per-socket TCP state that no dashboard shows by default.
$ ss -ti state established '( dport = :5432 )'
ESTAB 0 0 10.4.2.11:51844 10.4.2.60:5432
cubic wscale:7,7 rto:204 rtt:3.812/0.44 mss:1448 cwnd:10
bytes_sent:88214 bytes_acked:88214 retrans:0/47 rcv_rtt:4.1
send 30.4Mbps lastsnd:4 lastrcv:4 pacing_rate 60.8Mbps
Reading it:
rtt 3.8ms to a database that should be on the same rack. Check placement -
cross-AZ or cross-host traffic silently adds a millisecond or two per round
trip, and an ORM doing 40 sequential queries per request turns that into
150ms of pure network wait.
retrans:0/47 = 47 cumulative retransmits. Non-zero and growing means loss.
cwnd stuck at 10 (the initial window) means the connection never got to
stretch its legs - short-lived connections, so connection reuse matters
more than bandwidth here.
To attribute the load to a process or thread rather than to the box, pidstat is the fastest tool. pidstat -t breaks a process down per thread, which is how you catch a single-threaded hot spot inside a nominally multi-threaded application.
$ pidstat -t -p 24817 1
TGID TID %usr %system %wait %CPU CPU Command
24817 - 612.0 41.0 8.0 653.0 - java
- 24831 99.4 0.6 88.0 100.0 2 |__scheduler-1
- 24832 4.1 0.2 0.1 4.3 5 |__http-nio-8080-1
- 24833 3.9 0.1 0.1 4.0 1 |__http-nio-8080-2
Reading it:
One thread pinned at 100% of a single core while the worker threads idle.
Adding cores will not help; adding servers will not help. Something in that
scheduler thread is a serialization point. Next step is a thread dump
(jcmd PID Thread.print) or a CPU profile of that thread specifically.
%wait is time runnable but not scheduled - if that is high across all
threads, the box is CPU-saturated or the cgroup CPU quota is throttling.
On Windows the equivalents are performance counters. The counter to reach for first is not CPU but the processor queue and disk latency:
PS> Get-Counter -Counter @(
'\System\Processor Queue Length',
'\Processor(_Total)\% Processor Time',
'\Memory\Pages/sec',
'\PhysicalDisk(_Total)\Avg. Disk sec/Read',
'\PhysicalDisk(_Total)\Avg. Disk sec/Write',
'\TCPv4\Segments Retransmitted/sec'
) -SampleInterval 1 -MaxSamples 30
Reading it:
Processor Queue Length sustained above roughly 2 per logical core is the
Windows analogue of a long run queue.
Avg. Disk sec/Read above 0.020 (20ms) on flash storage is a problem; on a
database volume you want it in single-digit milliseconds.
Memory\Pages/sec matters only alongside a low Available MBytes - on its own
it is mostly mapped-file activity, not pressure.
The Ceiling Is Usually Software
In practice, most application servers hit a configured limit long before they hit a hardware limit. The symptom is distinctive and easy to recognise once you have seen it: throughput plateaus at a flat ceiling while latency climbs linearly, and CPU, memory, and disk all remain unremarkable. That shape means requests are queueing for a slot, not for silicon.
The usual suspects, in the order they tend to bite:
- HTTP thread pools. Apache Tomcat defaults to a maximum of 200 request-processing threads with an acceptCount backlog of 100.[4] Reach both and new connections are refused. More threads is not automatically the answer — if each thread is blocked on the database, raising the pool only moves the queue.
- Database connection pools. HikariCP's default maximum pool size is 10, and its documentation argues that small pools outperform large ones because the database itself has a limited number of cores and spindles.[5] A pool of 200 against a database that can usefully execute 16 concurrent queries just relocates the contention into the database's lock manager.
- File descriptors. Every socket, file, and epoll instance costs a descriptor. Distributions commonly ship a soft nofile limit of 1024, which a busy server passes without effort. Under systemd, LimitNOFILE in the unit file governs — editing /etc/security/limits.conf does nothing for a systemd-managed service.
- Ephemeral ports and TIME_WAIT. Every outbound connection is identified by four values — source address, source port, destination address, destination port — and that combination has to be unique. A server making many short-lived connections to one backend is varying only the source port, so it works its way through a finite range of them, and each connection it closes keeps its port reserved in the TIME_WAIT state for a while before it can be reused. Exhaust that 4-tuple space and new outbound connections simply fail to open, with CPU, memory, and bandwidth all sitting idle. Connection pooling and keep-alive fix this by reusing connections instead of constantly creating new ones; raising the port range only postpones it.
- Locks and single-threaded sections. A global lock, a synchronized cache refresh, or a single-writer log flush caps concurrency regardless of core count.
Rule of Thumb: If throughput is flat while latency rises and no hardware resource is saturated, you are queueing on a configured limit. Find the limit before you buy anything. This one diagnostic has cancelled more hardware purchases than any other in my experience.
Why 80% Utilization Is a Cliff
There is a reason experienced operators refuse to run production servers at 90% utilization even though it looks like efficient use of an asset. Queueing theory describes what happens as a resource approaches saturation: the wait time does not rise proportionally with utilization, it rises far faster, and it approaches infinity as utilization approaches 100%.[2]
At 50% utilization an arriving request often finds the resource free. At 80%, it more often waits behind work already in progress. Near saturation, the queue has little time to drain, so bursts stack and latency rises non-linearly. A safe operating band must leave room for burstiness and response time; 70–80% is a common planning target, not a physical boundary, and the tested latency curve for the workload decides the real limit.
Two corollaries follow. First, the smoother your arrival pattern, the higher you can safely run; bursty traffic needs more headroom than steady traffic at the same average. Second, more parallel servers of the same total capacity tolerate higher utilization than one big one, because a queue served by many workers is less likely to be blocked by one long job. This is a real argument for horizontal scaling that has nothing to do with fault tolerance.
Utilization is a budget for latency. Spending all of it buys you throughput you cannot use, because the response times at that point are outside your SLO anyway.
Load Testing That Resembles Reality
Most load tests measure the load generator rather than the system. The single largest cause is the difference between closed and open workload models.
A closed model has a fixed number of virtual users, each of which sends a request, waits for the response, thinks, and sends the next. Concurrency is capped by design. If the system slows down, the load generator automatically sends fewer requests — the test backs off exactly when a real system would be piling on. An open model sends requests at a specified arrival rate independent of how fast responses come back, which is how real internet traffic behaves. Real users do not wait politely for your server to recover before clicking again; they refresh.
Closed models are appropriate for a fixed population — an internal application with 400 named users and a desktop client. Open models are the right default for anything public-facing or event-driven. Modern tools support both: k6 has constant-arrival-rate executors, Gatling has open injection profiles, and JMeter can approximate one with a throughput shaping timer.
Then there is coordinated omission, named by Gil Tene: when a load generator's request is delayed by the system, every subsequent measurement in that thread is also delayed but is never recorded as such, so the worst pauses are systematically excluded from the results.[6] The effect is not small — it can hide multi-second stalls entirely and make a p99.9 look like a p99. Two defences: use a tool that records latency against intended send time rather than actual send time, and always compare the maximum observed latency against the reported high percentiles. If the maximum is 30x the p99, your percentiles are probably fiction.
The rest of realism is unglamorous: include think time, or you are testing a workload no human generates. Ramp gradually — a 5 to 10 minute ramp with a plateau at each step shows you where the knee is, whereas an instant jump to full load only tells you it broke. Use production-shaped data volume and cardinality, because query plans change when a table goes from 10,000 rows to 10 million. And test at least one sustained run of 30 to 60 minutes: memory leaks, connection pool exhaustion, log volume, and garbage collection pathologies only appear over time.
Note: Testing against a fully warm cache is the classic way to publish a number you can never reproduce in production. Real systems restart, deploy, fail over, and evict. Include a cold-start run and a cache-eviction scenario in the test plan, and quote both numbers.
Forecasting, Headroom, and Right-Sizing
Capacity forecasting is arithmetic on a trend plus judgement about lead time. Take 12 to 18 months of your primary demand driver — not CPU, but the business metric that generates load: orders per hour, active sessions, documents indexed. Decompose it into trend and seasonality. Most enterprise workloads have a weekly cycle, an annual cycle, and one or two calendar spikes that dwarf both. Fit the trend, then add the seasonal peak on top; you size for the peak, not the mean.
Next, convert demand to resources using a measured ratio from your load tests — "one application node sustains 340 orders/hour at p99 under 600 ms" — rather than a vendor sizing sheet. Then subtract headroom for the utilization ceiling discussed above, and add lead time. Lead time is the number teams forget: cloud instances arrive in minutes, but a reserved-capacity change, a licence true-up, a firewall change, or a physical server through procurement and a change advisory board can take one to two quarters. Your capacity plan has to cross that gap.
| Approach | Best for | Limits | Watch out for |
|---|---|---|---|
| Scale up (vertical) | Databases, single-writer systems, licensed-per-instance software, workloads with large shared state | Largest available SKU; NUMA effects; downtime to resize | Cores added beyond the point where the application can use them; per-core licensing costs that scale faster than benefit |
| Scale out (horizontal) | Stateless web/app tiers, queue consumers, read replicas | Shared backend becomes the new bottleneck; coordination overhead | Sticky sessions, non-shared caches, and any serialization point that every node still funnels through |
| Autoscale | Spiky, predictable-shape traffic on stateless tiers | Scale-up latency (image pull, JIT warm-up, cache fill) often exceeds spike duration | Scaling on CPU when the constraint is a connection pool; flapping from aggressive thresholds |
| Optimise code/config | Anything where one query, index, or pool setting dominates | Requires developer time and a profiler | Usually the cheapest option by a wide margin and usually attempted last |
The mirror image of capacity planning is right-sizing what you already over-bought. Virtual machines accumulate safety margin: a VM sized at 16 vCPU for a project that never launched, doubled during an incident in 2023, and never revisited. Oversized guests are not free — they consume host scheduling slots, they make the hypervisor's job harder (co-scheduling many vCPUs that are idle adds latency), and in the cloud they bill continuously. Review the p95 of actual usage over 90 days, not the peak; size to p95 plus your headroom target and leave burst to the platform. Do this on a schedule, because nobody ever revisits a safety margin voluntarily.
Rule of Thumb: Size for the 95th percentile of observed demand plus growth over your procurement lead time, targeting 70–80% utilization at peak. Re-run the exercise quarterly. A capacity plan older than two quarters is a historical document.
Common Analysis Mistakes
Every one of these is something that produces a confident, well-presented, wrong conclusion.
- Tuning the thing that is easy to measure. CPU has a big graph on every dashboard, so CPU gets tuned. Lock contention, connection pool waits, and GC pauses need instrumentation someone has to add, so they get ignored. Ask which resource the request actually spent its time in — if you cannot answer that from your data, the missing instrumentation is the first fix.
- Benchmarking an unrealistic workload. A test that hits three endpoints with identical parameters and a synthetic dataset measures a system nobody runs. Uniform request mixes, unrealistic key distributions, and one-tenth-scale data all shift where the bottleneck lives.
- Chasing CPU when the wait is on disk or a lock. High CPU utilization can be a symptom of I/O waiting (spin-waiting, retry loops, GC under memory pressure) rather than a cause. Check wa, check disk await, and take a thread dump before you conclude the processor is the constraint.
- Adding servers to a serialization point. If one component — a licence server, a sequence generator, a shared lock, a single-writer queue — is the constraint, node number six behaves exactly like nodes two through five: it waits. Horizontal scaling multiplies capacity only for the parts of the path that are actually parallel.
- Load testing against a warm cache. Run the test twice and quote the first number too. Production experiences cold caches every deployment, restart, and failover, which is precisely when it is also under load.
- Comparing runs with different data or configuration. A 20% improvement that came from a database that had been vacuumed between runs is not an improvement. Snapshot config and dataset state with every result.
The Bottom Line
Capacity planning and performance tuning are the same discipline viewed at two timescales. Both depend on measuring the right thing: a latency distribution rather than an average, saturation rather than utilization, and the business driver rather than the CPU graph.
Establish a baseline over a representative business cycle and record the configuration with it. Use RED to identify the service affecting users, then USE to inspect its resources. Determine whether the constraint is hardware, software configuration, or a dependency before spending money. Use a load model that represents production demand, check percentile calculations for coordinated omission, and set headroom from the service objective, failure model, growth rate, and procurement lead time.
The value of this is not primarily technical. Correctly identifying the bottleneck is what lets you decline the hardware request, defend the one you do submit, and stop the quarterly ritual of adding capacity to a system whose real constraint is a connection pool of ten.
References
- Beyer, Jones, Petoff, Murphy (eds.) — "Site Reliability Engineering: How Google Runs Production Systems." O'Reilly Media, 2016. See the chapters on Monitoring Distributed Systems (four golden signals) and Addressing Cascading Failures.
- Gregg, Brendan — "Systems Performance: Enterprise and the Cloud," 2nd edition. Addison-Wesley, 2020. Also the USE Method reference and checklists at brendangregg.com/usemethod.html.
- Amazon Web Services — "Amazon EBS volume types" and "Amazon EC2 instance network bandwidth." AWS Documentation, current edition. Equivalent per-SKU IOPS and network limits are published by Microsoft Azure and Google Cloud.
- The Apache Software Foundation — "Apache Tomcat 10 Configuration Reference: The HTTP Connector" (maxThreads, acceptCount, maxConnections). Apache Tomcat Documentation.
- Brett Wooldridge / HikariCP — "About Pool Sizing." HikariCP Wiki, GitHub.
- Tene, Gil — "How NOT to Measure Latency." Strange Loop / QCon conference presentation, 2015. Source of the coordinated omission analysis.