Pidoku

Archive

This learning material is in the archive. It is not currently maintained and has not been updated with the latest information, so tool versions, prices and dates may be out of date.

Queueing for SREs

Module 7 Lesson 7.e 50 min Difficulty 4/5

Prerequisites 7.d

The idea in one minute#

Three results from queueing theory explain a surprising share of production behaviour:

  1. Little’s law: in-flight = arrival rate × time in system. It always holds, for any system in a steady state. 200 req/s at 50 ms each means 10 in flight — size pools from it.
  2. Latency explodes near full utilisation. For a single server with random arrivals, the mean wait is proportional to ρ / (1 − ρ), where ρ is utilisation. At 50% busy, waits are about one service time; at 90%, nine; at 99%, ninety-nine. This is why services fall off a cliff instead of slowing down gently, and why capacity plans target 60–70%.
  3. Pooling and variability matter. Many servers sharing one queue handle high utilisation far better than one server, and the more variable the service times, the longer the queues.

An analogy#

A motorway at 3 a.m. and at 5 p.m. has the same lanes and the same speed limit. Traffic at 50% of capacity flows freely; at 95% the smallest braking creates a jam that lasts an hour. Nothing about the road changed — only utilisation.

A picture#

flowchart LR
  A["Arrivals λ<br/><small>requests/s</small>"] --> Q["Queue<br/><small>wait W_q</small>"] --> S["c servers<br/><small>each serves μ/s</small>"] --> D["Done"]
  L["Little's law: L = λ × W"] -.-> Q
  U["Utilisation ρ = λ / (c·μ)"] -.-> S
  class A neutral
  class Q queue
  class S compute
  class D io
  class L,U memory

How it really works#

Little’s law#

L = λ × W
L = average number in the system (in flight)
λ = arrival rate
W = average time in the system

Uses:

  • Size a pool. A service calls a database 400 times per second, each query takes 25 ms: 400 × 0.025 = 10 connections busy on average. Size the pool for peaks and variance (say 2–3×), not for 100.
  • Spot a problem. If in-flight requests grow while the arrival rate is flat, time in system is growing — something is slowing down.
  • Concurrency limits. A worker pool of 50 with 100 ms requests caps throughput at 500 req/s, no matter how many CPUs there are.

Utilisation versus waiting#

For the simplest model, M/M/1 (random arrivals, random service times, one server):

utilisation         ρ   = λ / μ
mean time waiting   W_q = ρ / (μ − λ)       = (ρ / (1 − ρ)) × service time
mean time in system W   = 1 / (μ − λ)
UtilisationMean wait (in service times)Time in system
50%12×
70%2.33.3×
80%45×
90%910×
95%1920×
99%99100×

Tail latency is worse than the mean: in M/M/1 the time in system is exponentially distributed, so the p99 is about 4.6× the mean.

Many servers: M/M/c#

With c servers sharing one queue, the probability of having to wait at all is given by the Erlang C formula, and waiting stays low up to much higher utilisation. A pool of 32 workers at 85% utilisation has a much shorter queue than one worker at 85%. Practical consequences:

  • One shared queue beats many per-server queues (supermarkets vs bank tellers) — and is what least-requests and P2C approximate (7.b).
  • Big pools can run hotter than small ones. A service on 2 instances needs more headroom than the same service on 50.

Variability#

Kingman’s formula approximates the wait for any single-server queue:

W_q ≈ (ρ / (1 − ρ)) × ((c_a² + c_s²) / 2) × service time

where c_a and c_s are the coefficients of variation (standard deviation ÷ mean) of arrival gaps and service times. Random (Poisson) arrivals have c_a = 1. If some requests take 100× longer than others (a slow report endpoint next to fast lookups), c_s is large and queues grow, even at moderate utilisation. Isolate slow work into its own pool (a bulkhead, 6.c) so it does not inflate everyone’s wait.

What this means in practice#

  • Target 60–70% utilisation at peak of the constrained resource for interactive services. Batch systems can run at 90%+ because latency does not matter.
  • Do not trust averages. A CPU average of 60% over 5 minutes may hide 100% for 30 seconds.
  • Saturation signals (queue length, wait time) move before utilisation reaches 100% (3.a).
  • Little’s law sanity-checks dashboards: if in_flight ≠ rate × latency, a metric is wrong.

A worked example#

An API has 8 workers; each request takes 20 ms of work: capacity 400 req/s.

