Skip to content

Queueing at the Checkout

A store checkout is a queueing system: customers arrive, wait, and get served. The classical closed forms (Erlang, M/M/1) need known arrival and service rates, but in reality those rates are unknown and must be estimated from data.

This example does three things:

  1. Estimate the arrival and service rates with conjugate models
  2. Propagate the estimation uncertainty into the queueing metrics with posterior draws
  3. Go beyond the closed forms with a simulation that uses the posterior draws as inputs

The system

Everything below lives inside this picture. Customers arrive as a Poisson process with rate lam, wait in a queue, and are served one at a time, each service an Exponential draw with rate mu. What we usually get to measure is on the two ends: arrival counts and service times. What we usually care about is in the middle: queue length, waits, and utilization rho = lam / mu.

Code to draw the schematic
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(figsize=(9, 2.5))
ax.set_xlim(0, 10)
ax.set_ylim(0, 3)
ax.axis("off")

ax.text(1.1, 2.0, "arrivals\nPoisson($\\lambda$)", ha="center", fontsize=10)
ax.text(
    4.0,
    1.5,
    "queue",
    ha="center",
    va="center",
    bbox=dict(boxstyle="square", fc="white", ec="black"),
)
ax.text(
    7.0,
    1.5,
    "server\nExp($\\mu$)",
    ha="center",
    va="center",
    bbox=dict(boxstyle="square", fc="white", ec="black"),
)
ax.text(9.0, 2.0, "departures", ha="center", fontsize=10)

for y in (1.2, 1.5, 1.8):
    ax.annotate(
        "",
        xy=(3.2, 1.5),
        xytext=(2.0, y),
        arrowprops=dict(arrowstyle="->", color="black", alpha=0.5),
    )
ax.annotate("", xy=(5.4, 1.5), xytext=(4.7, 1.5), arrowprops=dict(arrowstyle="->"))
ax.annotate("", xy=(8.4, 1.5), xytext=(7.7, 1.5), arrowprops=dict(arrowstyle="->"))
ax.annotate(
    "",
    xy=(8.9, 2.0),
    xytext=(8.2, 1.6),
    arrowprops=dict(arrowstyle="->", color="black", alpha=0.5),
)

ax.text(1.1, 0.9, "observed", ha="center", fontsize=9, color="darkred")
ax.text(5.5, 0.9, "hidden", ha="center", fontsize=9, color="gray")
ax.text(9.0, 0.9, "observed", ha="center", fontsize=9, color="darkred")

plt.savefig("./docs/images/queueing-schematic.png", bbox_inches="tight")
plt.close()

Queue schematic

Setup

Suppose we observed one busy day. Customers arrive at a rate of 0.8 per minute and each service takes on average 1 minute, so the utilization is 0.8. We observe the number of arrivals each minute and the service time of each customer.

import numpy as np

rng = np.random.default_rng(42)

lam_true = 0.8  # arrivals per minute
mu_true = 1.0  # services per minute
n_minutes = 8 * 60

arrivals = rng.poisson(lam_true, size=n_minutes)
service_times = rng.exponential(1 / mu_true, size=arrivals.sum())

Conjugate updates for the inputs

The two ingredients of every M/M/1 formula are conjugate friendly:

  • Arrivals are counts per unit of time, a Poisson likelihood, so a Gamma prior gives a Gamma posterior with poisson_gamma
  • Service times are an Exponential likelihood, so a Gamma prior on the rate gives a Gamma posterior with exponential_gamma
from conjugate.distributions import Gamma
from conjugate.models import (
    exponential_gamma,
    exponential_gamma_predictive,
    poisson_gamma,
    poisson_gamma_predictive,
)

prior_lambda = Gamma(alpha=2, beta=2)  # prior mean of 1 arrival per minute
prior_mu = Gamma(alpha=2, beta=2)  # prior mean of 1 service per minute

Prior predictive check

Before touching the data, check what the priors claim. The prior predictive marginalizes over the prior: counts per minute come back a NegativeBinomial through poisson_gamma_predictive and service times come back a heavy tailed Lomax through exponential_gamma_predictive.

