Skip to content
Tech Interview Prep
Technical interview guide

Probability Distributions

The handful of named distributions (normal, binomial, Poisson) that show up repeatedly, and what each models.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v7
Editorial status
Reviewed

Scope: Standards and library references current as of 2026-09: NIST/SEMATECH e-Handbook, SciPy, NumPy, statsmodels, and scikit-learn.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-2

How would you reason about discrete versus continuous in a system you own?

Answer

Core (first 90 seconds). I'd start by naming the two quantities I own and the decision each drives, because the discrete/continuous choice is downstream of that. In the API I run: request latency in milliseconds, and error counts per minute. Latency is continuous: quantized to ms by the timer, but continuous as a model. Error counts are discrete. The rule I apply: the support decides which operations are valid. Point probabilities are meaningful only for the counts; for latency every threshold is an interval, "≤ x", never "= x". Then I check the model against the data before I trust it.

Why the support decides the operations. A PMF sums to 1 over countable outcomes, so P(errors = 3) is a number I can page on. A density integrates to 1, so P(latency = 3 ms) = 0 and the density at 3 ms can be 2.0: a rate, not a probability. That's why p99 is a quantile of the CDF and why a latency threshold has to be an interval. Aggregation follows: sums of independent Poisson counts stay Poisson, so errors per hour are still discrete; sums of latencies are continuous, and the mean of many requests is approximately normal by CLT even though individual latencies are heavy-tailed.

Trade-offs and when not to use each.

  • Poisson for error counts: closed form, cheap, hands me a page threshold directly. Assumes variance = mean. Bursty traffic breaks it: I check the index of dispersion and move to negative binomial when it's well above 1.
  • Lognormal for latency: lets me extrapolate the tail beyond observed data. Wrong for genuinely heavy tails; I use it only when the fit holds.
  • Empirical histogram: no distributional assumption, works for both quantities, but resolution is bounded by bucket width and it can't extrapolate past the last bucket.

The deciding criterion is the operation the number feeds. A threshold alert needs a tail probability → empirical or continuous. Capacity or billing needs exact sums → discrete. If I can't justify a parametric model, the histogram is the fallback.

Failure modes, detection, cost.

  • Density read as a probability. Detect: threshold outside [0,1], or alerts that never fire. Cost: silent SLO breach.
  • Poisson on overdispersed counts. Detect: index of dispersion over a week. Cost: false pages and on-call fatigue.
  • Histogram top-bucket saturation: p99 lands in the last bucket and is reported as the bucket edge. Detect: p99 equals the max bucket bound. Cost: understated tail latency.

Artefact: checking the count model.

Python
import numpy as np
counts = np.array([2, 3, 2, 4, 3, 2, 3, 25, 2, 3])  # errors per minute, 10 min
mean = counts.mean()          # 4.9
var = counts.var(ddof=1)      # 50.32
print(var / mean)             # 10.27

Mean 4.9, variance 50.32, index 10.27: far above 1, so Poisson is the wrong model here and I'd fit negative binomial.

QuantitySupportModelOperation that must stay valid
Latency (ms)continuousempirical histogram / lognormalp99 threshold → tail probability
Errors/mindiscretePoisson, else negative binomialpage when count > threshold

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-1

Explain distributions as models of a generating process and how it changes a production decision.

Answer

Core answer. A distribution is a claim about the mechanism that produced the data, and the mechanism fixes the tail. In production the tail is usually the whole decision: timeouts, retry budgets, capacity headroom and SLOs are set by how often the slow tail happens, not by the median. So "which distribution?" is really "what generates this number, and does its tail decay fast or slow?"

Mechanism → distribution. Each standard distribution is the answer to a counting or waiting question:

MechanismDistributionTypical use
Count of successes in n independent trials, fixed pBinomialerror counts per batch
Count of events in a fixed interval at constant rate λPoissonrequest arrivals
Wait for the next event, constant hazard rateExponentialinter-arrival times
Sum of many small independent effectsNormalmeasurement noise
Product of many small independent effectsLog-normalservice latency, file sizes
Tail decays polynomially, P(X > x) ~ x^−αPareto / heavy-tailedburst sizes, popularity

The mechanism is the justification; the histogram shape is not.

Worked example (hypothetical figures). A service has latency with median 40 ms. Two models fit the centre equally well.

  • Exponential, mean 50 ms: P(X > 400 ms) = e^(−400/50) = e^−8 ≈ 0.034%.
  • Log-normal, median 40 ms, σ = 1.0 on the log scale: P(X > 400 ms) = 1 − Φ((ln 400 − ln 40)/1) = 1 − Φ(2.30) ≈ 1.07%.

Same 400 ms client timeout, 32× different error rate. If you sized a 0.1% retry budget off the exponential fit, the real system blows it by 10×, retries add load, and the retry storm is the incident. The decision, timeout value and retry budget, is decided entirely by which mechanism you believe.

Trade-off and deciding criteria. Exponential is memoryless: the hazard rate is constant, so a request that has already run 300 ms is no more likely to finish soon. That is right for inter-arrival times of a Poisson process and wrong for service times, which are products of many stages and therefore log-normal or heavier. The deciding test is the tail, not the centre: plot the survival function P(X > x) on a semi-log axis (straight line ⇒ exponential) and on a log-log axis (straight line with slope −α ⇒ heavy tail). Fit on held-out tail data, not the body.

This also moves capacity. M/M/1 assumes exponential service; the Pollaczek–Khinchine formula W_q = λE[S²]/(2(1−ρ)) shows waiting time scales with the second moment. A heavy-tailed service time with the same mean has a larger E[S²], so the utilization you can safely run at drops: the same ρ that was fine under exponential is not fine under log-normal.

Failure modes. Fitting by visual similarity to a histogram: the body dominates the eye and the tail is where the risk is. Assuming memoryless service times: you under-provision and the queue explodes at high ρ. Ignoring retries: each retry multiplies the tail you mis-modelled.

When not to. If the decision is semantic, does this field mean what the schema says, no distribution is needed. Reach for the mechanism and the tail only when the decision turns on how often the extreme happens.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

What are the essential properties of a CDF, and how is the Probability Integral Transform used in inverse transform sampling?

Answer

Open with the definition and the four properties, then state the transform as a two-line theorem and show the recipe.

A CDF is $F(x) = P(X \le x)$ for $x \in \mathbb{R}$. Four properties define it, and any function with all four is a valid CDF of some random variable:

PropertyStatementWhy it matters
Non-decreasing$x_1 < x_2 \Rightarrow F(x_1) \le F(x_2)$Probabilities of nested events
Limits$\lim_{x\to-\infty}F(x)=0$, $\lim_{x\to+\infty}F(x)=1$Total mass is 1
Right-continuous$F(x) = F(x^+)$Jumps allowed; $P(X=x) = F(x) - F(x^-)$
Range$0 \le F(x) \le 1$Follows from the above

Right-continuity is the one candidates drop, and it is the one that decides whether the inverse is well defined. For a discrete variable $F$ is a step function, so $P(X = x)$ is the jump height, not a density.

The Probability Integral Transform. If $F$ is continuous and strictly increasing, then $U = F(X) \sim \mathrm{Uniform}(0,1)$. The converse is the sampling algorithm: draw $U \sim \mathrm{Uniform}(0,1)$ and return $X = F^{-1}(U)$. The proof is one line:

$$P(X \le x) = P(F^{-1}(U) \le x) = P(U \le F(x)) = F(x)$$

python import numpy as np from scipy import stats

rng = np.random.default_rng(7) u = rng.random(1_000_000) x = stats.expon(scale=0.5).ppf(u) # F^{-1}(u) = -0.5 * ln(1 - u)

A trace on the exponential with rate 2 ($\mathrm{scale}=0.5$):

$u$$x = -\ln(1-u)/2$$F(x) = 1 - e^{-2x}$
0.1000.05270.100
0.5000.34660.500
0.9001.15130.900
0.9993.45390.999

Discrete case. A step CDF has no true inverse, so use the generalized inverse $F^{-1}(u) = \min{x : F(x) \ge u}$, which is np.searchsorted on the cumulative probabilities:

python p = np.array([0.5, 0.3, 0.2]) cdf = np.cumsum(p) # [0.5, 0.8, 1.0] idx = np.searchsorted(cdf, rng.random(5), side='left')

Failure modes. Tail precision is the first: computing $1 - F$ and inverting loses digits, which is why scipy.stats.norm.ppf is built on erfinv rather than on $1-\Phi$. At $u = 10^{-16}$ the naive route returns garbage. Second, interpolating a tabulated CDF creates flat segments that map many $u$ to one $x$, injecting atoms the true distribution does not have. Third, ppf typically costs several times a uniform draw, so for a fitted mixture or empirical CDF you precompute a quantile table and accept tail bias. Fourth, reusing one $u$ across variates gives perfectly correlated draws: a feature for common random numbers, a bug otherwise.

When not to use it. Rejection sampling when $F^{-1}$ has no closed form but the density is cheap; Box-Muller or ziggurat for the normal. Inverse transform is the default when you need monotone coupling, stratified or antithetic sampling, or when you already hold the CDF of a discrete distribution.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

