---
title: Queueing and sampling lab
heading: Simulating an M/M/1 server, the tail at scale with hedged requests, and sampled simulation, in Python
eyebrow: S4 · Lesson 48 · Queueing and sampling lab
xp: 60
---

::: hook
Lessons 39, 43 and 44 used three formulas that are easy to misapply: the M/M/1 response time, the tail-at-scale probability, and the number of samples a sampled simulation needs. Each comes from a model, and the best way to trust a model is to simulate the system it describes and see the formula land on the measurement. This lab simulates a single-server queue, a fan-out service with and without hedged requests, and random sampling of a program's CPI, and checks each against its formula.
:::

::: play
- The curve is the M/M/1 mean response time, $S/(1 - \rho)$, against utilization ρ for a service time S.
- It doubles from ρ = 0 to 0.5, quintuples by 0.8, and grows without bound toward 1.
- The lab's event simulation reproduces it within a percent or two with a few hundred thousand requests.
:::

```sim plot
view: graph
x: p = 0..0.95
y: T = 0..200 ms
slider: S = 1..20 = 10 ms
plot: S/(1 - p) | label: mean response time
plot: S + 0*p | dashed | label: service time
```

::: predict
## A request fans out to 100 leaves; each is slow 1% of the time. Hedging sends each leaf request to two replicas and takes whichever answers first. What fraction of requests are slow with and without hedging, if replicas are slow independently?

- [x] About 63% without, about 1% with
- [ ] About 63% both ways
- [ ] About 1% without, about 0.01% with
- [ ] About 50% with, 63% without

::: reveal
Without hedging, $1 - 0.99^{100} = 63\%$. With two replicas a leaf is slow only if both are: $0.01^2 = 10^{-4}$, so $1 - (1 - 10^{-4})^{100} = 1.0\%$. Doubling the leaf requests (or sending the second only after a short delay, which costs far less) turns the common case back into the rare one.
:::
:::

::: nameit
## The models

- **M/M/1:** Poisson arrivals at rate λ, exponential service with mean S, one server: $T = S/(1 - \rho)$ with $\rho = \lambda S$. Simulate it by drawing exponential gaps and service times; each request starts at the later of its arrival and the previous request's finish.
- **Tail at scale:** k parallel sub-requests, each slow with probability p: $1 - (1 - p)^k$. Hedged across two independent replicas: $1 - (1 - p^2)^k$.
- **Sampling:** n random samples of a quantity with coefficient of variation CoV estimate its mean within $\varepsilon = z\,\text{CoV}/\sqrt n$ at confidence z (1.96 for 95%), so $n = (z\,\text{CoV}/\varepsilon)^2$.
:::

::: check
kind: python

## Write `mm1(lam, S, n, seed)`: simulate n requests of an M/M/1 queue with `random.Random(seed)` (draw each interarrival gap, then each service time, with `expovariate`) and return the mean response time.

```python starter
def mm1(lam, S, n, seed):
    return S
```

```python solution
import random

def mm1(lam, S, n, seed):
    r = random.Random(seed)
    t = free = tot = 0.0
    for _ in range(n):
        t += r.expovariate(lam)
        start = max(t, free)
        free = start + r.expovariate(1 / S)
        tot += free - t
    return tot / n
```

```python tests
for rho in (0.5, 0.8):
    T = mm1(rho / 0.01, 0.01, 200000, 1)
    assert abs(T / (0.01 / (1 - rho)) - 1) < 0.03, "Within 3% of S/(1 − ρ)."
assert mm1(10, 0.01, 50000, 2) < 0.0115, "At 10% load, barely more than the service time."
```

::: right
Right. The simulation converges more slowly at high load, where long queues come and go: that's the variance behind the mean.
:::
:::

::: check
kind: python

## Write `tail(k, p, trials, seed, hedge)`: simulate `trials` requests, each fanning out to k leaves that are slow with probability p (with hedge=True a leaf is slow only if two independent draws both are), and return the fraction of slow requests.

```python starter
def tail(k, p, trials, seed, hedge):
    return 0.0
```

```python solution
import random

def tail(k, p, trials, seed, hedge):
    r = random.Random(seed)
    slow = 0
    for _ in range(trials):
        for _ in range(k):
            s = r.random() < p
            if hedge:
                s = s and r.random() < p
            if s:
                slow += 1
                break
    return slow / trials
```

```python tests
assert abs(tail(100, 0.01, 5000, 2, False) - (1 - 0.99 ** 100)) < 0.02, "Without hedging: 63%."
assert abs(tail(100, 0.01, 20000, 3, True) - (1 - (1 - 1e-4) ** 100)) < 0.003, "With hedging: 1%."
```

::: right
Right. Hedging squares each leaf's slow probability, which is why it works so well against rare, independent stragglers.
:::
:::

::: check
kind: python

## Write `samples_needed(cov, eps, z)` and `sample_error(values, n, trials, seed)`: draw n values at random (with replacement) `trials` times and return the 95th percentile of the relative error of the sample mean.

```python starter
def samples_needed(cov, eps, z):
    return 1

def sample_error(values, n, trials, seed):
    return 0.0
```

```python solution
import random

def samples_needed(cov, eps, z):
    return (z * cov / eps) ** 2

def sample_error(values, n, trials, seed):
    r = random.Random(seed)
    true = sum(values) / len(values)
    errs = sorted(abs(sum(values[r.randrange(len(values))] for _ in range(n)) / n - true) / true for _ in range(trials))
    return errs[int(0.95 * trials)]
```

```python tests
import math, random
assert abs(samples_needed(0.5, 0.03, 3) - 2500) < 1e-9, "CoV 0.5, ±3% at z = 3: 2500 samples."
r = random.Random(4)
cpi = [1.0 + 0.5 * math.sin(i / 50) + r.gauss(0, 0.3) for i in range(100000)]
m = sum(cpi) / len(cpi)
cov = math.sqrt(sum((c - m) ** 2 for c in cpi) / len(cpi)) / m
pred = 1.96 * cov / math.sqrt(1000)
assert abs(sample_error(cpi, 1000, 200, 5) / pred - 1) < 0.25, "The 95th-percentile error matches 1.96 CoV/√n."
```

::: right
Right. A thousand random samples estimate a hundred-thousand-point trace's mean to about 3%, the principle behind SMARTS.
:::
:::

::: explain
## Why does the mean response time of a queue grow so sharply as utilization approaches 1?

::: model
Arrivals and service times vary at random, so even when the server is idle on average a fraction of the time, requests sometimes arrive in clumps or meet long services, and a queue forms. The server can only work off a queue at the rate its spare capacity allows, which is the fraction of time it would otherwise be idle, 1 − ρ. As that spare capacity shrinks, each backlog takes longer to drain and new arrivals pile on before it clears, so the typical waiting time grows like 1/(1 − ρ). At 90% utilization a request waits about nine service times on average, at 99% about ninety-nine.
:::
:::