prior_predictive_counts = poisson_gamma_predictive(distribution=prior_lambda)
prior_predictive_service = exponential_gamma_predictive(distribution=prior_mu)
Code to plot the prior predictive
import matplotlib.pyplot as plt

counts = prior_predictive_counts.dist.rvs(5_000, random_state=rng)
services = prior_predictive_service.dist.rvs(5_000, random_state=rng)

fig, axes = plt.subplots(ncols=2, figsize=(10, 3))
axes[0].hist(counts, bins=np.arange(-0.5, 10), density=True)
axes[0].axvline(arrivals.mean(), color="black", linestyle="--", label="observed")
axes[0].set_xlabel("arrivals per minute")
axes[0].legend()
axes[1].hist(services, bins=60, density=True)
axes[1].axvline(service_times.mean(), color="black", linestyle="--", label="observed")
axes[1].set_xlabel("service time (minutes)")
axes[1].legend()
plt.savefig("./docs/images/queueing-prior-predictive.png", bbox_inches="tight")
plt.close()

Prior predictive for counts per minute and service times

The prior is weakly informative: it finds a minute with a handful of arrivals plausible and has no strong opinion about the service time, while still covering the values the data later supports. Nothing about the prior predictive contradicts the domain, so the updates below are safe to trust.

posterior_lambda = poisson_gamma(
    x_total=arrivals.sum(),
    n=arrivals.size,
    prior=prior_lambda,
)
posterior_mu = exponential_gamma(
    x_total=service_times.sum(),
    n=service_times.size,
    prior=prior_mu,
)

The data dominates both posteriors, which is what we want to see before trusting any downstream number.

Code to compare prior and posterior
import matplotlib.pyplot as plt

fig, axes = plt.subplots(ncols=2, figsize=(10, 3))
for ax, prior, posterior, truth, label in (
    (axes[0], prior_lambda, posterior_lambda, lam_true, "arrival rate"),
    (axes[1], prior_mu, posterior_mu, mu_true, "service rate"),
):
    bound = 3 * truth
    prior.set_bounds(0, bound).plot_pdf(ax=ax, label="prior")
    posterior.set_bounds(0, bound).plot_pdf(ax=ax, label="posterior")
    ax.axvline(truth, color="black", linestyle="--", label="truth")
    ax.set_xlabel(label)
    ax.legend()
plt.savefig("./docs/images/queueing-posteriors.png", bbox_inches="tight")
plt.close()

Prior and posterior for the arrival and service rates

Posterior draws instead of point estimates

The usual workflow plugs point estimates into the formulas:

rho_point = arrivals.mean() * service_times.mean()

The problem is that every downstream number inherits that false precision. The utilization rho = lam / mu is a ratio of two Gamma posteriors, and ratios of Gammas do not even have a finite mean. Sampling from the posteriors respects that heavy tail instead of hiding it.

n_draws = 50_000
lam = posterior_lambda.dist.rvs(n_draws, random_state=rng)
mu = posterior_mu.dist.rvs(n_draws, random_state=rng)

rho = lam / mu
p_above = (rho > 0.9).mean()

The same draws turn the M/M/1 waiting time formula into a distribution. Note that W_q is only defined when the queue is stable, which is itself something we are uncertain about.

stable = lam < mu
W_q = np.where(stable, lam / (mu * (mu - lam)), np.inf)
Code to plot the utilization and waiting time
import matplotlib.pyplot as plt

fig, axes = plt.subplots(ncols=2, figsize=(10, 3))
axes[0].hist(rho, bins=60, density=True)
axes[0].axvline(rho_point, color="black", linestyle="--", label="point estimate")
axes[0].axvline(0.9, color="red", linestyle=":", label="utilization 0.9")
axes[0].set_xlabel("utilization")
axes[0].legend()

W_q_zoom = W_q[stable & (W_q < np.percentile(W_q[stable], 95))]
axes[1].hist(W_q_zoom, bins=60, density=True)
axes[1].set_xlabel("mean wait (minutes), below the 95th percentile")
plt.savefig("./docs/images/queueing-utilization.png", bbox_inches="tight")
plt.close()