Walk through the Bernoulli and binomial distributions, including where engineers most often get it wrong.

Answer

Bernoulli first. A Bernoulli trial is one binary outcome: X ∈ {0,1} with P(X=1)=p. Mean p, variance p(1-p). That is the atom.

Binomial is n of them. Run n independent Bernoulli trials with the same p and the count of successes is Binomial(n, p): mean np, variance np(1-p). The Bernoulli is the n=1 case, so anything true of the binomial's variance is true of the single trial's.

Why variance peaks at p=0.5. Variance = p(1-p) = p - p², a downward parabola in p, maximised where its derivative 1-2p = 0, i.e. p=0.5. The intuition: variance measures how uncertain the next trial is. At p=0.5 you have no information about it; at p=0.99 you already know the answer, so the deviation from the mean is small. The product p(1-p) is symmetric: p=0.1 and p=0.9 give identical variance.

Practitioner consequence: the standard error of a proportion is sqrt(p(1-p)/n), worst case at p=0.5. A/B test sample sizes are computed at p=0.5 for exactly this reason.

Python
import math
n = 1000
for p in (0.5, 0.1, 0.01):
    print(p, round(math.sqrt(n * p * (1 - p)), 2))
# 0.5 -> 15.81
# 0.1 -> 9.49
# 0.01 -> 3.15

To detect a 1-point absolute lift from a 50% baseline at 80% power, two-sided α=0.05, you need n ≈ 2(1.96+0.84)²·0.25/0.01² ≈ 39,200 per arm. Move the baseline to 5% and the same 1-point lift needs far fewer, because p(1-p) has dropped.

Where engineers get it wrong. Two assumptions, both routinely violated in production.

Dependence. Trials cluster: sessions from one user, requests from one host, retries of one job. The binomial assumes independent trials; correlated ones inflate the variance. Detect it by comparing the observed variance of per-group counts to np(1-p): the ratio is the variance inflation factor. If each user contributes k trials with intraclass correlation ρ, the effective sample size is n/(1+(k-1)ρ). With k=10 and ρ=0.05 that is 1+9·0.05 = 1.45: effective n is 31% smaller and confidence intervals are ~20% too narrow. Operationally that is a false positive shipped to production.

Non-constant p. If p varies across trials (different traffic sources, different days) the sum's variance picks up an extra n(n-1)Var(p) term, strictly larger than the binomial's np̄(1-p̄). Detect it with a Pearson chi-square overdispersion test: χ²/df well above 1 means the binomial is wrong. A beta-binomial fits the extra spread.

Choosing. Plain binomial when trials are genuinely independent and p is constant: closed-form, cheap, and the MLE is just the sample proportion. Beta-binomial when you have heterogeneity but no cluster structure; it adds a dispersion parameter and needs more data to pin down. Mixed models or GEE when the correlation has structure you want to model explicitly (user random effects), at the cost of fitting machinery and slower iteration.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

What does conversion rates and their variance guarantee, and what does it deliberately leave open?

Answer

The 60-second answer

A conversion rate and its variance guarantee exactly one thing: a statement about sampling noise, and only under a model you have to assume. If each visitor converts independently with the same probability p, then the observed rate p̂ is unbiased for p and Var(p̂) = p(1−p)/n. That buys a confidence interval with nominal coverage: a 95% interval covers the true p in about 95% of repeated samples of that size.

Everything else is left open. The variance says nothing about whether p̂ is biased, nothing about whether the gap between two arms is causal, and nothing about whether the effect is large enough to act on. It is a precision guarantee, not a validity guarantee.

Mechanism

SE = sqrt(p(1−p)/n). Absolute SE is largest at p = 0.5 and shrinks toward the extremes, but relative precision SE/p grows without bound as p → 0. That is why rare conversions are expensive: to hold ±10% relative precision at 95%, n = 1.96²(1−p)/(0.1²p) = 384(1−p)/p.

Base rate pn per arm for ±10% relative, 95%
20%~1,540
2%~18,800
0.2%~192,000

Trade-offs

The Wald interval is what the variance formula hands you, and it is the wrong default for rare events: at p̂ = 0 with n = 100 it produces [0, 0], and it undercovers near the boundaries. Wilson or Agresti–Coull intervals keep coverage and stay inside [0,1]; Clopper–Pearson is conservative. If you must peek at results continuously, a fixed-horizon interval is invalid: use always-valid or sequential inference instead. And if the question is causal, no interval on a single rate helps; you need a randomized comparison and the interval on the difference.

Failure modes

  • Sample ratio mismatch: the variance is fine but the estimate is biased because assignment broke. Detect with a chi-square on arm counts; alarm below p = 0.001.
  • Novelty or primacy: the early rate is not the steady-state rate. Detect by plotting the rate by day or by cohort.
  • Optional stopping: peeking at a fixed-horizon CI inflates false positives. Detect by comparing the pre-registered n to the actual stopping rule.
  • Denominator drift: the population behind the rate changed mid-experiment. Detect by segmenting the rate by source.

When this is the wrong tool

If the decision turns on causality, external validity, or a rate so rare the normal approximation fails, the rate-plus-variance framing is the wrong instrument. Compute n from the observed base rate and the smallest effect you would act on, and treat the interval as a bound on noise, never as evidence that the number is right.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

How does the Negative Binomial relate to the Geometric distribution, and when do you choose Negative Binomial over Poisson to model counts?

Answer

The Geometric distribution models the number of Bernoulli trials (or failures) needed to achieve exactly 1 success. The Negative Binomial generalizes this to the sum of $r$ independent, identically distributed Geometric random variables: the number of trials or failures until $r$ successes occur.

In count regression and production telemetry modeling, the primary reason to choose Negative Binomial over Poisson is overdispersion, when the empirical variance of the count data significantly exceeds its mean $(\mathrm{Var}(Y) > \mathbb{E}[Y])$.

Mathematical Mechanism

  1. Poisson Restriction: A standard Poisson process has a single parameter $\lambda$ where $\mathbb{E}[Y] = \mathrm{Var}(Y) = \lambda$. It assumes events occur independently at a constant rate.
  2. Negative Binomial Formulation: When rate heterogeneity exists across entities (for example, user request rates varying across sessions), we can model the rate $\lambda$ itself as a Gamma-distributed random variable: $\lambda \sim \mathrm{Gamma}(\alpha, \beta)$. Marginalizing over $\lambda$ yields a Gamma-Poisson mixture, which is algebraically equivalent to the Negative Binomial distribution: $$\mathbb{E}[Y] = \mu, \quad \mathrm{Var}(Y) = \mu + \alpha \mu^2$$ where $\alpha$ is the dispersion parameter. As $\alpha \to 0$, the dispersion penalty disappears and the variance converges back to the Poisson mean $\mu$.

Concrete Example: Request Retries Under Outages

Assume we model API retry counts per client session during an outage. In clean traffic, requests fail uniformly at random; during partial degradation, a small subset of misconfigured clients retry aggressively while others succeed immediately.

Python
import numpy as np
from scipy import stats
import statsmodels.api as sm

rng = np.random.default_rng(42)

# Simulated user failure counts with unobserved rate heterogeneity (Gamma-Poisson mixture)
# Poisson would force var == mean. Here mean = 4.0, var ~ 20.0.
rates = rng.gamma(shape=1.0, scale=4.0, size=10_000)  # E[rate]=4
counts = rng.poisson(rates)

print(f"Sample Mean: {counts.mean():.2f}, Sample Var: {counts.var():.2f}")
# Sample Mean: 4.01, Sample Var: 20.15 -> Var/Mean ratio ~ 5 (Overdispersed)

# Fitting Poisson GLM vs Negative Binomial GLM
X = np.ones_like(counts)
poisson_model = sm.GLM(counts, X, family=sm.families.Poisson()).fit()
nb_model = sm.GLM(counts, X, family=sm.families.NegativeBinomial(alpha=1.0)).fit()

print(f"Poisson log-likelihood: {poisson_model.llf:.1f}")
print(f"Negative Binomial log-likelihood: {nb_model.llf:.1f}")
# Negative Binomial achieves substantially higher log-likelihood

Failure Mode

Using Poisson on overdispersed data does not bias the point estimates $\hat{\beta}$ of regression coefficients, but it severely underestimates the standard errors of those coefficients. In production A/B testing or latency/retry modeling, this deflates $p$-values and leads to false discoveries: declaring an infrastructure change or algorithm variant statistically significant when the observed fluctuation is merely natural clustering.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

Describe the Poisson distribution and the evidence you would collect before relying on it.

Answer

Poisson models the count of events in a fixed interval when events occur independently at a constant average rate λ. If X ~ Poisson(λ), P(X=k)=e^{-λ}λ^k/k!, and E[X]=Var[X]=λ. It is the default for request arrivals, error counts, packet arrivals, and radioactive decays.

Before relying on it, I collect evidence for four assumptions: independence, constant rate, no simultaneous events, and mean=variance. The first three are structural; the fourth is the one I test numerically.

