System Design Part 1 Measurement basics

Latency, Throughput, and p99: Stop Looking at Averages and Size Thread and Connection Pools with Little's Law

Bill.Lin 12 min read

System Design series Part 1-2 | Previous: The Journey of an HTTP Request | Next: Napkin Math for Capacity Estimates | Series map

Scenario and problem

The load test report says “60 ms average response, handles 400 RPS”, and everyone is relaxed. After launch, though, reports start coming in: “sometimes it hangs for several seconds.” The same week, the database slows down because of one slow query, and then the whole service times out. Someone suggests: “Raise the Tomcat threads from 200 to 1,000 and make the connection pool bigger, and we’ll hold up.”

A 60 ms average service, so why does it hang?1 / 4
A 60 ms average service, so why does it hang?UsersAPI serviceDatabaseUsersAPI serviceDatabase400 RPSqueryavg 60 msUsersAPI serviceopen a page2% hang for 2 sUsersAPI serviceDatabasestill 400 RPS2 s per queryall 200 threads stuckAPI serviceDatabasethreads 200 → 1,000more querieseven slower
  1. A great load test reportThe load test report says 60 ms average response and 400 RPS sustained. The service runs 200 Tomcat threads, and everyone feels safe.
  2. Hangs of several secondsAverages lie: of 1,000 requests, 980 take 20 ms and 20 hang for 2 seconds. The average is about 60 ms, yet not a single request actually took 60 ms. One page sends dozens of requests, so almost every user hits the slowest 1%.
  3. The database slows, all time outOne slow query makes the database take 2 seconds to respond. Traffic is still 400 a second, so the requests sitting in the system at once grow to 400 × 2 = 800. All 200 threads are stuck waiting on the database, later requests can only queue, and then they time out.
  4. Raise threads to 1,000?Someone suggests raising the threads to 1,000 and enlarging the connection pool. But the bottleneck is the database: more threads only pile more concurrent queries onto a database that is already saturated, and it just gets slower.

Both of these come from the same set of ideas: look at the distribution of latency, not the average, and throughput and latency affect each other through queuing. Once you understand them, you can see why raising the thread count usually does not help.

The simplest metrics and their blind spot

The most common report has just two numbers: average response time and QPS. One example is enough to show the problem with averages: of 1,000 requests, 980 take 20 ms, and 20 hang for 2 seconds because of GC or lock waits.

java
import java.util.Arrays;

public class PercentileDemo {

    public static void main(String[] args) {
        long[] latenciesMs = new long[1_000];
        Arrays.fill(latenciesMs, 0, 980, 20);        // 98% of requests take 20 ms
        Arrays.fill(latenciesMs, 980, 1_000, 2_000); // 2% hang for 2 s (GC, lock waits, retries...)
        Arrays.sort(latenciesMs);

        double avg = Arrays.stream(latenciesMs).average().orElseThrow();
        System.out.printf("avg   = %.1f ms%n", avg);
        for (double p : new double[] {50, 95, 98, 99, 99.9}) {
            System.out.printf("p%-4s = %d ms%n", trim(p), percentile(latenciesMs, p));
        }
    }

    // nearest-rank: after sorting, take sample number ceil(p/100 * n)
    static long percentile(long[] sorted, double p) {
        int rank = (int) Math.ceil(p / 100.0 * sorted.length);
        return sorted[Math.max(rank, 1) - 1];
    }

    static String trim(double p) {
        return p == Math.floor(p) ? String.valueOf((long) p) : String.valueOf(p);
    }
}

Output:

text
avg   = 59.6 ms
p50   = 20 ms
p95   = 20 ms
p98   = 20 ms
p99   = 2000 ms
p99.9 = 2000 ms

The 59.6 ms average is a number that no request actually experienced: most people got 20 ms, a few got 2 seconds. The average blends the two groups together and describes neither of them.

Core mechanism

Latency, Response Time, Throughput

  • Response time: the total time from when the client sends a request to when it receives the response, including network, queuing, and processing
  • Latency: strictly speaking, the time a request spends “waiting to be processed”. In practice the two terms are often used interchangeably; in this series, latency means the response time the client sees
  • Throughput: the number of requests completed per unit of time (RPS, QPS, TPS)

The two are not simply inversely related. At low load, more throughput barely affects latency; near saturation, latency climbs steeply.