Posterior of the utilization and the waiting time

Compare rho_point against the posterior of rho: the point estimate sits comfortably below 0.9, but about 3 percent of the posterior draws cross it, a tail risk the point estimate cannot even express. The staffing decision is yours to make, but now it is made with the odds in view.

Beyond the closed forms

The store we care about is messier than M/M/1:

  • the arrival rate swings across the day: a lunch rush, a slow mid-afternoon, and a dinner push that peaks around 7pm
  • a basket of k items takes k exponential scan times, so service time is Gamma with a rate set by the per item rate
  • customers who find a long queue defect and come back later, a retrial loop

None of that has a closed form, but all of it keeps the conjugate structure. We update one Gamma posterior per hour for the arrival rates and one Gamma posterior for the per item service rate. With basket sizes logged per customer, each scanned item is one exponential observation, so the update uses the total service time and the total number of items.

n_hours = 12
# open 11am to 11pm, arrivals per minute
hour_labels = np.array(
    [
        "11am",
        "12pm",
        "1pm",
        "2pm",
        "3pm",
        "4pm",
        "5pm",
        "6pm",
        "7pm",
        "8pm",
        "9pm",
        "10pm",
    ]
)
lam_hours_true = np.array([0.2, 1.2, 1.0, 0.4, 0.2, 0.3, 0.6, 1.4, 1.6, 1.3, 0.8, 0.4])
mu_item_true = 8.0  # eight items scanned per minute

hourly_counts = rng.poisson(lam_hours_true, size=(1_000, n_hours))
# one Gamma posterior per hour: the vector x_total broadcasts against the
# scalar n of observations per hour
posterior_lam_h = poisson_gamma(
    x_total=hourly_counts.sum(axis=0),
    n=1_000,
    prior=prior_lambda,
)

basket_sizes = 1 + rng.poisson(3, size=500)
item_times = rng.exponential(1 / mu_item_true, size=basket_sizes.sum())
posterior_mu_item = exponential_gamma(
    x_total=item_times.sum(),
    n=basket_sizes.sum(),
    prior=prior_mu,
)

The per hour posteriors recover the shape of the day, both rushes and the quiet stretch between them, and show which hours are actually uncertain.

Code to plot the hourly rates
import matplotlib.pyplot as plt

hours = np.arange(n_hours)
lam_mean = posterior_lam_h.alpha / posterior_lam_h.beta
lam_lo = posterior_lam_h.dist.ppf(0.025)
lam_hi = posterior_lam_h.dist.ppf(0.975)

fig, ax = plt.subplots(figsize=(9, 3))
ax.fill_between(hours, lam_lo, lam_hi, alpha=0.3, label="95% credible band")
ax.plot(hours, lam_mean, label="posterior mean")
ax.plot(hours, lam_hours_true, color="black", linestyle="--", label="truth")

# shade the rushes so the shape of the day reads at a glance
ax.axvspan(0.5, 2.5, color="orange", alpha=0.08)
ax.axvspan(6.5, 9.5, color="orange", alpha=0.08)
ax.text(1.5, 1.85, "lunch rush", ha="center", fontsize=9, color="darkorange")
ax.text(8.0, 1.85, "dinner rush", ha="center", fontsize=9, color="darkorange")

ax.set_xticks(hours, labels=hour_labels, rotation=45)
ax.set_ylabel("arrivals per minute")
ax.set_ylim(0, None)  # utilization rates have a natural zero
ax.legend()
plt.savefig("./docs/images/queueing-hourly.png", bbox_inches="tight")
plt.close()

Per hour arrival rate posterior

The posterior draws then parameterize the simulation. Each draw is one plausible day, and the spread across draws is the honest answer to "how bad can it get".

import heapq