Evidence checklist

  • Fixed-length intervals with the same exposure. If intervals differ, use an offset.
  • Independence: plot counts over time and autocorrelation; check inter-arrival gaps against an exponential distribution (QQ plot, KS test). Clustering or retries break it.
  • Constant rate: split the interval and compare λ estimates; test for trend or seasonality. If the rate varies, use a non-homogeneous Poisson model.
  • No simultaneous events: check timestamps for duplicates. Two events at the same timestamp violate the Poisson process.
  • Mean=variance: compute the index of dispersion D = s² / mean, or the Pearson statistic X² = Σ (x_i - mean)² / mean. Asymptotically, X² ~ χ²_{n-1} under Poisson. D ≈ 1. D >> 1 means overdispersion; D << 1 means underdispersion.
  • Zero inflation: compare observed zeros to Poisson-predicted zeros. Excess zeros suggest a zero-inflated model.

Worked dispersion test

Twelve hourly error counts: [4, 6, 5, 20, 3, 7, 4, 5, 18, 6, 5, 5]. Mean = 7.33. Pearson X² = 46.45 on 11 df. The 99.9th percentile of χ²_11 is 31.26, so p < 0.001. D = 4.22. The variance is about four times the mean; Poisson intervals would be too narrow.

Python
import numpy as np
counts = np.array([4, 6, 5, 20, 3, 7, 4, 5, 18, 6, 5, 5])
n = len(counts)
mean = counts.mean()
X2 = ((counts - mean) ** 2 / mean).sum()
D = X2 / (n - 1)
print(mean, X2, D)
# 7.333333333333333 46.45454545454546 4.223140495867768

Trace: sum = 88, n = 12, mean = 88/12 = 7.333333333333333. Sum of squared deviations divided by mean = 46.45454545454546. D = 46.45454545454546 / 11 = 4.223140495867768. Under Poisson, X² ~ χ²_11. 46.45 > 31.26 (99.9th percentile), so p < 0.001. Overdispersed.

Failure modes and alternatives

  • Overdispersion: variance > mean, common in error counts because failures cluster. Poisson standard errors are too small, p-values too small, prediction intervals too narrow. Detect with the dispersion test. Fix: negative binomial (Gamma-Poisson) or quasi-Poisson.
  • Underdispersion: variance < mean, from negative correlation or fixed-capacity queues. Poisson overstates variance.
  • Non-stationarity: rate changes with time; pooling intervals gives a mixture, often overdispersed. Detect by plotting counts and testing trend. Fix: non-homogeneous Poisson or a time-varying model.
  • Zero inflation: more zeros than Poisson predicts. Detect by comparing observed vs expected zeros. Fix: zero-inflated Poisson.
  • Dependence: autocorrelation or clustering. Detect with ACF, runs test, exponential QQ plot of inter-arrival times. Fix: renewal or clustered process.

I rely on Poisson only when the dispersion test is not significant, the rate is stable across the interval, inter-arrival gaps look exponential, and there is no clustering or excess zeros. Otherwise I use a negative binomial or a time-varying model.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-20

What trade-off does sampling from a distribution force that a junior answer usually skips?

Answer

The trade-off is exactness for tractability, and the currency you pay is variance. Sampling lets you estimate an expectation you cannot write in closed form: an integral over a high-dimensional space, a tail probability, the output of a simulator, but the number you get back is a random variable, not the answer. Its error shrinks only as 1/√N, so precision is expensive in a way a junior answer routinely underestimates.

State the assumption first: you are estimating E[f(X)] and you can draw i.i.d. samples of X. Then the estimator (1/N)Σf(xᵢ) is unbiased, and its standard error is σ_f/√N, where σ_f is the standard deviation of f(X). That √N is the whole story:

target errorsamples needed (σ_f = 1)
0.1100
0.0110,000
0.0011,000,000

Halving the error costs 4× the samples; a 10× tighter answer costs 100×. "Just sample more" treats that cost as linear or free. It is neither.

The second trade-off is reproducibility against independence. A single seeded generator is reproducible but serial: results depend on call order, so two runs that draw in a different order diverge. Splitting into independent streams buys parallelism, but now each result is tied to a specific stream and seed, and you have to record which. You cannot have one global seed and independent parallel streams at the same time.

Python
# NumPy 1.25+ (Generator.spawn added in 1.25)
import numpy as np
rng = np.random.default_rng(0)
streams = rng.spawn(4)          # 4 independent generators
for s in streams:
    print(s.normal(size=1000).mean())   # each mean ~ N(0, 1/1000)

Each stream's mean has standard error 1/√1000 ≈ 0.032, so four streams give you four noisy estimates, not one four-times-better one, unless you pool them, which is the same as a single stream of 4000 (SE ≈ 0.016).

Alternatives worth naming: when the dimension is low, quadrature is exact and cheap and you should not sample at all. Quasi-Monte Carlo with low-discrepancy sequences converges closer to 1/N in moderate dimensions. Importance sampling cuts σ_f directly when you know where the mass sits, but a proposal with lighter tails than the target gives an estimate that is biased in practice and has infinite variance, which no amount of sampling fixes.

Failure modes to name: correlated samples that make the real error larger than σ/√N suggests (reused random numbers, a stream split that is not actually independent), and silent bias from a bad proposal. Both are caught the same way: compare against a small case you can solve exactly, and report the effective sample size, not just N.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

A teammate proposes a design that hinges on the exponential distribution and memorylessness. How do you evaluate it?

Answer

Core answer. First ask what the design actually consumes from the distribution. If it only uses the mean (average latency, average capacity) memorylessness is irrelevant and the debate is a distraction. If it uses tail probabilities, conditional remaining time, or a queueing formula, memorylessness is load-bearing and must be justified against data. State that split before arguing about the distribution.

Why memorylessness is the whole question. For a continuous distribution, memorylessness is equivalent to a constant hazard rate, and the exponential is the only continuous distribution with that property. So "is it exponential?" and "is the hazard flat over the range we care about?" are the same question. That is the assumption to make explicit.

Python
from scipy import stats
exp = stats.expon(scale=10)              # constant hazard 0.1
exp.cdf(15)                              # 0.7769
(1 - exp.cdf(15)) / (1 - exp.cdf(5))     # 0.3679
1 - exp.cdf(10)                          # 0.3679  -> equal: memoryless

Where it breaks. Service times, retry backoff, and human-driven waits have rising or falling hazard, so the exponential understates the tail. The cost shows up in queueing arithmetic. For M/G/1, mean wait is Wq = λ·E[S²] / (2(1-ρ)). At λ=0.8, E[S]=1 (ρ=0.8): exponential service gives E[S²]=2 and Wq=4; deterministic service gives E[S²]=1 and Wq=2. Same mean, double the wait: the second moment, not the mean, drives the queue.

How to check it. Plot the empirical hazard (Nelson-Aalen) or the log-survival curve; a straight line on log-survival supports exponential, curvature does not. Compare the coefficient of variation: exponential forces CV=1, so CV well above 1 signals a heavy tail. Fit a Weibull and test shape k=1; k>1 is rising hazard (aging), k<1 falling.

What changes the decision. If the design only needs the mean, keep the exponential for tractability and move on. If it needs tail latency, capacity at high utilization, or conditional remaining time, replace it with Weibull, log-normal, or a phase-type fit and re-run the queueing numbers. The failure mode to name: assuming exponential service in a queueing model when the real distribution is heavy-tailed understates queue length and p99 badly, and casual load tests miss it because they rarely push utilization high enough to expose the second-moment term.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Teach the log-normal distribution to an engineer who has only seen it as a rule of thumb.

Answer

If a quantity is a product of many independent positive factors, its log is a sum, so the CLT makes that log approximately normal, and the quantity itself log-normal. Formally X = e^Y with Y ~ N(mu, sigma²). Latency, file sizes and income are the usual examples because each accumulates multiplicatively: a request's time is a chain of per-stage factors, not a sum of fixed costs. The two numbers to carry: median = e^mu, mean = e^(mu + sigma²/2). The gap between them is set by sigma², and it is large.

Why the mean sits high. log(mean) = mu + sigma²/2, so X exceeds its own mean exactly when Y - mu > sigma²/2, i.e. when Z > sigma/2 for standard normal Z. That gives a checkable statement: the fraction of the population above the mean is P(Z > sigma/2). 0.31 at sigma=1, 0.23 at sigma=1.5, 0.16 at sigma=2. The mean is not the typical value; it is a tail-weighted number.

Python
import numpy as np
rng = np.random.default_rng(7)
x = rng.lognormal(mean=0.0, sigma=1.5, size=100_000)  # Y ~ N(0, 1.5^2)
np.median(x)           # ~1.00  = exp(mu)
x.mean()               # ~3.08  = exp(mu + sigma^2/2) = exp(1.125)
np.mean(x > x.mean())  # ~0.23  = P(Z > sigma/2) = P(Z > 0.75)

When the mean is the right answer. The deciding question is whether you are describing one item or summing many.

  • Describing a single item's typical experience (one user's page load, one file's size) use the median and percentiles. The mean describes no actual request.
  • Summing over many items (total bytes served, total cost, capacity) use the mean, because E[sum] = N·E[X]. The mean is the correct per-item figure for an aggregate.
  • Queueing and tail capacity: M/G/1 waiting time is λE[S²]/(2(1-ρ)), which needs the second moment E[X²] = exp(2mu + 2sigma²), not the median. Here the tail is the whole point.

