Sub topic 3
Finding the bottleneck before you scale
This chapter assumes you know the basics of client-server web architecture, the four main server resources (CPU, memory, disk, network), and what a web server and a database do. It also assumes you have met the terms latency, throughput, and utilization in the previous chapter. Here you will use those measurements to decide what to scale.
Why measure first
Adding capacity costs money and adds operational work. If you add it in the wrong place, you pay for it and the system stays just as slow.
A bottleneck is the one resource or component that limits the throughput of the whole system. It is the first thing to saturate as load rises. Everything downstream of it waits, and everything upstream of it queues. Making the bottleneck faster raises the system's limit. Making anything else faster changes almost nothing.
Consider a web application with these stages for each request:
- The load balancer accepts the connection.
- The application server runs code.
- The application queries the database.
- The application renders and returns the response.
Suppose the database can answer 400 queries per second, and each request needs two queries. The database limits the system to 200 requests per second. Doubling the number of application servers does not change that number. You have bought machines that spend their time waiting for the database.
The workflow of this chapter is a loop:
- Observe the symptoms.
- Form a hypothesis about the saturated resource.
- Confirm it with measurements.
- Change one thing.
- Measure again.
Reading the symptoms
Users do not report "the database CPU is saturated". They report that pages are slow or that errors appear. Start from what you can observe and narrow down.
| Symptom | Likely meaning | First thing to check |
|---|---|---|
| Latency rises sharply at a certain request rate, throughput stops growing | A resource is saturated | Utilization of each resource at that rate |
| Latency is high even at low load | Slow code or slow dependency, not a capacity problem | Per-request traces, slow query logs |
| Only the slowest 1% of requests are slow | Queueing, garbage collection pauses, or one slow dependency | Percentile latency (p99) by endpoint |
| Errors such as timeouts or "too many connections" | A limit has been reached, such as a connection pool | Pool sizes, limits, and queue lengths |
| One server is busy while others are idle | Uneven distribution of work | Load balancer settings and request distribution |
The second row matters most for the scaling decision. If a single request is slow when the system is idle, then more machines will not help. Scaling adds capacity to serve more requests at once. It does not make one request faster.
The saturation curve
A system under rising load usually behaves in three phases. At low load, latency is flat and throughput grows in step with the request rate. Near capacity, latency begins to climb because requests wait in queues. Past capacity, throughput stops growing or even falls, and latency and error rates grow quickly.
The bottleneck is the resource that reaches its limit first as you move from the first phase to the second. A load test that increases the request rate step by step, while recording utilization of every resource, shows you which one it is.
The resources to inspect
Check each of the four basic resources, and also the limits that software imposes.
CPU
High CPU utilization on a server is the most obvious sign of a compute bottleneck. Look at two numbers: overall utilization and the run queue (the number of processes waiting for a CPU). A machine at 95% CPU with a long run queue is saturated. A machine at 95% for one core while seven other cores idle suggests a single-threaded program, and a bigger or more numerous set of cores will not help it.
Memory
Memory pressure shows up as swapping, where the operating system moves memory pages to disk, or as processes killed by the out-of-memory killer. Swapping turns memory accesses that take nanoseconds into disk accesses that take microseconds or milliseconds, so latency rises sharply. Watch for available memory trending toward zero and for any swap activity.
Disk
Disk saturation shows up as high I/O wait (CPU time spent waiting for disk), long disk queue lengths, and high per-operation latency. Databases are the usual victims. Compare the observed operations per second and throughput with the limits of the disk or volume type.
Network
Network limits include bandwidth, packets per second, and connection counts. A server returning large files can fill its network link while CPU stays low. Watch for dropped packets, retransmissions, and exhausted ports.
Software limits
Many bottlenecks are not hardware. Examples are a database connection pool of 20 connections, a thread pool of 200 workers, a limit on open file descriptors, or a lock that serializes access to a shared object. These show up as waiting with low hardware utilization. If every resource looks idle but latency is high, look for a limit of this kind.
A utilization table in practice
Suppose you run a load test against one application server and one database. At 300 requests per second you record the following.
| Component | CPU | Memory | Disk busy | Network |
|---|---|---|---|---|
| Application server | 35% | 60% | 5% | 20% |
| Database | 92% | 70% | 88% | 10% |
The database is near saturation on both CPU and disk, while the application server has plenty of room. Scaling the application tier horizontally would add load to a database that is already close to its limit. The right first actions are to look for expensive queries, add an index, cache results, or move the database to a larger machine.
This table is a model of what you want to produce. Build one for your own system before you propose any scaling change.
Utilization and queueing
Why do latencies rise before utilization reaches 100%? Because requests arrive at random times. Even when the average arrival rate is below capacity, bursts occur, and a burst forms a queue. The higher the utilization, the longer a queue gets and the longer it takes to drain.
A simple queueing model shows the shape. For a single server with random arrivals, the average time a request spends in the system is proportional to 1 / (1 − utilization). The following script prints the multiplier.
for utilization in [0.5, 0.7, 0.8, 0.9, 0.95, 0.99]:
multiplier = 1 / (1 - utilization)
print(f"{utilization:.0%} utilized -> latency x{multiplier:.0f}")At 50% utilization the multiplier is 2. At 90% it is 10, and at 99% it is 100. This is a simplified model and real systems differ in detail, but the curve explains a common observation: a system that looks fine at 70% utilization can be unusable at 95%. It is also why teams commonly plan to keep critical resources well below full utilization, often in the range of 60% to 70% at peak, so that bursts do not push them onto the steep part of the curve.
Tools and techniques
You do not need a complete observability platform to start. You need a way to see utilization, latency percentiles, and where time goes inside a request.
- System metrics. Tools such as
top,vmstat,iostat, andsaron Linux show CPU, memory, and disk. Monitoring agents collect the same data over time so that you can compare it with load. - Request metrics. Record request count, error count, and latency percentiles (p50, p95, p99) for each endpoint. Averages hide the slow tail.
- Tracing. A distributed trace records the time a request spends in each service and each database call. It tells you which stage dominates.
- Slow query logs. Most databases can log queries that take longer than a threshold. A single unindexed query can account for most of the load.
- Load testing. Generate realistic traffic at increasing rates in a test environment and record the point at which latency climbs. This gives a measured capacity figure instead of a guess.
A basic way to capture the effect of saturation is to measure latency percentiles at several request rates and plot them next to utilization. The place where p99 latency leaves its flat region is your practical capacity limit.
Common errors
- Scaling the wrong tier. Adding application servers when the database is the limit, as in the example above. The fix is to measure each tier at the same load.
- Looking only at averages. Average CPU of a cluster may be 40% while one node is at 100%. Average latency may be fine while p99 is ten seconds. Use percentiles and per-node data.
- Treating a code problem as a capacity problem. A missing index, a query inside a loop (the "N+1 query" pattern), or an inefficient serialization step can consume as much capacity as a large traffic increase. Fixing it is usually cheaper than adding hardware and is worth trying first.
- Ignoring the next bottleneck. After you fix one, another resource becomes the limit. Removing the database bottleneck may expose the application server CPU or a connection pool. Expect to repeat the loop.
- Testing with unrealistic data or traffic. A test with a tiny dataset fits entirely in memory and hides disk problems. A test with uniform requests hides hot keys, where a few items receive most of the traffic.
- Confusing correlation with cause. A resource that is busy is not always the bottleneck. A busy resource is only a limit if work is waiting for it. Check queue lengths and wait times, not utilization alone.
From bottleneck to scaling choice
Once you know the bottleneck, the next chapters give you options. The result of your measurement narrows the choice.
- A single saturated resource on one machine, with code that is already reasonably efficient, points to a bigger machine (vertical scaling) or to spreading the work over several machines (horizontal scaling).
- A bottleneck that is a lock, a single-threaded component, or one shared database points to design changes first, because more copies of the application do not remove the shared limit.
- A bottleneck that is uneven distribution points to load balancing or partitioning, not more capacity.
Summary
A bottleneck is the first resource to saturate, and only raising its capacity raises the system's limit. Start from symptoms, then inspect CPU, memory, disk, network, and software limits for every tier at the same load. Use percentiles and queue lengths instead of averages. Remember that latency climbs steeply as utilization approaches 100%, so capacity planning should leave headroom. Check for code-level fixes before buying capacity, and measure again after every change.
Exercise
A load test of one application server and one database shows these numbers at 500 requests per second. Application server: CPU 40%, memory 55%, disk 3%. Database: CPU 45%, memory 80%, disk 97% busy with a long queue. p99 latency is 4 seconds, up from 120 ms at 100 requests per second. Your manager proposes adding four more application servers. What do you say, and what do you investigate first?
Show answer
Do not add application servers. The database disk is saturated (97% busy with a long queue), so it is the bottleneck, and more application servers would send it even more work. First look at the slow query log and query plans for missing indexes or queries that read far more data than needed, and check whether caching could reduce reads. If the workload is already efficient, consider a faster disk or volume type, more memory so more data stays cached, or a read replica for read traffic. Then rerun the load test and check which resource saturates next.
Exercise
A single server has an average CPU of 25% across its 8 cores, yet requests are slow at peak. Name two possible explanations that do not involve CPU capacity, and one measurement for each.
Show answer
One explanation is a single-threaded or lock-bound code path: one core is at 100% while the others idle, so the average hides it. Measure per-core CPU utilization. Another is a software limit such as a database connection pool that is too small, so requests wait for a connection. Measure pool usage and wait time for a connection. (Disk or network saturation are also valid answers, measured with I/O wait and queue length or link utilization.)