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.

Intermediate 6 min readLesson 4 of 9

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: P(E)=∣E∣/∣Ω∣P(E) = \lvert E \rvert / \lvert \Omega \rvert. So P(sum=7)=6/36=1/6P(\text{sum} = 7) = 6/36 = 1/6.
RuleFormula
ComplementP(A‾)=1−P(A)P(\overline{A}) = 1 - P(A)
UnionP(A∪B)=P(A)+P(B)−P(A∩B)P(A \cup B) = P(A) + P(B) - P(A \cap B)
Independent eventsP(A∩B)=P(A) P(B)P(A \cap B) = P(A)\,P(B)
ConditionalP(A∣B)=P(A∩B)/P(B)P(A \mid B) = P(A \cap B) / P(B)

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 1−0.9910≈9.6%1 - 0.99^{10} \approx 9.6\%. Systems with many components fail more often than any single component.

Conditional probability and independence

P(A∣B)P(A \mid B) 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: P(A∣B)=P(A)P(A \mid B) = P(A). 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

P(A∣B)=P(B∣A) P(A)P(B)P(A \mid B) = \frac{P(B \mid A)\,P(A)}{P(B)}

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?

P(fraud∣flag)=0.99×0.0010.99×0.001+0.01×0.999≈9%P(\text{fraud} \mid \text{flag}) = \frac{0.99 \times 0.001}{0.99 \times 0.001 + 0.01 \times 0.999} \approx 9\%

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:

E[X]=∑xx⋅P(X=x)\mathbb{E}[X] = \sum_x x \cdot P(X = x)

A fair die: E=3.5\mathbb{E} = 3.5.

Linearity of expectation

E[X+Y]=E[X]+E[Y]\mathbb{E}[X + Y] = \mathbb{E}[X] + \mathbb{E}[Y]

— 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 Xi=1X_i = 1 if person i gets their own hat; E[Xi]=1/n\mathbb{E}[X_i] = 1/n. So E[∑Xi]=n⋅1/n=1\mathbb{E}[\sum X_i] = n \cdot 1/n = 1 — regardless of n.

Example — expected collisions. Hash n keys into m buckets uniformly. For each of the (n2)\binom{n}{2} pairs, the collision probability is 1/m, so the expected number of colliding pairs is (n2)/m\binom{n}{2}/m (Hash tables).

Variance

Var(X)=E[(X−μ)2]=E[X2]−E[X]2\text{Var}(X) = \mathbb{E}[(X - \mu)^2] = \mathbb{E}[X^2] - \mathbb{E}[X]^2

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

DistributionModelsMeanExample
Bernoulli(p)One success/failurepOne request fails
Binomial(n, p)Successes in n independent trialsnpFailed requests out of 1,000
Geometric(p)Trials until the first success1/pRetries until success; expected probes in open addressing ≈ 1/(1 − α)
UniformEvery value equally likely(a+b)/2Random jitter in retry backoff
Poisson(λ)Count of rare events in an intervalλRequests per second; disk failures per year
Exponential(λ)Time between Poisson events1/λTime between arrivals (queueing theory)
Normal(μ, σ²)Sums of many small effects (central limit theorem)μMeasurement noise; averages of samples
Power law / long tailFew 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 (1−0.99100≈63%1 - 0.99^{100} \approx 63\%) — "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 m\sqrt{m} samples:

P(no collision among n)≈e−n2/(2m)P(\text{no collision among } n) \approx e^{-n^2 / (2m)}
Values (m)~50% collision after
365 birthdays23
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

TypeGuaranteeExamples
Las VegasAlways correct; running time is randomRandomised quicksort (expected O(n log n) on any input), treaps, skip lists
Monte CarloBounded time; small probability of a wrong answerMiller–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:

Python
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 sample

By 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 (nnn^n equally likely swap sequences can't map evenly onto n!n! permutations).

Python
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.
Key takeaways
  • 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.