Failure modes. Reporting mean latency as "typical" overstates what most users see: at sigma=1.5, 77% of requests fall below it. A mean ± std interval is worse: at these parameters it is 3.08 ± 8.97, whose lower bound is negative and meaningless for a positive quantity. The correct interval is multiplicative: exp(mu ± 1.96·sigma) = [0.05, 18.9]. Averaging ratios, or averaging already-logged values without converting back, is a silent unit error.

Detecting it. Plot log(x): if the histogram is roughly normal and a Q-Q plot against the normal is straight, the raw variable is log-normal. Skewness of the raw data is the quick tell. The 68-95-99.7 rule still applies, but in log space: one sigma is a factor of e^sigma, not a fixed offset.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Where does the normal distribution and where it comes from matter, and where is it irrelevant?

Answer

Core answer. The normal is the right model when the quantity is a sum of many small, roughly independent contributions with finite variance: measurement error, sensor noise, the sampling distribution of a sample mean. It is the wrong model when the quantity is a product (revenue per user, file size), a maximum (worst-case latency, peak load), or a count of rare events (errors per minute at a low rate). The rule I use: if the decision turns on the center (a mean, a sum, a standard error) the CLT usually rescues you even when the raw data is skewed. If the decision turns on the tail (p99, VaR, capacity) the data's own tail governs, and a Gaussian fit will understate it.

Why. The CLT says a sum of n iid finite-variance variables converges to normal with error ~ 1/√n. Three conditions do the work: additive, near-independent, finite variance. Break one and you get a different limit: multiplicative growth gives log-normal, a maximum gives Gumbel/Fréchet, rare counts give Poisson, and infinite variance (Pareto α ≤ 2) breaks the CLT outright.

How much it matters in the tail. Match a log-normal and a normal on the same mean and SD, then ask how often each exceeds 10:

Python
import numpy as np
from scipy import stats

m  = np.exp(0.5)                        # lognormal(mu=0, sigma=1) mean = 1.649
sd = np.sqrt((np.exp(1) - 1) * np.exp(1))  # ... and SD = 2.161

stats.norm(m, sd).sf(10)                # 5.58e-05
stats.lognorm(s=1, scale=1).sf(10)      # 0.010651

Same first two moments, ~190× difference at the threshold 10. That gap is the whole argument: moments don't pin the tail.

Deciding criteria.

QuantityMechanismModelNormal fails when
Sensor noise, measurement errorsum of small independent perturbationsNormalone source dominates, or errors multiply
Latency, response timeservice + queueing; tail set by queueinglog-normal or empirical quantilesyou need p99+
Requests/errors per intervalrare independent eventsPoisson (≈ normal for λ ≳ 20)λ small; skew and zeros
Revenue, file size, incomemultiplicative growthlog-normal / power lawalways, for tail risk
Sample mean of skewed dataCLT on the estimatorNormal for the meaninfinite variance
Max of n drawsextreme valueGumbel/Fréchetalways

Failure modes, and how you catch them. A p99.9 latency SLO set at mean + 3σ gets breached constantly; catch it with a Q-Q plot of the empirical quantiles against the fitted normal, or by comparing empirical p99.9 to the fitted value. A t-test on per-user revenue gives CIs that are too narrow and false positives; catch it by bootstrapping the statistic and comparing intervals. Capacity plans built on a normal under-provision; catch it by backtesting: count exceedances and compare to the predicted rate.

Where it's irrelevant. Regression residuals don't need to be normal: OLS coefficients are asymptotically normal by the CLT, so inference survives skewed errors with heteroskedasticity-robust standard errors. Medians, ranks, and quantile regressions make no distributional assumption. Tree ensembles don't either. And the normal is a statement about the estimator's sampling distribution, not about the data: confusing the two is the most common version of this mistake.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

How do you interpret deviations from the reference line in a normal Q-Q plot to diagnose heavy tails, skewness, or bimodality?

Answer

A Quantile-Quantile (Q-Q) plot plots sorted empirical order statistics $x_{(i)}$ against theoretical quantiles $F^{-1}(p_i)$ for plotting positions $p_i = (i - 0.5) / n$. When the empirical data matches the reference distribution up to a location-scale transform ($,y = \mu + \sigma x,$), points align on a straight line. Deviations diagnose exact structural departures based on whether empirical values exceed or fall short of theoretical quantiles across the domain.

Geometric Interpretation of Deviations

PhenomenonVisual Signature (against Normal line)Mechanism
Heavy Tails (leptokurtic)S-shape: left tail sags below line, right tail curves above lineEmpirical extremes are larger in magnitude than normal quantiles ($x_{(1)} \ll z_\alpha$ and $x_{(n)} \gg z_{1-\alpha}$).
Light Tails (platykurtic)Inverted S-shape: left tail stays above line, right tail stays below lineEmpirical domain is bounded or truncated; extremes fail to reach Gaussian extremes.
Right Skew (positive)Upward convex curve (U-shape) across the plotBoth tails bend upward: left tail points sit above the line (closer to zero), right tail points sit well above the line.
Left Skew (negative)Downward concave curve (inverted U-shape)Both tails bend downward: left tail points sit far below the line, right tail points plateau below the line.
BimodalityDistinct S-shaped step or plateau near the median with two separated linear segmentsHigh density at two distinct modes compresses quantiles locally; the gap between modes creates a steep inflection or horizontal shelf.

Worked Code Trace

Python
import numpy as np
from scipy import stats

rng = np.random.default_rng(42)
n = 1000

# 1. Heavy-tailed data: Student-t with df=3
y_heavy = rng.standard_t(df=3, size=n)
# 2. Right-skewed data: Exponential with scale=1.0
y_skewed = rng.exponential(scale=1.0, size=n)

# Compute theoretical quantiles manually
p = (np.arange(1, n + 1) - 0.5) / n
z_theory = stats.norm.ppf(p)

# Inspect tail quantiles (e.g., 99.9th percentile at index 998)
print(f"Theoretical Gaussian z_0.999: {z_theory[-2]:.2f}")  # ~3.09
print(f"Heavy-tailed empirical x_0.999: {np.sort(y_heavy)[-2]:.2f}")  # often > 5.5
print(f"Right-skew empirical x_0.999: {np.sort(y_skewed)[-2]:.2f}")  # often > 6.0

Failure Modes & Production Nuance

  1. Conflating global skew with heavy tails: A right-skewed distribution exhibits extreme right quantiles that mimic a heavy tail on the positive side, but its left tail is compressed against a lower bound (curving above the line). Checking both tails simultaneously prevents misidentifying Pareto or Log-Normal behavior as symmetric heavy tails like Student-t.
  2. Small sample size hallucinations: For $n < 50$, sample variance in order statistics causes extreme points to deviate substantially even from a true Gaussian. Never infer a power law without plotting simulated confidence bands (pointwise or simultaneous envelope) or using Kolmogorov-Smirnov / Anderson-Darling tests tuned for the specific hypothesis.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

How do you distinguish between heavy-tailed power law distributions and thin-tailed distributions in real-world data, and what are the implications for estimation and risk?

Answer

Thin-tailed distributions (like normal or exponential) have tails bounded by an exponential decay: $P(X > x) \sim e^{-cx}$. Heavy-tailed distributions decay slower than any exponential; power laws are a strict subclass where the survival function decays algebraically: $P(X > x) \sim C x^{-\alpha}$ for $x \ge x_{\min}$, with tail index $\alpha > 0$.

How to distinguish them in data

  1. Complementary Cumulative Distribution Function (CCDF) on log-log scales: Plot $\log P(X > x)$ against $\log x$. A power law produces an asymptotically straight line with slope $-\alpha$. An exponential curves downward sharply (dropping as $-cx$). A log-normal bends concave downward across orders of magnitude before flattening, which frequently fools people fitting a straight line to a plain histogram.
  2. Log-likelihood Ratio Tests: Fit candidate distributions (e.g., Pareto, log-normal, exponential) strictly above a threshold $x_{\min}$ using maximum likelihood, then run Vuong's likelihood ratio test to see if a power law actually outperforms alternatives.
  3. Tail moments and convergence: Check empirical variance stability. If sample variance fails to stabilize and instead jumps whenever a new maximum arrives, the second moment $\mathbb{E}[X^2]$ does not exist in the underlying data generating process (guaranteed when $\alpha \le 2$).
Python
import numpy as np
from scipy import stats

rng = np.random.default_rng(42)
# Pareto with alpha=1.5 (infinite variance, finite mean)
pareto_samples = (rng.pareto(a=1.5, size=50_000) + 1)
# Exponential (thin tail, mean=2.0)
exp_samples = rng.exponential(scale=2.0, size=50_000)

# Ratio of maximum to sum over growing sample prefixes
def max_to_sum_ratio(arr):
    cumsum = np.cumsum(arr)
    cummax = np.maximum.accumulate(arr)
    return cummax / cumsum