Percentiles

p99 = 200 ms means “99% of requests finish within 200 ms, and the slowest 1% take longer than 200 ms”. SLOs are usually set at p99; core services with heavy traffic go as far as p99.9.

1% sounds small, but one user opening one page usually sends dozens of requests, so almost every user hits the p99. And the slowest requests often come from the users with the most data (the most orders, the fullest carts), in other words your most important customers.

Fan-out amplifies the tail

If one request has to call N downstream services at the same time and wait for all of them, a single slow one makes the whole request slow:

java
public class FanOutTail {

    public static void main(String[] args) {
        double slowRate = 0.01; // each downstream has a 1% chance of exceeding its own p99
        for (int n : new int[] {1, 10, 50, 100}) {
            double atLeastOneSlow = 1 - Math.pow(1 - slowRate, n);
            System.out.printf("fan-out %3d -> %.1f%% of requests are slowed down%n", n, atLeastOneSlow * 100);
        }
    }
}
text
fan-out   1 -> 1.0% of requests are slowed down
fan-out  10 -> 9.6% of requests are slowed down
fan-out  50 -> 39.5% of requests are slowed down
fan-out 100 -> 63.4% of requests are slowed down

Each downstream has only 1% slow requests, but with a fan-out of 100, more than 60% of requests are slowed down. The finer you split your microservices, and the more services an aggregation page calls, the worse the tail gets.

Queuing: the higher the utilization, the longer the wait

With the simplest queuing model (M/M/1: requests arrive at random and processing times are random), average response time = processing time ÷ (1 − utilization). Suppose one request takes 10 ms to process:

Utilization Average response time
50% 20 ms
80% 50 ms
90% 100 ms
95% 200 ms
99% 1,000 ms

Real systems do not match this model exactly, but the curve has the same shape: once utilization passes 80%, response time does not grow linearly; it shoots up. That is why capacity planning usually targets 60–70% utilization, leaving room to absorb spikes.

Little’s Law

flowchart LR
    A["Arrival rate λ<br/>(how many arrive per second)"] --> B["In the system<br/>L requests in progress at once"]
    B --> C["Average time in system W<br/>(how long each request stays)"]
    C --> D[Done]

L = λ × W: the number of requests in the system at once = arrival rate × the average time each request spends in the system.

The formula only requires the system to be in a steady state (requests leave as fast as they arrive). It holds no matter how requests are distributed or how they queue, which makes it a great fit for estimating resources:

  • 400 requests a second, 50 ms each on average → 400 × 0.05 = 20 requests in progress at once, which means 20 threads busy on average
  • If a downstream slows down and W becomes 2 seconds → 400 × 2 = 800 requests in the system at once, and 200 threads are nowhere near enough

The second example shows one thing: a slow downstream turns directly into resource exhaustion upstream.

Comparing options: ways to raise throughput and their effect on latency

Technique Throughput Latency Cost
Horizontal scaling (add machines) Higher Utilization drops, less queuing Money; the service has to be stateless first
Cache Higher (less backend load) Drops sharply on a hit Data consistency, memory cost
Batching (batch insert, Kafka linger.ms) Higher Each item gets slower, waiting for a batch to fill Parameters need tuning
Going async (respond once it is in the MQ) The front end can accept more requests Faster responses, but longer end-to-end completion Eventual consistency; failures need separate handling
More threads or a bigger connection pool Helps only when the bottleneck is not downstream Slower when the downstream is already saturated Memory, context switches, overwhelming the database
Virtual threads More concurrent requests when I/O-bound A single request is no faster The downstream is still the bottleneck; on JDK 21–23, blocking inside synchronized causes pinning
Hedged request (send another copy if there is no reply after p95) Almost unchanged The tail drops noticeably A little extra load; only for idempotent reads

For the details of virtual threads, see Spring Virtual Threads.

In Java

1. Size Tomcat threads and the HikariCP connection pool with Little’s Law

Suppose a single instance peaks at 400 RPS with a 50 ms average response, and each request holds a DB connection for 8 ms on average:

Resource Calculation Needed on average Default Verdict
Tomcat threads 400 × 0.05 s 20 200 Plenty of headroom
HikariCP connections 400 × 0.008 s 3.2 10 Plenty of headroom
yaml
server:
  tomcat:
    threads:
      max: 200                  # default; at peak only about 20 threads are busy on average