def simulate_day(hourly_rate, mu, rng, *, max_queue=4, p_return=0.75):
    """Discrete event simulation of a 12 hour day with retrials."""
    horizon = 12 * 60.0

    # piecewise homogeneous arrivals, exact within each hour
    events = []
    for h, rate in enumerate(hourly_rate):
        n = rng.poisson(rate * 60)  # rate is per minute, an hour has 60
        for t in h * 60 + 60 * np.sort(rng.random(n)):
            if t < horizon:
                heapq.heappush(events, (t, "arrival", 0))

    queue = []
    busy_until = 0.0
    waits = []
    lost = 0
    n_customers = 0

    while events:
        t, kind, attempt = heapq.heappop(events)

        if kind == "arrival":
            if attempt == 0:
                n_customers += 1
            if len(queue) >= max_queue:
                # defect, but maybe come back later
                if attempt < 3 and rng.random() < p_return:
                    delay = rng.exponential(45.0)
                    heapq.heappush(events, (t + delay, "arrival", attempt + 1))
                else:
                    lost += 1
                continue
            queue.append(t)

        # after any event, the server may be free with work waiting:
        # the departure event guarantees we wake up when it is
        if queue and t >= busy_until:
            arrival_time = queue.pop(0)
            waits.append(t - arrival_time)
            items = 1 + rng.poisson(3)
            busy_until = t + rng.gamma(items, 1 / mu)
            heapq.heappush(events, (busy_until, "departure", 0))

    return np.array(waits), lost, n_customers


n_sims = 10_000  # enough draws to smooth the whole-number loss granularity
lam_days = posterior_lam_h.dist.rvs((n_sims, n_hours), random_state=rng)
mu_days = posterior_mu_item.dist.rvs(n_sims, random_state=rng)

results = [
    simulate_day(lam_day, mu_day, rng) for lam_day, mu_day in zip(lam_days, mu_days)
]
mean_waits = []
lost_counts = []
for lam_day, (waits, lost, n_customers) in zip(lam_days, results):
    mean_waits.append(waits.mean() if waits.size else 0.0)
    lost_counts.append(lost)  # a day loses a whole number of people
mean_waits = np.array(mean_waits)
lost_counts = np.array(lost_counts)
Code to plot the simulated days
import matplotlib.pyplot as plt

fig, axes = plt.subplots(ncols=2, figsize=(10, 3))
axes[0].hist(mean_waits, bins=40, density=True)
axes[0].set_xlabel("mean wait (minutes)")
axes[1].hist(
    lost_counts,
    bins=np.arange(-0.5, lost_counts.max() + 1.5),
    density=True,
)
axes[1].set_xticks(np.arange(0, lost_counts.max() + 1, 2))
axes[1].set_xlabel("customers lost per day")
plt.savefig("./docs/images/queueing-simulation.png", bbox_inches="tight")
plt.close()

Simulated mean wait and customers lost per day

A typical day loses one to two of its roughly 570 walk-ins, under half a percent; the risk to manage is the tail of genuinely bad days, and how often it reaches three or more lost customers.

Departures only

Now imagine a stricter data limit: the store only logs completed transactions. One stream of departure times, no arrival data at all. This is the queue inference problem, studied since Larson's Queue Inference Engine (1990).

Same system as the opening schematic, but now only the right end is observed. The arrivals, the queue, and the server are all hidden, and the only measurements are the moments customers walk out the door.

Code to draw the departures-only schematic
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(9, 2.5))
ax.set_xlim(0, 10)
ax.set_ylim(0, 3)
ax.axis("off")

ax.text(
    1.1, 2.0, "arrivals\nPoisson($\\lambda$)", ha="center", fontsize=10, color="gray"
)
ax.text(
    4.0,
    1.5,
    "queue",
    ha="center",
    va="center",
    color="gray",
    bbox=dict(boxstyle="square", fc="white", ec="gray"),
)
ax.text(
    7.0,
    1.5,
    "server\nExp($\\mu$)",
    ha="center",
    va="center",
    color="gray",
    bbox=dict(boxstyle="square", fc="white", ec="gray"),
)
ax.text(9.0, 2.0, "departures", ha="center", fontsize=10)