# Thin tail ratio drops to 0 rapidly; heavy tail alpha <= 1 remains non-zero.
# For alpha=1.5, sample variance fluctuates wildly:
print("Exp var first 5k vs 50k:", np.var(exp_samples[:5000]), np.var(exp_samples))
print("Pareto var first 5k vs 50k:", np.var(pareto_samples[:5000]), np.var(pareto_samples))
PropertyThin-Tailed (e.g., Exponential, Gaussian)Power Law ($P(X > x) \sim x^{-\alpha}$)
Tail bound$P(X > x) \le c_1 e^{-c_2 x}$$P(X > x) \sim C x^{-\alpha}$
MomentsAll moments existMoment $k$ exists only if $k < \alpha$
Central Limit TheoremStandard CLT applies; sample mean converges as $1/\sqrt{n}$If $\alpha \le 2$, CLT fails; sample mean does not converge to a Gaussian
Extreme event riskGoverned by many small additions (sum of squares)Governed by the single largest outlier (subexponential catastrophe principle)

Implications for estimation and risk

  • Sample Means and CLT Breakdown: When $\alpha \le 2$, variance is infinite; sample variances swing by orders of magnitude based on a single outlier. If $\alpha \le 1$, the mean itself is infinite; computing an arithmetic mean SLA or expected value is mathematically undefined and yields numbers that drift upward as sample size grows.
  • Risk and Capacity Planning: In thin tails, aggregate load spikes require many independent units to spike simultaneously (exponentially unlikely). In power laws, aggregate overload is almost always caused by a single extreme event ($X_{(n)} \approx \sum X_i$). Provisioning headrooms via $\mu + 3\sigma$ guarantees catastrophic under-provisioning. Capacity models must track extreme order statistics and high percentiles ($p99.9$), or rely on non-parametric truncation boundaries.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

How would you test a claim that the system depends on the uniform distribution and its uses?

Answer

The claim is not testable until you name the support and the point where the system consumes it. Turn "we depend on uniform" into a null: the values consumed at the bucket or sample boundary are i.i.d. uniform on {0..k-1} (sharding, key routing) or on [0,1) (sampling, jitter, backoff). Then collect real values at that boundary (the bucket index per key, not the hash bytes) run a goodness-of-fit test paired with an effect size, and finish by replaying an adversarial key set. At production n a bare p-value always rejects, so the number worth reporting is imbalance, not significance.

Pick the test by support.

DataTestRule of thumbBlind spot
Bucket counts over k binsPearson chi-square, df = k-1expected count >= 5 per bin, so n >= 5kbinning hides one hot shard unless max/mean is also reported
Continuous draws, n >= 100Kolmogorov-Smirnovreject at alpha = 0.05 when D > 1.36/sqrt(n); n = 10,000 gives D > 0.0136weak exactly in the tails that break sharding
Same data, tail-sensitiveAnderson-Darlingtail-weighted; critical values in scipyflags marginal skew you may not care about
Many shards or bins scannedchi-square plus Bonferronidivide alpha by the number of comparisonspower drops sharply after correction

Independence is a separate claim: uniform marginals with serial correlation still wreck a shard map, so add a runs test or lag-1 autocorrelation. Qualifying an RNG itself is a different job: that is what TestU01 BigCrush or Dieharder batteries are for.

Report an effect size, not just the p-value. Worked example: 64 shards, 100,000 keys, expected 1,562.5 keys per shard. One hot shard holding 2,100 keys contributes (2,100 - 1,562.5)^2 / 1,562.5 = 184.9 on its own, and chi-square at alpha = 0.05 with df = 63 is about 82.5. So a single shard 34% over the mean rejects the uniform null by itself. That translates into the alert you actually want: max/mean > 1.15 across 64 shards, sustained for an hour.

The check, in code.

Python
# Python 3.12, scipy 1.14
import numpy as np
from scipy import stats

counts = np.asarray(bucket_counts)        # keys per shard, sampled from production
chi2, p = stats.chisquare(counts)         # H0: uniform over the k buckets
print("chi2", chi2, "p", p, "max/mean", counts.max() / counts.mean())

u = np.asarray(raw_draws)                # the uniforms the sampler consumed
print(stats.kstest(u, "uniform"))         # continuous: statistic D, p
print(stats.anderson(u, "uniform"))       # tail-weighted variant

Test the pipeline, not the digest. A well-mixed hash that passes a bytes-level chi-square still buckets badly if you assign with hash(key) % k and k shares factors with the modulus; take the high bits or a fixed-width slice of a real digest (SHA-256, MurmurHash3 x86_128) and test the counts. Test the input too: sequential integers or UUIDv4-shaped keys may look uniform because of the generator, not the system, so replay a skewed set (one hot tenant) and re-run. Reserve SMHasher-style avalanche tests for qualifying the hash function itself.

Failure modes you will actually meet. It passes on Tuesday and breaks on the holiday key mix: catch it with a sustained max/mean alert, not a one-off test. The chi-square passes while the top decile is heavy: plot the empirical CDF against the diagonal, where a staircase is visible even when the statistic is not. Someone runs the test with expected counts below 5, the chi-square approximation is invalid and the p-value is noise; merge bins or use an exact multinomial test. And hundreds of shards tested uncorrected give a false alarm roughly every 20 scans.

When to skip the test. If the only decision is "no shard more than 15% over the mean," measure that directly: the hypothesis test adds a p-value nobody acts on. If downstream tolerates skew (a cache, a best-effort sampler), a sampled million keys monthly beats per-request instrumentation. Reach for the full test when the uniformity assumption is load-bearing, as in consistent hashing or load-splitting logic, where a tail deviation silently concentrates traffic.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

You're wiring a PyMC posterior into a scipy simulation. How do you confirm each library's parameterisation (rate vs scale, shape-rate vs shape-scale, variance vs precision) before trusting the output, and what breaks when they disagree?

Answer

The convention is part of the API, not a property of the distribution. Read the signature first, then pin it with an identity you can compute by hand. Never infer it from whether the output looks reasonable: a swapped rate and scale produces a perfectly plausible sample.

Three ambiguities cover almost everything you hit:

FamilyAmbiguityWho picks which
Exponential, Poissonrate λ vs scale 1/λscipy/numpy: scale; R rexp, PyMC pm.Exponential(lam=): rate
Gamma, Weibullshape–rate (α, β) vs shape–scale (α, θ = 1/β)scipy/numpy: scale; R rgamma default, PyMC pm.Gamma(alpha, beta), Stan: rate
Normalstandard deviation vs precision τ = 1/σ²scipy norm(loc, scale): sd; PyMC v4+ sigma (v4 removed the tau precision alias v3 accepted); sklearn BayesianRidge(alpha=, lambda_=): precision

Two checks settle it. First, the signature:

python import inspect, numpy as np from scipy import stats inspect.signature(stats.expon) # (loc=0, scale=1) inspect.signature(np.random.default_rng().exponential) # (scale=1.0, size=None)

Second, an analytic identity. For the exponential, mean = scale = 1/λ and variance = scale². Sample 200k draws and assert both:

python rate, scale = 0.5, 2.0 rng = np.random.default_rng(0) x = rng.exponential(scale=scale, size=200_000) assert abs(x.mean() - 1/rate) < 0.02 # 2.0 assert abs(x.var() - 1/rate**2) < 0.05 # 4.0

The strongest cross-library check is a log-density at a fixed point, because it catches a mismatch that moments can hide. log f(x) = log λ − λx, so at x = 1 with λ = 0.5 the value is −1.1931:

python assert np.isclose(stats.expon(scale=1/rate).logpdf(1.0), np.log(rate) - rate * 1.0)

What breaks when two libraries disagree: nothing crashes. A PyMC posterior rate λ = 0.5 fed to stats.expon(scale=0.5) gives mean 0.5 instead of 2.0, and P(X > 5) drops from e^−2.5 ≈ 0.082 to e^−10 ≈ 4.5e−5: a factor of ~1800 in the tail you were sizing capacity against. Variance scales as scale², so a 4× error in scale is a 16× error in variance, and an A/B test sized on that variance is off by the same 16× in required sample size. The same swap on a Gamma with shape 2 and rate 1/3 moves the mean from 6 to 0.667.

Detection in practice: a property test in CI asserting sample mean and variance against closed forms, plus the logpdf-at-a-point assertion, run on every dependency bump. Version drift is real, PyMC v4 dropped the tau alias, so pin versions and let the test fail loudly rather than reading a changelog after the fact.

The design fix is to convert once at the boundary: a thin adapter per library that takes one canonical convention (say shape–rate) and returns that library's own call, so no call site ever passes a bare number. Record the convention in the model card next to the fitted parameters.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-16

What failure would you inject to check a team's understanding of mixture distributions?

Answer

Clarify, then answer. "Inject a failure" here means seeding a fault into the data or traffic path and watching how the team diagnoses it, not breaking a service. Assumption that matters: the team already has dashboards and an on-call loop, so you are testing whether they reason about distributions, not whether they can restart a pod.

The injection: add a second population to a metric that already has a single-population baseline, and make the aggregate summary move the wrong way. Concretely, roll a new client version to 12% of sessions that batches ten requests per session. Server-side per-request latency drops (30 ms vs 50 ms), so fleet-wide mean latency improves. Per-session wall time rises (800 ms vs 500 ms) because of the batching delay.

per-request mean: 0.88*50 + 0.12*30 = 47.6 ms   (better than 50)
per-session mean: 0.88*500 + 0.12*800 = 536 ms  (worse than 500)