spring:
  datasource:
    hikari:
      maximum-pool-size: 10     # default; at peak only about 3~4 connections are needed on average
      connection-timeout: 1000  # fail if no connection within 1 second (default 30 seconds)

Now use the same formula to see what happens when “the database slows down”. Suppose a slow query makes each connection hold last 500 ms:

  • Maximum throughput the pool can sustain = connections ÷ hold time per use = 10 ÷ 0.5 s = 20 RPS
  • Arrivals are still 400 RPS, so 380 requests a second cannot get a connection. They can only wait where they are, and each one holds a Tomcat thread
  • The 200 threads are used up in about half a second. After that, new requests queue in the accept queue, and in the end the whole service times out

Growing the pool to 200 at this point only makes the already slow database take 20 times as many concurrent queries, so it gets even slower. The right moves are:

  1. Find out why the database slowed down (slow queries, lock waits); that is the root cause
  2. Shorten connection-timeout so requests that cannot get a connection fail fast and free their threads. But as long as “arrival rate × wait time” is still larger than the thread count, the threads still run out, which is why you also need point 3
  3. Add circuit breaking and load shedding on the caller side, so a broken downstream does not take the upstream down with it (Circuit Breakers and Bulkheads in Part 6)

For tuning the pool size in practice, see HikariCP tuning.

2. Make Spring Boot publish percentiles you can aggregate

properties
management.metrics.distribution.percentiles-histogram.http.server.requests=true
management.metrics.distribution.slo.http.server.requests=100ms,300ms,1s

Micrometer has two ways to publish percentiles, and they are very different:

Setting Where it is computed Can it be aggregated across instances?
percentiles (for example 0.99) Each instance computes it inside the application No; averaging the p99s of the instances means nothing
percentiles-histogram Only histogram buckets are published, and the monitoring system computes the percentile Yes; sum the buckets of all instances first, then compute

A service running on several instances has to use the histogram. To compute the p99 of the whole service in Prometheus:

text
histogram_quantile(0.99, sum by (le, uri) (rate(http_server_requests_seconds_bucket[5m])))

slo also publishes the boundaries you specify (100 ms, 300 ms, 1 s), so you can directly compute “what share of requests finished within 300 ms”, which is handy for checking against the SLO.

3. Avoid coordinated omission in load tests

Most load testing tools by default “send the next request only after receiving a response” (the closed model). When the server hangs for 2 seconds, the tool stops for 2 seconds too, and the requests that should have been sent during those 2 seconds, and that would have been slow, are never measured. As a result, the p99 looks much better than it really is.

The fix is to load test at a fixed arrival rate (the open model), sending at the planned rate whether or not the previous request has come back: wrk2’s -R, k6’s constant-arrival-rate executor, and Gatling’s constantUsersPerSec all work this way.

Pitfalls and gotchas

  • Looking at averages: averages hide the tail; look at least at three numbers: p50, p99, and max
  • Averaging percentiles: averaging the p99s of several machines, or averaging per-minute p99s into an hourly one, does not hold up mathematically. Recompute from the raw data or from the histogram
  • Looking only at successful requests, or mixing successes and failures together: errors that fail fast make latency look better. Look at the latency of successes and failures separately
  • Coordinated omission in load tests: closed-model load test results underestimate the tail
  • Pushing utilization above 90% and thinking you are saving money: queuing time shoots up, and a small spike causes a flood of timeouts
  • Raising threads or the connection pool as soon as things slow down: first use Little’s Law to work out which layer the bottleneck is in. When the downstream is saturated, more upstream concurrency only makes things worse

When to use it, and when not to

  • Use p99 for SLOs: add p99.9 for high-traffic core APIs that affect revenue
  • Be careful with percentiles on low-traffic services: with only 50 requests a minute, p99 is almost the maximum, and there are not enough samples. Widen the time window, or look at the maximum directly
  • Little’s Law applies to a steady state: it works well for estimating connection pools, thread pools, and queue lengths. The moments when traffic changes sharply (for example the first few seconds after sales open on the hour) are not a steady state, so estimate those separately from peak values
  • When to re-evaluate: if the p99 ÷ p50 ratio keeps growing (for example past 10x), the tail is getting worse, and it is time to look for GC, lock, slow query, or fan-out problems

References

Comments