Sub topic 14
Metrics that show saturation
This chapter assumes you know the queue, in-flight limit, and shedding ideas from the earlier chapters. You should also be able to read short Python examples and know what a latency percentile is. The goal is to choose metrics that tell you a service is approaching its limit before users notice, and that tell you whether your back pressure and shedding are working.
Utilization is not saturation
Utilization is the fraction of a resource that is busy. Saturation is the amount of work that is waiting because the resource has no room. A CPU at 100% utilization with no waiting work is fully used but not saturated. A CPU at 100% with 40 runnable threads queued behind it is saturated.
Saturation is the better overload signal because it measures the queue, and the queue is what turns into latency. Latency is the symptom, and a growing queue is its cause. Utilization also stops being informative near the limit: going from 95% to 100% busy tells you little, while the queue behind it can grow without bound.
The core signals
Most services need five signals. They map onto the mechanisms from earlier chapters.
| Metric | What it shows | Common mistake |
|---|---|---|
| Queue depth | How much work is waiting right now | Reading it without the queue's limit, so you can't tell "10 of 10" from "10 of 10,000" |
| Queue age (time in queue) | How long the oldest or typical item waited | Not measuring it at all, then missing that a short queue of slow items is still a problem |
| In-flight count versus its limit | How close you are to the concurrency limit | Reporting only the current value, which hides short peaks |
| Rejections by reason | How much load you shed, and why | Mixing queue-full, rate-limit, and deadline rejections into one counter |
| Latency percentiles and goodput | What users experience | Reporting only averages, or only successful requests |
Queue depth and queue age
Depth is easy to read from qsize(), so it is the metric people reach for first. Age is more useful. By Little's law, the wait in a queue is roughly depth divided by throughput. If throughput drops because a dependency slows down, the same depth means a longer wait. Age captures this directly, and it is what your deadline policy cares about. Add an enqueue timestamp to each item and record now - enqueued_at when a worker dequeues it.
A rising queue age with a flat arrival rate means capacity dropped. A rising queue age with a rising arrival rate means demand grew. You need both the arrival rate and the completion rate on the same dashboard to tell the two apart.
In-flight count and the Little's law check
In-flight work, L, should be close to arrival rate λ times latency W. You can use this as a consistency check on your own metrics. If you see 200 requests per second and a 0.5 s average latency, you expect about 100 in flight. If your gauge says 400, then either latency is higher than you think (often because of a slow tail) or work is stuck somewhere you aren't timing.
When in-flight sits at its limit for long periods, the limiter is doing the shedding. Whether that is healthy depends on the rejection rate and on what latency looks like for the requests that were admitted.
Rejections, split by reason
Keep a separate counter for each way work can be refused or dropped:
- Queue full (back pressure or shedding at the queue).
- Concurrency limit reached.
- Rate limit exceeded (token bucket empty).
- Deadline expired before work started.
- Client cancelled or disconnected.
Each reason points to a different fix. Many "queue full" rejections suggest the queue size or worker count is wrong. Many "deadline expired" drops suggest the queue is too deep for the deadlines you set. Use a small, fixed set of label values. A label that holds a user ID or request path creates a new time series for every value and can overwhelm your metrics system.
Latency and goodput
Throughput counts all completed responses. Goodput counts the useful ones: those that succeeded and arrived before the client gave up. Under overload, throughput can stay high while goodput collapses, because the service is busy finishing work nobody is waiting for.
Plot latency as percentiles (p50, p95, p99) from histograms. Averages hide the tail, and the tail is where saturation shows first. Be careful with what goes into the histogram. Rejected requests return in microseconds, so if you mix them with accepted ones, shedding makes your p50 look better while admitted users suffer. Record latency for accepted requests separately from rejection counts.
Resource-level saturation
Application metrics tell you that you are saturated. Resource metrics tell you where.
- CPU run queue or load average. Runnable threads exceeding cores means CPU saturation.
- Event loop lag. In asyncio, schedule a task that sleeps for a fixed interval and measure how late it wakes. High lag means something is blocking the loop or too many tasks are ready.
- Connection pool wait time. The time a request spends waiting to borrow a database connection is a queue that your own code does not control. It often saturates first.
- Thread pool queue length. The same applies to any executor.
- Memory and garbage collection pauses. Growing memory with a growing queue is the unbounded-queue failure from earlier in this tutorial.
Instrumenting a queue
This example wraps a bounded asyncio.Queue so that it records time in queue and a rejection count. It then runs a short overload test where requests arrive at about twice the rate the worker can serve.
import asyncio
import time
class InstrumentedQueue:
def __init__(self, maxsize: int) -> None:
self._queue: asyncio.Queue = asyncio.Queue(maxsize=maxsize)
self.rejected = 0
def put_nowait(self, item) -> None:
try:
self._queue.put_nowait((time.monotonic(), item))
except asyncio.QueueFull:
self.rejected += 1
raise
async def get(self):
enqueued_at, item = await self._queue.get()
return item, time.monotonic() - enqueued_at
def depth(self) -> int:
return self._queue.qsize()
async def worker(queue: InstrumentedQueue, waits: list) -> None:
while True:
_, wait = await queue.get()
waits.append(wait)
await asyncio.sleep(0.01) # about 100 items per second
async def main() -> None:
queue = InstrumentedQueue(maxsize=20)
waits: list = []
task = asyncio.create_task(worker(queue, waits))
for i in range(300): # about 200 items per second offered
try:
queue.put_nowait(i)
except asyncio.QueueFull:
pass
await asyncio.sleep(0.005)
await asyncio.sleep(0.5)
task.cancel()
waits.sort()
p50 = waits[len(waits) // 2]
p99 = waits[int(len(waits) * 0.99)]
print(f"accepted={len(waits)} rejected={queue.rejected}")
print(f"queue wait p50={p50 * 1000:.0f} ms p99={p99 * 1000:.0f} ms")
asyncio.run(main())Roughly half of the offered requests are rejected. The queue wait for accepted requests stays bounded near maxsize times the service time, about 200 ms here. Without the bound, the wait would keep growing for as long as the overload lasted. The two numbers printed are the ones to put on a dashboard: rejection count and the percentiles of queue wait.
Reading the signals together
A single metric rarely identifies the problem. Compare patterns:
- Depth and age rise, rejections are zero, arrival rate is flat. Capacity fell. Check the resource-level signals and dependency latency.
- In-flight is pinned at the limit, rejections rise, admitted latency stays flat. The limiter is shedding as designed. This is overload being handled, not an incident by itself.
- Rejections rise, admitted latency also rises. The limit is set too high for what the service can actually handle.
- Throughput is steady, goodput falls, deadline-expired drops rise. Work waits too long in the queue and is then discarded or wasted.
- Arrival rate suddenly exceeds the usual rate with no change in user traffic. Suspect retries. Compare the request rate with the rate of first attempts if clients send an attempt number.
Sampling and alerting pitfalls
Overload can start and end within seconds. If you scrape metrics every 60 seconds, a gauge such as queue depth may miss the peak. Prefer counters and histograms, which aggregate between scrapes, and track a maximum over the interval for gauges that matter.
Alert on symptoms that users feel, such as p99 latency of accepted requests and goodput. Add saturation alerts, such as queue age above a threshold or in-flight at its limit for several minutes, as early warnings. An alert on "any rejection" is too noisy if shedding is part of normal peak behavior.
Exercise
A service receives 400 requests per second, and the average latency of accepted requests is 0.25 s. Its in-flight gauge reads about 250. Using Little's law, what do you expect the gauge to read, and what does the gap suggest?
Show answer
Little's law gives L = λ × W = 400 × 0.25 = 100 requests in flight. The gauge reads 250, so either the real average latency is closer to 0.625 s (250 / 400) or some requests are stuck where you aren't timing them, for example waiting for a connection from a pool. Check the tail latency and pool wait time first.
Exercise
During a load test, throughput stays near 500 responses per second while goodput falls from 480 to 90 per second. Queue age has risen to 8 s and clients time out after 2 s. Which metric would you add, and what change would you make?
Show answer
Add a counter for work that completed after the client's deadline, or for deadline-expired drops. The service is spending capacity on responses nobody is waiting for. Make workers check the deadline on dequeue and drop expired items, and reduce the queue size so that the maximum wait stays below the client timeout.