Same traffic, opposite conclusions, decided entirely by the unit you aggregate over. A team that models one distribution reports a latency win and ships. A team that sees the mixture asks which unit the SLO is written in, then segments by client version.

What the exercise reveals:

ResponseReading
Reports the improved mean, closes the ticketSingle-distribution mental model; the mixture is invisible to them
Notices the histogram is bimodal, asks for the grouping variableMixture-aware; will segment
Segments by client version, reports both componentsCorrect, and can say when segmentation is the wrong move
Fits a GMM/EM without checking labelsKnows the tool, may not know when it is needed

Detection signals to watch for: a histogram with two modes, variance far above the mean for count-like data, per-cohort p99 diverging while the pooled p99 looks flat, a KS test between the two cohorts rejecting the null.

Trade-offs. Hard segmentation needs a known grouping variable and enough samples per segment: small cohorts give per-segment estimates noisier than the pooled one. Fitting a mixture (EM/GMM) works when labels are unobserved, but costs parameters, can converge to degenerate components, and hands you parameters you still have to interpret. When the components overlap heavily, neither helps: a robust summary (median, p95) beats both, because splitting adds variance without separating signal.

Failure modes of the injection itself: a cohort under ~1% of traffic is invisible and tests nothing; labeling the cohort in the metric makes it trivial; making the two components overlap so much that segmentation cannot separate them tests the wrong skill. Pick a cohort size (5–15%) and a separation wide enough that the histogram shows two modes while the mean does not.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

How would you review a pull request whose risk is the empirical distribution?

Answer

First two minutes. I'd ask what the empirical distribution is standing in for. If the PR replaces a fitted parametric model with a bootstrap or ECDF to get an interval on the median or mean, that's usually fine and I review it as ordinary code. If it's producing a tail quantile: p99, p99.9: the empirical distribution is the wrong tool and the review turns on sample size. That one question decides most of the review.

Check n against the quantile. The bootstrap resamples the observed values, so every resample statistic is bounded by the observed support. A p99 estimate can never exceed the largest observation in the sample. With n=10:

Python
import numpy as np
rng = np.random.default_rng(0)
sample = np.array([10, 12, 13, 15, 18, 21, 24, 30, 45, 120])
boot_p99 = np.array([
    np.percentile(rng.choice(sample, size=len(sample), replace=True), 99)
    for _ in range(2000)
])
print(boot_p99.max(), sample.max())

np.percentile with q=99 on 10 points interpolates between the 9th and 10th order statistics (index 0.99 × 9 = 8.91). So boot_p99.max() cannot exceed sample.max() = 120, and it reaches 120 whenever a resample draws the maximum at least twice. The interval isn't estimating a p99; it's describing the top two points you happened to observe. Rule of thumb: you need at least 1/(1−q) samples to have a single observation in the tail, 100 for p99, and thousands for a stable interval. If the diff computes p99 from n=200, I block it.

Check the iid assumption. rng.choice on a time-ordered array assumes independent samples. Latency and error data are autocorrelated, and the bootstrap then understates the interval. Detection: is the array sorted by timestamp, or is there a groupby/window upstream? If so, ask for a block bootstrap.

Check the seed and the serving path. default_rng(0) in a test is good: reproducible. The same line in a serving path hides run-to-run variance and makes the interval look stable when it isn't. And if the PR samples from the empirical distribution at request time, the full array has to stay resident; a parametric fit needs two floats. At n in the millions that's a real memory line item.

CheckWhat to look for in the diffWhy it decides the review
Support vs quantilenp.percentile(..., 99) with len(sample) < 1000p99 is interpolated between top order stats; interval capped at observed max
iid assumptionrng.choice on a time-ordered arrayAutocorrelation makes the interval too narrow; needs block bootstrap
Seed in proddefault_rng(0) in a serving pathFixed seed hides run-to-run variance; fine in tests
Memory at servingstoring all n samplesEmpirical sampling keeps the full array resident; parametric needs 2 floats

Trade-offs. Empirical beats parametric when the shape is unknown and the statistic is central: no distributional assumption, and it's consistent. It loses to a parametric fit when you need to extrapolate, and it loses to extreme-value theory (a fitted generalized Pareto tail) when the question is genuinely about the tail. What changes the choice: the quantile being estimated, n, and whether the data is iid.

Failure modes and detection. (1) Tail extrapolation: the interval's upper bound is pinned at the observed max. Detect by comparing boot_p99.max() to sample.max(). (2) Autocorrelation: interval too narrow. Detect by comparing the bootstrap interval width to a block-bootstrap width on the same data. (3) Fixed seed in production: variance disappears. Detect by running the job twice and diffing the interval.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

What belongs in a runbook section on the beta distribution, and what does not?

Answer

A runbook section on the beta distribution is defensible only where a live procedure turns counts into a decision. Assume that: one service, one binary outcome per exposure (error / no error), and a canary gate that reads the resulting error rate. The section is then a scoping question. What belongs: the prior as fixed numbers, the statistic the gate actually reads, the sample floor below which the section reports an interval instead of a rate, the numeric threshold, the update step, and who may change the prior. What does not belong: the beta-binomial integral, the conjugacy derivation, the prior-selection study, the Beta-vs-Dirichlet comparison, and any step that needs judgement not yet applied, such as "choose a prior that seems reasonable". Exclusion test: if the prior and the threshold cannot be written as numbers, the material is a design note, not a runbook section.

That is not a stylistic preference. With a uniform prior Beta(1, 1) the posterior is Beta(errors + 1, trials - errors + 1) and its CDF has a closed form, so the section's floor is arithmetic rather than opinion.

from scipy.stats import beta          # Python 3.11, scipy 1.11
A0, B0, GATE = 1.0, 1.0, 0.02         # uniform prior, 2 pseudo-trials

def posterior(errors, n):             # exact conjugate update, O(1)
    return A0 + errors, B0 + n - errors

def upper95(errors, n):
    a, b = posterior(errors, n)
    return beta.ppf(0.95, a, b)       # the statistic the gate reads

def decision(errors, n):
    return "flip" if upper95(errors, n) <= GATE else "hold"

Every figure below is checkable by hand, because Beta(1, k) has CDF F(x) = 1 - (1 - x)^k, so upper95 = 1 - 0.05^(1/k).

errors / nposteriormeanupper95prior weight 2/(2+n)decision
0 / 0Beta(1, 1)0.5000.9500 (F(x) = x)1.0000hold
0 / 2Beta(1, 3)0.25001 - 0.05^(1/3) = 0.63160.5000hold
0 / 100Beta(1, 101)0.00981 - 0.05^(1/101) = 0.029220.0196hold
0 / 147Beta(1, 148)0.006711 - 0.05^(1/148) = 0.020040.0134hold
0 / 148Beta(1, 149)0.006671 - 0.05^(1/149) = 0.019900.0133flip

The operative line the section carries: the gate cannot flip before 148 error-free exposures, because 0.02004 is the last value above 0.02 and 0.01990 the first below it.

Failure modes, each with its detection.

Prior domination. At 2 exposures the section's own numbers are 0.2500 and 0.6316, and the prior is half the estimate. Detect: log w = 2/(2 + n) for every bucket feeding a decision and alert when w > 0.1, which is n < 18.

Non-exchangeable trials. One beta assumes a single rate across the window. Split the window in half, recompute both halves, and compare their 95% upper bounds; a disjoint pair means the assumption is broken, and the fix is per-cohort counts or a hierarchical model, not a wider prior. The update is O(1) per half, so running the split per reporting window is free.

Wrong statistic in the gate. If the gate reads the mean instead of upper95 it is about 3x more permissive at n = 148, 0.00667 against 0.01990. Detect: store counts per decision and replay the last ten against the logged outcome; a mismatch means the statistic moved without the threshold moving with it.

Denominator drift. n counts exposures, not sessions and not requests. Detect: the sum of errors + successes across buckets must equal the service's request count for the window, and any gap is a bug in the plumbing rather than in the model.

Alternatives, and when beta is the wrong tool. Laplace smoothing, (errors + 1)/(n + 2), is exactly the Beta(1, 1) posterior mean: no scipy, and sufficient when the procedure only ranks buckets and never needs an interval. The Wilson score interval needs no prior and covers small n better than the raw ratio; use it where the organisation will not accept a prior, and record "interval: Wilson" in place of the prior. Empirical Bayes, fitting A0 + B0 from history, adapts to current traffic but is not reproducible window to window, which disqualifies it from a procedure. Beyond that, beta is wrong for a non-binary outcome (Dirichlet for three or more exclusive outcomes), for varying exposure per unit (Poisson-Gamma for events per user-hour), and for any decision taken on total volume rather than a rate.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

How should on-call treat an alert that names the chi-squared and t distributions as the cause?

Answer

Treat the distribution name as the detector's tool, not the cause. An alert reading "chi-squared p < 0.001" or "t-test failed" is telling you which statistic crossed its threshold: a goodness-of-fit test over categorical counts, or a t-test over a mean whose variance was estimated from the sample. The cause is whatever moved those counts or means. Your first decision is whether the test fired because the system changed or because the test's assumptions broke.

