Sub topic 6
How likely is a collision? The birthday bound
This chapter assumes you know what a UUID v4 is and why random IDs avoid coordination (the previous chapter). You should be comfortable with powers of two, basic probability, and reading short Python. No statistics background is needed beyond that.
Random IDs trade a guarantee for a probability. Nothing stops two nodes from drawing the same value, so you need to know how small that probability is and which assumptions it depends on. The tool for this is the birthday bound.
The birthday problem in one paragraph
In a room of 23 people, the chance that two share a birthday is already above 50%. That feels wrong because we picture comparing one person against everyone else, which is only 22 comparisons. The real count is every pair: 23 × 22 / 2 = 253 pairs, and each pair has a 1/365 chance of matching.
Random IDs behave the same way. If you store n IDs, any two of them can collide, so the number of chances grows with n², not n. The space of possible values (call its size N) must be large compared to n².
The formula
Let N = 2^bits be the number of possible IDs, and n the number of IDs drawn uniformly and independently. The number of pairs is n(n − 1) / 2, and each pair matches with probability 1/N. While the total is small, the union of those events is about the sum:
p ≈ n² / (2N) = n² / (2 · 2^bits)The exact result, using the standard approximation for the "no collision" probability, is:
p = 1 − exp(−n(n − 1) / (2N))The short form is the first-order expansion of this one. It is accurate when p is small, and it overestimates when p approaches 1 (it can even exceed 1, which is impossible for a probability). Treat it as valid only while the result is well below about 0.1.
Three consequences are worth memorizing:
- Adding one bit halves the collision probability.
- Multiplying the number of IDs by 10 multiplies the probability by 100.
- You reach a 50% chance of at least one collision at about n ≈ 1.1774 · √N, which is roughly the square root of the space size.
Computing it
The spine's first example implements the approximation directly:
def collision_probability(n, bits):
# Birthday-bound approximation: p ~ n^2 / (2 * 2^bits), valid while p is small.
return n * n / (2 * 2 ** bits)
# A UUID v4 has 122 random bits.
print(collision_probability(10**9, 122)) # about 9.4e-20A UUID is 128 bits, but 6 are fixed: 4 for the version and 2 for the variant. A v4 UUID therefore has 122 random bits, and that is the number to use for bits.
The next version adds the exact form and an inverse. The inverse answers the more useful question: how many IDs can I generate before the risk crosses a threshold?
import math
def collision_probability(n, bits):
return n * n / (2 * 2 ** bits)
def exact_probability(n, bits):
# expm1 keeps precision when the probability is tiny.
space = 2 ** bits
return -math.expm1(-n * (n - 1) / (2 * space))
def ids_for_probability(p, bits):
# Number of IDs at which the collision probability reaches p.
return math.sqrt(2 * 2 ** bits * -math.log1p(-p))
print(exact_probability(10**9, 122))
print(ids_for_probability(0.5, 122))
print(ids_for_probability(1e-9, 122))
print(ids_for_probability(0.5, 32))The outputs are about 9.4e-20, 2.7e18, 1.0e14, and 7.7e4. The last line is the 32-bit case: with a 32-bit random ID, you reach even odds of a collision after about 77,000 IDs.
expm1 and log1p are used because 1 - math.exp(-x) loses all precision when x is around 1e-20. The naive version would print 0.0.
Reference numbers
The table shows how many IDs it takes to reach a 50% chance, and a one-in-a-billion chance, for several random-bit widths.
| Random bits | Where it appears | IDs at p = 50% | IDs at p = 1e-9 |
|---|---|---|---|
| 32 | A truncated 8-hex-digit ID | about 77,000 | about 3 |
| 64 | A random 64-bit key | about 5.1e9 | about 190,000 |
| 74 | Random part of a UUID v7 | about 1.6e11 | about 6.2e6 |
| 122 | UUID v4 | about 2.7e18 | about 1.0e14 |
Read the last column as a budget. With UUID v4, you can store about 100 trillion IDs in one keyspace before the chance of any collision reaches one in a billion. A 64-bit random key does not have that margin. At a billion rows its collision probability is about 2.7%, which is far too high to ignore.
What n means
The most common mistake is estimating n incorrectly. Three rules help.
- n is the number of IDs that can meet in the same keyspace. For a primary key column, that is every row ever stored in it, including deleted rows if the value could be reused or if the old value stays in logs, caches, or other systems that refer to it. It is not the IDs generated per second.
- Different keyspaces do not collide. If every table has its own primary key, each table's n is counted separately. Two tables can hold the same value safely. A global ID that is shared across all entities puts everything into one n.
- Scope the risk to the failure you care about. A collision in a primary key column usually raises a unique-constraint error, and you can retry. A collision in a place without a constraint (a cache key, a log correlation ID, an object-store name) can silently overwrite or merge data. The second kind deserves a much lower target probability.
Checking the model by simulation
You can test the formula without waiting for 2^61 IDs. Shrink the space to 16 bits, so a collision should appear after about 300 draws, then measure.
import random
def first_collision(bits):
seen = set()
while True:
value = random.getrandbits(bits)
if value in seen:
return len(seen) + 1
seen.add(value)
trials = 2000
mean = sum(first_collision(16) for _ in range(trials)) / trials
print(mean) # close to 321 (sqrt(pi / 2 * 2**16))The expected number of draws before the first collision is about √(π/2 · N), which for N = 65,536 is about 321. The measured mean should land within about ten of that. The 50% point is lower, near 301, because the distribution of "draws until first collision" is skewed.
When the bound does not apply
The formula describes an ideal. It assumes every ID is drawn uniformly and independently from the full space. Real systems break that in several ways, and these failures are far more likely than the bound itself.
- A weak or shared random source. A PRNG seeded from the clock, or a virtual machine image cloned with identical random state, can produce identical sequences on different nodes. A process that forks without reseeding does the same. Use the operating system's cryptographic source:
uuid.uuid4()in Python reads fromos.urandom, andsecretsdoes too. Do not userandomfor IDs. - Truncation. Taking the first 8 characters of a UUID leaves 32 bits, which is the first row of the table. A truncated ID has the collision profile of its remaining bits, not of the original.
- Low-entropy fields. UUID v7 and ULID mix a timestamp with random bits. Only the random part protects against a collision, and only among IDs that share the same timestamp. For v7 that is about 74 random bits per millisecond. If 1,000 IDs fall into one millisecond, p ≈ 1000² / (2 · 2^74) ≈ 2.6e-17 for that millisecond, which is still negligible. The key point is that n is now the count per timestamp tick, not the lifetime count.
- Deterministic schemes. A Snowflake-style ID has no random part, so the birthday bound is not its risk model. It never collides by chance. It collides because two workers were given the same worker ID, or because a clock moved backwards. Those failures have their own chapters.
Design rules that follow
- Pick the bits from the budget. Choose the acceptable risk and the lifetime n, then solve for
bitswith the inverse function. Round up generously, since bits are cheap and a collision is not. - Keep a unique constraint anyway. The bound gives you a probability. A unique index converts the remaining risk into a visible error that a retry can handle. Without it, a collision becomes silent corruption.
- Do not retry blindly forever. If an insert keeps failing on duplicates, the cause is probably a broken random source or a duplicate worker ID, not bad luck. A real collision at 122 bits will essentially never happen twice.
- Compare the cost with other risks. With 122 bits and a billion IDs, p is about 1e-19. Disk errors, software bugs, and operator mistakes are many orders of magnitude more likely. Spending effort to push a 1e-19 risk lower is wasted. Spending it on the random source or on the constraints is not.
Summary
The collision probability of n random IDs in a space of N values is about n² / (2N). It grows with the square of n, so the usable capacity of a random ID is about the square root of its space. UUID v4 has 122 random bits and is safe for any realistic system, while 32-bit and 64-bit random IDs are not. The calculation is only as good as its assumptions: a uniform, independent, properly seeded random source, no truncation, and a correctly counted n. A unique constraint with retry covers what the math cannot.
Exercise
A service generates random 64-bit IDs and expects to store 200 million records in one table. Using the approximation p ≈ n² / (2 · 2^bits), estimate the collision probability. Is it acceptable if the target is one in a billion? What is the smallest number of random bits that meets the target, to the nearest whole bit?
Show answer
n² = 4e16, and 2 · 2^64 ≈ 3.69e19, so p ≈ 1.08e-3, about 0.11%. That is a million times above the target of 1e-9, so it is not acceptable. To meet p ≤ 1e-9 you need 2^bits ≥ n² / (2 · 1e-9) = 4e16 / 2e-9 = 2e25. Since log2(2e25) ≈ 84.0, 85 bits is the smallest whole number that meets it (84 bits gives about 1.0e-9 at best, slightly above the target, so use 85 or more). A UUID v4 with 122 bits meets the target easily.
Exercise
A system uses UUID v7 and its busiest node creates up to 5,000 IDs in a single millisecond. Treat the random part as 74 bits. Estimate the collision probability among IDs created in that millisecond, and explain why the lifetime count of IDs does not enter the calculation.
Show answer
With n = 5,000 and 74 random bits, p ≈ 5000² / (2 · 2^74) = 2.5e7 / 3.78e22 ≈ 6.6e-16 per busy millisecond. The lifetime count does not matter because an ID collides with another only if the 48-bit timestamp prefixes match, and IDs from different milliseconds differ in that prefix. The birthday bound applies separately to each millisecond, with n equal to the number of IDs in that millisecond. Several nodes generating in the same millisecond share that n, so count them together.
Exercise
Why does the code in this chapter use math.expm1 and math.log1p instead of 1 - math.exp(-x) and math.log(1 / (1 - p))?
Show answer
When x or p is extremely small, such as 1e-20, math.exp(-x) rounds to exactly 1.0 in floating point, so 1 - math.exp(-x) returns 0.0 and the real answer is lost. expm1(y) computes exp(y) − 1 accurately for small y, and log1p(y) computes log(1 + y) accurately for small y. They keep the correct tiny result.