for y in (1.2, 1.5, 1.8):
    ax.annotate(
        "",
        xy=(3.2, 1.5),
        xytext=(2.0, y),
        arrowprops=dict(arrowstyle="->", color="gray", alpha=0.5),
    )
ax.annotate(
    "", xy=(5.4, 1.5), xytext=(4.7, 1.5), arrowprops=dict(arrowstyle="->", color="gray")
)
ax.annotate(
    "", xy=(8.4, 1.5), xytext=(7.7, 1.5), arrowprops=dict(arrowstyle="->", color="gray")
)
ax.annotate(
    "",
    xy=(8.9, 2.0),
    xytext=(8.2, 1.6),
    arrowprops=dict(arrowstyle="->", color="black", alpha=0.5),
)

ax.text(1.1, 0.9, "hidden", ha="center", fontsize=9, color="gray")
ax.text(5.5, 0.9, "hidden", ha="center", fontsize=9, color="gray")
ax.text(7.0, 0.9, "hidden", ha="center", fontsize=9, color="gray")
ax.text(9.0, 0.9, "observed", ha="center", fontsize=9, color="darkred")

plt.savefig(
    "./docs/images/queueing-departures-schematic.png",
    bbox_inches="tight",
)
plt.close()

Departures only: arrivals, queue, and server hidden, departures observed

Start with what a single inter-departure gap can be. There are two cases:

  • the server was busy, so the gap is just one service time
  • the server was idle, so the gap is waiting for the next arrival plus that arrival's service time

Every gap is a mixture of these two, which is why the raw histogram below is hard to read: it blends the service distribution with the idle-time distribution, and the split between them is not observed.

There is also a deeper catch. Burke's theorem says a steady state M/M/1 queue emits departures as an exact Poisson process with rate lam, no matter what the service rate is. Averaged over a long steady stretch, the gaps are Exp(lam) and the service rate has washed out completely. Service information survives only in the transient structure, in other words in which gaps came from busy periods and which came from idle ones.

The practical fix is to reconstruct that split. Short gaps look like busy period service times, long gaps look like idle time, and a threshold separates the two:

# departures only: split the stream into busy periods
departure_gaps = rng.exponential(1 / lam_true, size=1_000)
gap_split = 2.5  # gaps longer than this look like idle time

busy_gaps = departure_gaps[departure_gaps < gap_split]
idle_gaps = departure_gaps[departure_gaps >= gap_split]
Code to plot the gap split
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(7, 3))
ax.hist(departure_gaps, bins=60, density=True)
ax.axvline(gap_split, color="red", linestyle="--")
ax.set_xlabel("inter-departure gap (minutes)")
plt.savefig("./docs/images/queueing-departures.png", bbox_inches="tight")
plt.close()

Inter-departure gaps with the busy and idle split

Each side of the split is now a clean Exponential likelihood in one rate: the busy gaps in the service rate mu, the idle gaps in the arrival rate lam. Conjugate updates apply to both.

posterior_mu_d = exponential_gamma(
    x_total=busy_gaps.sum(),
    n=busy_gaps.size,
    prior=prior_mu,
)
# idle gaps are exponential in the arrival rate itself
posterior_lambda_d = exponential_gamma(
    x_total=idle_gaps.sum(),
    n=idle_gaps.size,
    prior=prior_lambda,
)

Two caveats keep this honest. The gap_split threshold is chosen, not learned, and near high utilization the two gap distributions overlap so heavily that the split is mostly guesswork. A wider posterior on mu from this section, compared against the arrivals-plus-service posterior from earlier, is the visible cost of dropping the arrival data: simulating both posterior pairs through the queue shows exactly how much precision the transactions-only view gives up.

References

  • Larson, R. C. (1990). The Queue Inference Engine: Deducing Queue Statistics from Transactional Data. Management Science 36(5).
  • Shestopaloff, A. Y. and Neal, R. M. (2013). On Bayesian inference for the M/G/1 queue with efficient MCMC sampling.
  • Li, W. and Goldenshluger, A. (2024). Adaptive minimax estimation of service time distribution in the M_t/G/infinity queue from departure data. Queueing Systems 108.

Comments