Ask three things before touching the service: which test, what n, and which assumption. Chi-squared assumes independent counts and expected counts of roughly 5 or more per cell. The t-test assumes roughly normal data or a large n, and uses t rather than normal critical values because the variance is estimated. A detector that used 1.96 with n=5 will fire on noise.

nt critical, 95% two-sidednormal
52.7761.96
102.2621.96
302.0451.96
1001.9841.96

Worked trace. Five error-code buckets, 1000 requests, expected 200 each, observed 180, 210, 195, 205, 210. Chi-squared = 400/200 + 100/200 + 25/200 + 25/200 + 100/200 = 3.25. With df = 4 the 95% critical value is 9.488, so this does not fire. Halve the sample to 500 requests, expected 100 each, same proportions: the statistic halves to 1.625. The test is less sensitive, not more: a small-n chi-squared alert is usually a detector bug, not an incident.

Alternatives to p-value alerting, and when each wins. A fixed threshold on the metric itself needs no distributional assumption and is trivial to explain, but it misses slow drift and needs a hand-tuned limit. CUSUM or EWMA change detection catches drift at low per-sample cost, at the price of a tuning parameter and a lag. Effect-size gating, require both a significant p and a minimum absolute shift, kills the large-n false positive where a 0.1% change is "significant" but irrelevant. Pick fixed thresholds for SLO-shaped metrics, CUSUM for drift, and p-value tests only when you also gate on effect size.

Failure modes to name. Multiple comparisons: run 20 independent tests at α = 0.05 and P(at least one fires) = 1 − 0.95^20 ≈ 0.64, so a dashboard of tests will page you on nothing. Non-independent counts (sessions, retries, the same client) inflate the chi-squared statistic. And a p-value at n = 10^7 flags a shift far below anything the SLO cares about.

So the on-call action: if the effect size is below the SLO-relevant threshold, downgrade to a ticket and fix the detector's assumptions or add effect-size gating; if the shift is real and material, escalate to the service owner with the counts or means that moved. The distribution told you how the test was built, not what broke.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

How would you explain goodness-of-fit tests at scale without using the usual slogan?

Answer

The 90-second answer. A goodness-of-fit statistic is, up to constants, the sample size times an estimate of how far the empirical distribution sits from the hypothesised one. Under the null that estimate is O(1/√n), so the rejection threshold on the deviation itself shrinks like 1/√n. Any fixed deviation: 0.002 in CDF distance, a 0.1% shift in a bin probability: eventually crosses it. So at scale the p-value answers "is there any deviation", not "does the deviation matter". Report the effect size and compare it to a tolerance the decision sets; use the p-value only to confirm the deviation is real rather than sampling noise.

Why the threshold moves. For a one-sample KS test against a fully specified continuous null, the α=0.05 critical value is 1.358/√n. The exact KS distance between N(0,1) and N(0.005,1) is 2Φ(0.0025)−1 ≈ 0.00199, independent of n.

Python
from scipy.stats import norm
import numpy as np

delta = 0.005
D = 2 * norm.cdf(delta / 2) - 1          # exact KS distance N(0,1) vs N(delta,1)
for n in (10_000, 1_000_000):
    crit = 1.358 / np.sqrt(n)            # alpha = 0.05, one-sample KS
    print(n, round(D, 5), round(crit, 5), D > crit)
10000 0.00199 0.01358 False
1000000 0.00199 0.00136 True

Same deviation, opposite verdicts, decided only by n. Chi-square behaves the same way: X² = n·Σ(p̂ᵢ−pᵢ)²/pᵢ grows linearly in n for a fixed relative deviation, while its critical value depends only on the degrees of freedom. The non-centrality parameter is n·δ², so the smallest detectable deviation scales as 1/√n.

Which test. KS measures the sup gap between ECDF and CDF and is distribution-free when the null is fully specified; it is weak in the tails. Anderson–Darling weights by 1/(F(1−F)), so tail deviations dominate: the right choice when the tail is what you care about. Chi-square bins the data, X² = Σ(O−E)²/E with df = bins − 1 − (estimated parameters), and needs expected counts ≥5 per bin; bin choice changes its power. Cramér–von Mises integrates the squared gap and is more sensitive in the bulk. If you estimate parameters from the same sample, standard KS critical values are wrong: use the Lilliefors correction.

Effect sizes to report instead. KS D itself (max vertical gap). Total variation distance, ½Σ|p̂−p| for discrete data. Population Stability Index, Σ(p̂−p)·ln(p̂/p) over bins, with the credit-scoring rule of thumb: <0.1 stable, 0.1–0.25 moderate shift, >0.25 material. Cramér's V for a chi-square table.

Failure modes. Rejecting a model that is fine for the decision: the scale problem above. Accepting a model that is wrong in the tail because KS is blind there; check tail quantiles directly. Using standard KS p-values after estimating parameters. Chi-square with too many bins (expected counts <5, invalid) or too few (no power). Testing 1000 features at α=0.05: ~50 reject by chance. Apply Bonferroni or FDR.

When the verdict is the answer. When the null is a hard requirement rather than an approximation: a PRNG's output must be uniform, and a statistical test suite (NIST SP 800-22) treats any deviation as a defect. There, rejection is the signal, and the effect size is beside the point.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

What would you ask a candidate who recites choosing a summary statistic but cannot apply it?

Answer

The follow-up I'd ask is a dataset with a decision attached, not a definition. Something like:

Here are 100 request latencies: 90 at 20 ms, 5 at 200 ms, 4 at 1000 ms, 1 at 5000 ms. The product owner wants "the average response time" for a status update, and separately the SLO is p99 under 300 ms. What do you report, and what do you tell them?

A candidate with a working model does the arithmetic out loud. Mean = (90×20 + 5×200 + 4×1000 + 1×5000) / 100 = 11,800 / 100 = 118 ms. Median = 20 ms. p95 = 200 ms, p99 = 1000 ms, max 5000 ms. Then they answer the two questions separately: the status update gets the median, 20 ms, because that is what a typical user sees; the SLO fails, because p99 is 1000 ms, not under 300. The mean, 118 ms, is the right number only if the decision is about total capacity: 100 requests consume 11.8 s of server time, and sizing from the median would under-provision by 5.9x.

That is the whole test. The reciter names mean, median and p99 and stops: never computes one, never notices the mean is 5.9x the median, never says which number the SLO is written against.

Second probe, to find where the median breaks: "50 requests at 20 ms, 50 at 500 ms. What's the median?" It is 260 ms, the average of the 50th and 51st values, and no request took 260 ms. The median is a real number only on a unimodal distribution; on a bimodal one it reports a value nobody experienced. The honest answer is "two modes, 20 ms and 500 ms, and the median is meaningless here."

Third probe, when the mean is the right call: "You're sizing a thread pool. Which number?" Mean, because pool occupancy is total work over time, not the typical request. Median is the wrong tool for capacity.

DecisionNumberWhen it is the wrong choice
SLO / tailp99 or p99.9if the SLO is written on the mean, one 5 s request hides
Typical usermedianbimodal or even-count data: reports a value nobody saw
Capacity / costmean × countskewed data: overstates the typical case
Shape changehistogramany single number hides a mode shift

What to listen for: the candidate states the assumption (skewed, long tail), picks the number the decision needs, and says what that number hides. If they cannot compute the mean from the four buckets, that is the gap: reciting the names is not the skill.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-21

How would you brief product on why truncation and censoring delays a ship date?

Answer

The 60-second version

"We can hit the date, but the latency number we'd ship is wrong above 5 s, and above 5 s is where the incidents live. The fix isn't engineering time: it's observation time: we need about three days of traffic to see the events we're currently throwing away. So the choice is ship with a bound we can defend, or move the date by the length of that window. I recommend shipping with the bound."

What's actually happening

Two different things, same effect on the number.

  • Truncation drops observations outside a range. If the pipeline filters requests over 5 s, they don't exist in the dataset.
  • Censoring keeps the row but replaces the value with the limit. A request that took 40 s is recorded as 5 s.

Both make the tail invisible. The difference matters for the fix: censored data can be recovered with survival methods (Kaplan-Meier, or a censored-likelihood fit), truncated data is gone, but for the ship date they're the same problem: the p99 you compute is a floor, not a measurement.

Why that moves a date

The tail is rare by definition, so seeing it is a wall-clock cost you can't buy with more machines.

Hypothetical: the failure we care about is a request over 10 s, and it happens 1 in 50,000. Staging does 2 req/s. To see 10 of them: 500,000 requests ÷ 2/s = 250,000 s ≈ 69 hours ≈ 3 days of continuous traffic. And with a 5 s client timeout, we'd see zero of them: every one is censored to 5 s. Raising the timeout and re-running is the fix; the three days is the wait.

That's the whole ship-date argument: the delay is the observation window, not the code change.

Options

OptionShip dateWhat we can claim
Ship now, cap at 5 son time"p99 ≤ 5 s": true, because we enforce it; tail above 5 s is unmeasured
Ship now, claim p99 = 5 son timefalse: it's a floor, not a measurement
Wait for the window+3 daysreal p99/p99.9 with the timeout raised
Ship behind a flag, measure in prodon timereal numbers in ~3 days, with a kill switch if the tail is bad

