Probability for Programmers
Probability you'll actually use — sample spaces and events, conditional probability and independence, Bayes' theorem, random variables, expectation and linearity, variance, key distributions, the birthday problem, randomised algorithms, reservoir sampling, and A/B test intuition.
Probability shows up all over software: hash collisions, load balancing, randomised algorithms (quicksort, skip lists, Bloom filters), retries with jitter, A/B tests, machine learning, and reasoning about failure rates in distributed systems.
Basics
- Sample space Ω: all possible outcomes (two dice: 36 pairs).
- Event: a subset of outcomes ("sum is 7" = 6 outcomes).
- For equally likely outcomes: . So .
| Rule | Formula |
|---|---|
| Complement | |
| Union | |
| Independent events | |
| Conditional |
The complement trick often simplifies "at least one" questions: the probability that at least one of 10 independent servers (each up 99% of the time) is down is . Systems with many components fail more often than any single component.
Conditional probability and independence
is the probability of A given that B happened — we restrict the sample space to B.
Events are independent if knowing one tells you nothing about the other: . Common mistakes:
- Gambler's fallacy: after five heads, tails is not "due" — coin flips are independent.
- Assuming independence that doesn't exist: replicas in the same data centre fail together (shared power, network, bad deploys). Real failure probabilities are higher than naive products suggest — that's why availability zones exist.
Bayes' theorem
It updates a prior belief P(A) into a posterior P(A | B) after observing evidence B.
Example — the base-rate fallacy. A fraud detector catches 99% of fraud and flags 1% of legitimate transactions. Fraud is 0.1% of transactions. A transaction is flagged; how likely is it fraud?
Over 90% of flags are false alarms, because legitimate transactions vastly outnumber fraud. This is why precision matters for rare-event classifiers (Model evaluation). Spam filters (Naive Bayes) apply this theorem word by word.
Random variables and expectation
A random variable assigns a number to each outcome (the sum of two dice, the number of probes in a hash lookup, the running time of randomised quicksort).
The expected value is the probability-weighted average:
A fair die: .
Linearity of expectation
— even when X and Y are dependent. This is the most useful tool in algorithm analysis: break a complicated quantity into a sum of simple indicator variables (1 if an event happens, else 0) whose expectations are just probabilities.
Example — hat check. n people get random hats back. Expected number who get their own hat? Let if person i gets their own hat; . So — regardless of n.
Example — expected collisions. Hash n keys into m buckets uniformly. For each of the pairs, the collision probability is 1/m, so the expected number of colliding pairs is (Hash tables).
Variance
Expectation tells you the average; variance tells you how far you'll typically stray. Two services can have the same mean latency but very different tails — which is why we monitor percentiles (p99), not averages (Monitoring and SRE).
Distributions you'll meet
| Distribution | Models | Mean | Example |
|---|---|---|---|
| Bernoulli(p) | One success/failure | p | One request fails |
| Binomial(n, p) | Successes in n independent trials | np | Failed requests out of 1,000 |
| Geometric(p) | Trials until the first success | 1/p | Retries until success; expected probes in open addressing ≈ 1/(1 − α) |
| Uniform | Every value equally likely | (a+b)/2 | Random jitter in retry backoff |
| Poisson(λ) | Count of rare events in an interval | λ | Requests per second; disk failures per year |
| Exponential(λ) | Time between Poisson events | 1/λ | Time between arrivals (queueing theory) |
| Normal(μ, σ²) | Sums of many small effects (central limit theorem) | μ | Measurement noise; averages of samples |
| Power law / long tail | Few items dominate | — | Popularity of videos, hot keys, file sizes |
Long-tailed latencies and hot keys break "everything is average" assumptions: a fan-out request that waits for 100 backends hits the p99 of at least one of them most of the time () — "the tail at scale".
The birthday problem
With 23 people, the probability that two share a birthday exceeds 50%. In general, with m equally likely values, a collision becomes likely after about samples:
| Values (m) | ~50% collision after |
|---|---|
| 365 birthdays | 23 |
| 2³² (32-bit IDs) | ~77,000 |
| 2⁶⁴ | ~5 billion |
| 2¹²² (random UUIDv4) | ~2.7 × 10¹⁸ |
Consequences: 32-bit random IDs collide quickly; use 64+ bits (UUIDs have 122 random bits); cryptographic hashes need 256 bits for 128-bit collision resistance (Hash functions).
Randomised algorithms
| Type | Guarantee | Examples |
|---|---|---|
| Las Vegas | Always correct; running time is random | Randomised quicksort (expected O(n log n) on any input), treaps, skip lists |
| Monte Carlo | Bounded time; small probability of a wrong answer | Miller–Rabin primality testing, Bloom filters (false positives), HyperLogLog, Karger's min cut |
Randomness defeats adversarial inputs: a fixed pivot choice makes quicksort O(n²) on sorted input; a random pivot makes bad behaviour unlikely for every input (Sorting). Randomised hashing (seeded hash functions) defends against hash-flooding DoS attacks. Probabilistic data structures trade exactness for huge memory savings (Probabilistic structures).
Reservoir sampling
Pick k items uniformly at random from a stream of unknown length, in one pass and O(k) memory:
import random
def reservoir_sample(stream, k):
sample = []
for i, item in enumerate(stream):
if i < k:
sample.append(item)
else:
j = random.randint(0, i) # inclusive
if j < k:
sample[j] = item # item i survives with probability k/(i+1)
return sampleBy induction, after processing n items every item is in the sample with probability k/n.
Shuffling correctly
The Fisher–Yates shuffle produces each of n! permutations with equal probability. The common bug — swapping each element with a random position in the whole array — produces biased results ( equally likely swap sequences can't map evenly onto permutations).
for i in range(len(a) - 1, 0, -1):
j = random.randint(0, i) # only from the unshuffled prefix
a[i], a[j] = a[j], a[i]Statistics for engineers: A/B tests
When comparing a new feature (B) with the control (A):
- Differences in small samples are often noise. A significance test asks how surprising the observed difference would be if there were no real effect (the p-value).
- Decide the sample size before starting, using the minimum effect you care about; don't stop early when results look good ("peeking" inflates false positives).
- Report confidence intervals, not just "significant / not significant".
- Testing many metrics or variants multiplies false positives — correct for multiple comparisons.
- Correlation ≠ causation: randomised experiments are how you establish causation.
- Use the complement for "at least one" questions; failures in many components compound quickly.
- Conditional probability and Bayes' theorem update beliefs; mind base rates for rare events.
- Linearity of expectation holds even for dependent variables — sum indicator variables to analyse algorithms.
- Variance and percentiles describe spread; tails dominate at scale.
- Know the common distributions: Bernoulli, binomial, geometric, Poisson, exponential, normal, power law.
- Birthday bound: collisions appear after about √m samples — size IDs and hashes accordingly.
- Randomised algorithms (Las Vegas, Monte Carlo), reservoir sampling and Fisher–Yates rely on correct probability.