LoadρWhat users see
200 req/s50%6% of requests wait at all; mean 20 ms, p99 about 90 ms
320 req/s80%Nearly half wait; p99 about 100 ms
380 req/s95%84% wait; mean triples, p99 about 260 ms; any spike causes timeouts

(Service times are random — exponential — in this model, which is why even at 50% the p99 is several times the 20 ms of work.) A product manager asks why the service “falls over at 380 when it can do 400”. The program answers with numbers: it computes the M/M/c waits from Erlang C and checks them with a simulation.

Code#

Go
// queueing.go — Little's law, M/M/1 and M/M/c (Erlang C) waits, checked against a simulation.
package main

import (
	"fmt"
	"math"
	"math/rand"
	"sort"
)

// erlangC returns the probability that an arrival must wait, for c servers at offered load a = λ/μ.
func erlangC(c int, a float64) float64 {
	sum, term := 0.0, 1.0
	for k := 0; k < c; k++ {
		if k > 0 {
			term *= a / float64(k)
		}
		sum += term
	}
	termC := term * a / float64(c)
	rho := a / float64(c)
	top := termC / (1 - rho)
	return top / (sum + top)
}

// simulate an M/M/c FIFO queue and return the mean and p99 time in system (seconds).
func simulate(c int, lambda, mu float64, n int, r *rand.Rand) (mean, p99 float64) {
	free := make([]float64, c)
	t := 0.0
	times := make([]float64, n)
	for i := 0; i < n; i++ {
		t += r.ExpFloat64() / lambda
		k := 0
		for j := range free {
			if free[j] < free[k] {
				k = j
			}
		}
		start := math.Max(t, free[k])
		done := start + r.ExpFloat64()/mu
		free[k] = done
		times[i] = done - t
		mean += done - t
	}
	sort.Float64s(times)
	return mean / float64(n), times[int(0.99*float64(n))]
}

func main() {
	fmt.Println("Little's law: in-flight = rate × time")
	fmt.Printf("  400 queries/s × 25 ms = %.0f connections busy on average\n\n", 400*0.025)

	const c, service = 8, 0.020 // 8 workers, 20 ms per request
	mu := 1 / service
	r := rand.New(rand.NewSource(5))
	fmt.Printf("M/M/%d, %v ms per request, capacity %.0f req/s\n", c, service*1000, float64(c)*mu)
	fmt.Println("  load    util   P(wait)  mean (theory)  mean (sim)  p99 (sim)   1 worker, same util")
	for _, load := range []float64{200, 280, 320, 360, 380, 392} {
		a := load / mu
		rho := a / c
		pw := erlangC(c, a)
		wq := pw / (float64(c)*mu - load) // mean wait in queue
		mean, p99 := simulate(c, load, mu, 300_000, r)
		mm1 := service / (1 - rho) // mean time in system, one server at the same utilisation
		fmt.Printf("  %4.0f   %4.0f%%   %5.1f%%   %8.1f ms   %7.1f ms   %6.1f ms   %8.1f ms\n",
			load, rho*100, pw*100, (wq+service)*1000, mean*1000, p99*1000, mm1*1000)
	}
	fmt.Println("\nLast column: a single 20 ms worker (M/M/1) at the same utilisation. Eight workers")
	fmt.Println("sharing one queue wait far less at the same utilisation: pooling matters.")
}

Remember this#

  • Little’s law: in-flight = rate × time. Use it to size pools and sanity-check metrics.
  • Waiting grows like ρ / (1 − ρ): gentle until ~70%, a cliff after ~90%.
  • Many servers sharing a queue tolerate higher utilisation; small fleets need more headroom.
  • Variability lengthens queues; isolate slow work.
  • Plan interactive services for 60–70% of the constrained resource at peak.

Try it#

  1. Run queueing.go. Change c to 2 and to 64 (keeping capacity similar by changing service). How does the cliff move?
  2. A pool of 20 database connections, 15 ms queries, 1,000 queries/s. Use Little’s law: is the pool big enough on average? At peaks?
  3. Add a second request type to the simulation that takes 500 ms, 2% of the time. What happens to the p99 of the fast requests?

Check yourself#

  1. Using Little’s law: 50 in flight, 250 req/s — what is the mean time in system?
  2. Why does a service “fall over at 95%” rather than slow down linearly?
  3. Why can a fleet of 50 instances run at higher utilisation than a fleet of 2?
  4. What does Kingman’s formula say about mixing slow and fast requests in one pool?

Sources#

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in