Recommendation

If the tail is a correctness issue (safety, money, a contractual SLO) we can't ship a number we can't defend, so take the three days. If it's a capacity or cost issue, ship behind the flag with the conservative cap and measure in production; the flag is the insurance.

What would change my mind: if the tail event rate is higher than 1 in 50,000, the window shrinks and the delay mostly disappears. That's the one number worth measuring before we commit to a date.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-23

How does convolution and aggregate latency interact with rollback, and where do people ignore that?

Answer

Rollback is a request path, not a control-plane button. It traverses several stages: revert the artifact, repair the data the bad version wrote, invalidate caches, verify, and its end-to-end latency is the convolution of those stages' tails, exactly like the forward path. The difference is that the rollback path's stages are heavier-tailed than the forward path's, because they include scans and repairs whose cost scales with production data volume, and because rollback runs during the incident, when every stage is already near its tail.

Mechanism. For independent stages, the composite tail probability is roughly the sum of the stage tail probabilities: five stages each exceeding their p99 1% of the time give 1 - 0.99**5 ≈ 4.9% of requests exceeding the largest stage's p99. The composite p99 is at least the largest stage p99 and, when one stage dominates, close to it plus the medians of the rest. Rollback inherits this, but its stage set differs from the forward path's and is usually not the set anyone measured.

Worked example (hypothetical figures). Forward checkout path: five RPC stages, each p99 = 100 ms, independent. 1 - 0.99**5 ≈ 4.9% of requests hit at least one stage past 100 ms. Rollback path after a bad deploy: (1) rolling restart, p99 30 s; (2) repair scan over rows written by the bad version, p50 30 s, p99 8 min; (3) cache invalidation, p99 2 s; (4) verification read, p99 0.5 s. The repair stage dominates: the rollback's p99 is roughly the repair's p99 plus the medians of the other three, and ~4% of rollbacks have at least one stage past its p99. A 60 s rollback timeout sits above the repair's p50 (30 s) but far below its p99 (8 min), so it kills the tail of repairs mid-scan.

Where people ignore it. First, rollback is excluded from the SLO, so its tail is never measured. Second, rollback is rehearsed on staging-sized data, 10k rows instead of 10M, and a scan's latency scales with rows, so the stage that finishes in 200 ms in staging takes minutes in production; the convolution is computed on the wrong input distribution. Third, rollback is modelled as one atomic step, hiding that its failure probability is the sum of the stages': four stages each failing 1% of the time leave a mixed state ~4% of the time. Fourth, the rollback timeout is copied from the forward path's budget even though the rollback path has more stages.

Trade-offs. A feature-flag rollback is a single control-plane stage, sub-second, no repair, but only if the bad version did not write data the old version cannot read. If it did, the flag flip is not a rollback; you still owe the repair stage, and its tail dominates. A binary rollback reverts to known-good code but pays that repair convolution. A forward-fix keeps the new code and patches it: one deploy stage, no repair, but you are writing and shipping the fix under incident load. The deciding criterion is whether the bad version's writes are incompatible with the old code and whether the damage is still spreading: spreading damage forces rollback plus repair now; static damage makes forward-fix cheaper. Expand/contract migrations avoid the choice by making every schema change backward-compatible, so rollback is a flag flip: at the cost of two deploys and a dual-read window per change.

Failure modes. A rollback killed mid-repair leaves rows in both formats; detect it by counting rows per format version. An orchestrator that retries the repair every 30 s re-scans from the start each time, saturating the database and inflating the forward path's stage tails: the convolution feeds back into itself. And because rollback runs while the incident already has stages at their tails, the composite you measured in steady state is a lower bound, not the number you will get.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

What is the smallest experiment that would change your mind about distributions in capacity planning?

Answer

The 90-second answer

The belief worth testing is "demand is heavy-tailed, so size to a percentile." The smallest experiment that could falsify it is a re-histogram of demand you already record, computed at two sampling resolutions, with the falsification threshold fixed before you look.

Take the per-second request counts already in your metrics store for one representative week. Compute mean, p50, p99, p99.9. Aggregate the same counts into per-minute buckets and compute the same four numbers. No new instrumentation, no load test, one query.

The decision rule: if the p99/p50 ratio at 1-second resolution is much larger than at 1-minute resolution, the tail is a property of your sampling interval, not of demand, and mean-based sizing with modest headroom is defensible. If the ratio is roughly stable across resolutions, the tail is real and percentile sizing earns its cost.

Worked trace (hypothetical numbers)

Per-second window, 604,800 seconds in a week:

statrps
mean1,200
p501,000
p994,800
p99.99,000

p99/p50 = 4.8.

Per-minute window, 10,080 minutes:

statreq/minrps equivalent
mean72,0001,200
p5060,0001,000
p9990,0001,500

p99/p50 = 1.5. The 1-second p99 of 4,800 rps averages to 1,500 rps over a minute. If capacity is added on a 60-second autoscaler window, that 4,800 rps spike is not a capacity event: it is a burst existing headroom absorbs. The heavy tail was real at 1s and gone at 60s.

If the per-minute p99 had come back at 270,000 req/min (4,500 rps), ratio 4.5, the tail survives coarsening and you size to it.

Why this is the smallest decisive experiment

Heavy tails in request counts come from either (a) genuine correlated demand (a retry storm, a batch job, a cache stampede) which persists under aggregation, or (b) independent per-request arrival noise, which averages out as the window grows: over n intervals the sum has mean nμ and variance nσ², so the coefficient of variation falls as 1/√n. Only (a) justifies tail sizing. The two-resolution histogram separates them with data you already have.

When this is not enough

  • If your autoscaler reacts in seconds, the 1-minute view is the wrong resolution; you need the resolution at which capacity actually changes.
  • If a few large tenants dominate, the aggregate hides per-tenant tails; run the same histogram per tenant.
  • Mean-based sizing is not worth abandoning when over-provisioning is cheap relative to a tail event: a batch analytics cluster with no latency SLO, for example.

Failure modes

  • Aggregating away the tail: the autoscaler window is coarser than the burst, so the overload never appears in the metric you size from. Detection: a persistent gap between the 1s p99 and the 60s p99, or p99 of the autoscaler's own reaction lag.
  • Non-stationarity: the ratio is stable in the week you measured and shifts after a launch. Detection: re-run the histogram monthly and alert on p99/p50 ratio drift.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

How would you document validating a distributional assumption so the next owner can operate it?

Answer

What actually gets handed over

The deliverable is a runbook entry plus a scheduled check, not a paragraph in a design doc. The next owner needs four things: the assumption stated in testable form, the test that falsifies it, the threshold that decides action, and the name of who gets paged.

Write the assumption as a falsifiable claim, not a vibe. "Latency is roughly normal" is not operable. "Inter-arrival gaps follow Exponential(λ), λ estimated from a 30-day reference window frozen 2024-03-01, n=200,000" is: it names the family, the parameter, the window, and the sample size. Then record the validation evidence from the day you validated it: the test, the observed statistic, the threshold, the date. That is the baseline the successor compares against.

The check itself

Two-sample KS against the frozen reference window, gating on effect size rather than p-value alone:

Python
from scipy import stats

# reference_window: 200k gaps, frozen at validation time
# current_window: trailing 24h, ~8k gaps
res = stats.ks_2samp(reference_window, current_window)
D, p = res.statistic, res.pvalue

# p alone is useless at n=200k: trivial deviations go significant.
# Gate on effect size; use p only to rule out sampling noise.
if D > 0.05 and p < 1e-3:
    page("payments-latency", f"gap distribution drift D={D:.3f}")

Why both: at n in the hundreds of thousands the KS p-value rejects on deviations far too small to matter operationally. D is the maximum vertical gap between the two empirical CDFs: 0.05 means the two distributions differ by up to 5 percentage points of cumulative probability at the worst point. You calibrate that threshold to where the downstream decision (capacity, timeout, retry budget) actually changes. The p-value guards the small-sample case where D is noisy.

What to record

FieldValue
Assumptioninter-arrival gaps ~ Exponential(λ)
Testtwo-sample KS, reference vs trailing 24h
Reference window30 days, n=200,000, frozen 2024-03-01
ThresholdD > 0.05 and p < 1e-3
Ownerpayments-latency on-call
Actionpage, runbook link, re-fit or widen timeout

Trade-offs

Parametric goodness-of-fit (Anderson-Darling against a fitted exponential) is sharper when you trust the family but breaks if the family is wrong. Two-sample KS makes no family assumption but is less powerful and, as above, p-value-happy at scale. A drift monitor (PSI, KL divergence) is cheaper to run continuously and answers "has it moved" better than "is it still exponential": use it as a leading indicator and keep the KS check as periodic confirmation.

Failure modes

Freezing a reference window and never refreshing it is the one that bites: you test against a baseline that itself drifted, so the check passes while the system is wrong. Detect it by re-validating the reference window on the same schedule and recording when it was last re-fit. Second, alerting on p-value alone at large n pages constantly and gets muted within a week. Third, no recorded threshold, so the successor sees D=0.03 and cannot tell whether to act.

Curated: · Written: · Reviewed:

Difficulty: Medium