← Math
Math

Collisions and the birthday problem

How long must a random ID be?

Estimate duplicate risk across the whole population of IDs sharing a value space.

Outcome

Count pairs in a uniqueness scope, turn them into expected collisions and a chance, and choose an ID width that meets a budget.

Terminology (6)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Collision
Two different items that get the same ID or hash value within one uniqueness scope.
Birthday problem
The surprise that collisions appear after about √N items, not N, because the number of pairs grows as n²/2.
Uniqueness scope
The set of IDs that are compared with each other, such as one table or one namespace.
Expected matching pairs
Pairs divided by the number of possible values. It can be larger than 1.
Collision budget
The largest chance of any duplicate that a design accepts.
Pigeonhole principle
With more items than possible values, at least two must share a value.

Why this matters

Short random IDs, share codes, cache keys, content hashes and sharding keys all assume that two items rarely get the same value. The chance depends on how many items share one scope and how many values exist, and it rises much sooner than intuition suggests. Sizing the width from the per-item chance leaves IDs far too short.

This lesson assumes the complement rule and expected counts from the previous lesson.

Why a collision is a pair event

A collision occurs when two independently drawn IDs have the same value. The birthday problem asks whether any pair in a population matches. Each new ID adds possible partners, so the number of comparisons grows faster than the number of records.

This model assumes uniform independent draws within one shared ID space. The expected number of matching pairs and the probability of any match are different quantities. The reading derives the exact no-collision probability before introducing an approximation for choosing a width; the approximation retains its own assumptions and error limits.

01Count pairs

Count pairs

A service gives 100,000 records random 32-bit IDs. Four billion possible values for a hundred thousand records sounds safe. The design review needs a chance of any duplicate in the whole table, rather than the risk for one new record.

Any two IDs in the same table could collide. 100,000 IDs form 100,000 × 99,999 / 2 = 4,999,950,000 pairs, and each pair matches with chance 1/2³². Predict the three lines this program prints.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const ids = 100_000;
const values = 2 ** 32; // 32-bit random IDs

const pairs = (ids * (ids - 1)) / 2;

console.log((ids / values).toExponential(3)); // one new ID against 100,000 distinct existing values
console.log((pairs / values).toExponential(3)); // expected matching pairs
console.log((-Math.expm1(-pairs / values)).toExponential(3)); // Poisson estimate of any match
Which line is the expected number of matching pairs?

02From pairs to a chance

From pairs to a chance

Imagine drawing IDs in order from N values. If the first k draws are distinct, the next avoids them with chance 1 − k/N. For n ≤ N the exact no-collision chance is the product (1−0/N)(1−1/N)…(1−(n−1)/N). For n > N a duplicate is certain.

Take logs of that product. When k/N is small, log(1 − k/N) ≈ −k/N; summing gives −n(n − 1)/(2N). Thus the Poisson approximation to any collision is 1 − e^(−pairs/N). Independent draws do not make all pair-match events independent: if A = B and A = C, then B = C. Expected pair counts still add exactly by linearity.

For the record table, 1.164 expected pairs gives an estimated 0.688 chance of any match. The approximation is useful when the draw count is small relative to the value space. A tight real-world budget may require evaluating the exact product or bounding its error; the approximation alone is not a risk guarantee. Expected pairs can exceed 1 while a chance cannot.

At n = √N the expected pairs are about ½ and the chance is 0.39. For 32-bit IDs that is only 65,536 records, which is why √N is the rule of thumb for when collisions become likely.

True product versus Poisson estimate for smaller scopes
Draws and widthTrue chancePoisson estimate
2 IDs, 16 bits0.000015258789060.00001525867265
300 IDs, 16 bits0.49611220.4955854
3,000 IDs, 24 bits0.23520500.2351928

03Tiny chances

Tiny chances

With 1,000 IDs of 64 bits, the expected pairs are 2.7 × 10⁻¹⁴. Computing 1 − exp(−x) rounds exp(−x) to a double just below 1; the subtraction changes even the fourth significant digit here: 2.709 rather than 2.708 × 10⁻¹⁴. expm1 computes e^x − 1 directly, so −expm1(−x) avoids that cancellation. The result remains a binary64 approximation.

crypto.randomUUID() gives a version 4 UUID with 122 random bits. For shorter IDs, fill bytes with crypto.getRandomValues; Math.random is not designed for unpredictable or collision-sensitive IDs.

04Size the width

Size the width

To keep the chance of any duplicate among 10⁸ IDs within 10⁻⁶, add bits until 1 − e^(−pairs / 2^b) ≤ 10⁻⁶. That first happens at 73 bits, with a chance of 5.3 × 10⁻⁷.

Width estimates for 10⁸ IDs and a 10⁻⁶ budget
MethodBits
log₂(n / budget), per-ID thinking47
Add bits until the chance fits73
UUID version 4122
With a 50% budget and 100,000 IDs, log₂(pairs / budget) asks for 34 bits. Why is 33 enough?

05What the model assumes

What the model assumes

06Size the record IDs

Size the record IDs

The record service first needs an expected duplicate count for its table. That count can exceed 1, so the review next asks for the Poisson estimate of any duplicate. Finally, choose the smallest available width that meets the modeled budget, or report that the available widths cannot meet it. Earlier helpers and the complete caller remain visible.

In the frontend Sizing share codes in Next.js and Svelte Optional

Share codes use 32 unambiguous characters, 5 bits each. The component picks the shortest length whose chance of any duplicate among the expected number of codes fits the budget, using the same approximate model. This format supports 4 to 25 characters, or 20 to 125 bits; it reports unavailable if none fits and validates the same bounded count and budget. It selects a length; it does not generate or store codes.

Estimate.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import { useMemo } from "react";

const ALPHABET = "abcdefghijkmnpqrstuvwxyz23456789"; //32symbols,5bits/character

// Supported4..25-character format; Poisson estimate, not exact birthday risk.
function codeLength(expected: number, budget: number): number | null {
  if (
    !Number.isInteger(expected) ||
    expected < 0 ||
    expected > 1e8 ||
    !Number.isFinite(budget) ||
    budget <= 0 ||
    budget >= 1
  )
    return null;

  const pairs = (expected * (expected - 1)) / 2;

  for (let length = 4; length <= 25; length++) {
    if (-Math.expm1(-pairs / 2 ** (5 * length)) <= budget) return length;
  }

  return null;
}

export function ShareCodeLength({
  expected,
  budget
}: {
  expected: number;
  budget: number;
}) {
  const length = useMemo(() => codeLength(expected, budget), [expected, budget]);

  if (length === null)
    return <p>No supported recommendation. Check inputs or widen the format.</p>;

  return (
    <p>
      Modeled budget fits at {length} characters from {ALPHABET.length} symbols (
      {5 * length} bits).
    </p>
  );
}

Check this idea later
10⁹ random version 4 UUIDs: about what is the chance of any duplicate?
Doubling the number of IDs multiplies the expected duplicate pairs by about how much?
Sources

Values above were computed in Node 22 and run in Go 1.27, Rust 1.99 and Apple clang 17. The record service is a worked model.

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.