Short codes and the birthday bound
Design short, hard-to-guess share codes step by step: what each base62 character buys, why counters fail, how the birthday bound and the per-insert collision rate differ, how long a code must be against a stated guessing attack, and how a case-insensitive column quietly shrinks the space.
Contentsand lesson path
On this page
- The problem
- Step 1: What each character buys
- Step 2: Why not encode a counter?
- Step 3: Random codes and the birthday bound
- Step 4: Insert with a uniqueness check and retry
- Step 5: Size the code for guessing, not only for collisions
- Step 6: Store the codes case-sensitively
- Check your understanding
- Apply it
- Review prompt
Lessons of Unique ID Generation
- What an ID must be: unique, sortable, compact, opaque Concept · 15 min
- Sequences, ticket servers and UUID versions Concept · 20 min
- Building a Snowflake-style generator Lab · 30 min
- Short codes and the birthday bound Worked example · 20 min
- ID scheme check Knowledge check · 6 questions
What you will learn
- Design short, non-guessable public identifiers (for example base62 codes) and calculate their collision probability.
01. The problem
A notes app adds "share a read-only link": https://notes.example/s/<code>. Anyone who has the link can read the note, so the code works like a key. The requirements are:
- Unique: two notes must never share a code.
- Short: at most about 16 characters, so the link fits in a chat message.
- Hard to guess: someone who tries codes at random should find essentially nothing.
- No central counter: any app server can create a link.
Assume up to 50 million links over five years, with 10 million as a low estimate and 200 million as a high one. This lesson works through the design and runs every number. A URL shortener faces the same maths with different priorities; that case study is in URL shortener design. You need Python 3.10 or newer; everything uses the standard library. Save base62.py and birthday.py from the steps below in one folder and run the commands there.
02. Step 1: What each character buys
Base62 writes numbers with 62 symbols: the digits, the uppercase letters and the lowercase letters. All 62 are safe in a URL path without escaping. Each character multiplies the number of possible codes by 62, which is about 5.95 bits. base62.py encodes counters and draws random codes; random_code uses secrets.SystemRandom, the operating system's secure random source, and choice picks each character with equal probability.
"""Base62 codes from a counter or from a CSPRNG (standard library only)."""
import secrets
import string
ALPHABET = string.digits + string.ascii_uppercase + string.ascii_lowercase # 62
_csprng = secrets.SystemRandom() # reads the operating system's secure source
def encode(n: int) -> str:
"""The base62 digits of a non-negative integer, most significant first."""
digits = []
while True:
n, r = divmod(n, 62)
digits.append(ALPHABET[r])
if n == 0:
return "".join(reversed(digits))
def decode(code: str) -> int:
n = 0
for ch in code:
n = n * 62 + ALPHABET.index(ch)
return n
def random_code(length: int, rng=_csprng) -> str:
"""Each character uniform over the alphabet (choice() has no modulo bias)."""
return "".join(rng.choice(ALPHABET) for _ in range(length))python3 - <<'EOF'
import math
from base62 import ALPHABET
print(ALPHABET)
for length in (6, 8, 10, 12):
space = len(ALPHABET) ** length
print(f"{length:>2} characters: {space:9.2e} codes = {math.log2(space):4.1f} bits")
EOF0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
6 characters: 5.68e+10 codes = 35.7 bits
8 characters: 2.18e+14 codes = 47.6 bits
10 characters: 8.39e+17 codes = 59.5 bits
12 characters: 3.23e+21 codes = 71.5 bits03. Step 2: Why not encode a counter?
The shortest codes come from a counter: link number 48,213,000 becomes five characters and can never collide. But look at what happens next:
python3 - <<'EOF'
from base62 import decode, encode
for n in range(48_213_000, 48_213_004): # four links created one after another
print(n, encode(n))
print("someone else's link:", encode(48_213_000 - 1))
print("links made so far, read off code 3GIP5:", f"{decode('3GIP5'):,}")
EOF48213000 3GIP2
48213001 3GIP3
48213002 3GIP4
48213003 3GIP5
someone else's link: 3GIP1
links made so far, read off code 3GIP5: 48,213,003Consecutive links get consecutive codes, so anyone who receives one link can try its neighbours, and decoding a code reveals how many links exist. The counter also breaks requirement 4. You could pass the counter through a secret permutation, a keyed shuffle of the whole code space, so that codes stop looking consecutive. That hides the order but not the density: if 50 million of the 916 million five-character codes are live, about one random guess in eighteen still finds a note. Resistance to guessing needs a space far larger than the number of live codes, whatever produces them.
04. Step 3: Random codes and the birthday bound
With random codes, collisions become a matter of probability. Let N be the number of possible codes and n the number already issued. Three different numbers answer three different questions:
- The next insert collides with probability n / N. This is your retry rate.
- The expected number of colliding pairs among n codes is n(n − 1) / 2N, because there are n(n − 1) / 2 pairs and each matches with probability 1 / N.
- At least one collision somewhere has probability 1 − (1 − 1/N)(1 − 2/N)…(1 − (n − 1)/N), which is very close to 1 − e^(−n(n − 1) / 2N) while n is far smaller than N. It passes 50% near n ≈ 1.1774 × √N. This is the birthday bound: collisions become likely around the square root of the space, not near the space itself.
"""Collision maths for n random codes drawn uniformly from a space of N values."""
import math
def p_any_collision(n: int, space: int) -> float:
"""P(at least two of the n codes are equal) ~ 1 - exp(-n(n-1) / 2N).
The approximation is very close while n is far smaller than the space.
"""
return -math.expm1(-n * (n - 1) / (2 * space))
def p_exact(n: int, space: int) -> float:
"""The exact 1 - (1 - 1/N)(1 - 2/N)...; a loop of n steps, so small n only."""
return -math.expm1(sum(math.log1p(-k / space) for k in range(n)))
def expected_pairs(n: int, space: int) -> float:
"""Expected number of colliding pairs among n codes."""
return n * (n - 1) / (2 * space)
def p_next_collides(n: int, space: int) -> float:
"""Chance that one more random code equals one of the n already issued."""
return n / spacepython3 - <<'EOF'
from birthday import (expected_pairs, p_any_collision, p_exact,
p_next_collides)
n = 50_000_000 # links issued over five years
print("length P(any collision) colliding pairs P(next insert collides)")
for length in (8, 10, 12):
space = 62**length
print(f"{length:>6} {p_any_collision(n, space):16.3g} "
f"{expected_pairs(n, space):15.3g} {p_next_collides(n, space):23.2g}")
small, k = 62**4, 5_000 # check the approximation where the exact loop is cheap
print(f"62^4 space, {k:,} codes: approx {p_any_collision(k, small):.6f}, "
f"exact {p_exact(k, small):.6f}")
EOFlength P(any collision) colliding pairs P(next insert collides)
8 0.997 5.73 2.3e-07
10 0.00149 0.00149 6e-11
12 3.87e-07 3.87e-07 1.5e-14
62^4 space, 5,000 codes: approx 0.570777, exact 0.570818With 8 characters, a collision somewhere among 50 million codes is almost certain (about six colliding pairs), yet any single insert collides only about 2 times in 10 million. Both are true. The first number says you must enforce uniqueness; the second says that doing so is cheap. The last line checks the approximation against the exact product for a case small enough to loop over. A seeded simulation checks the 50% rule itself: draw three-character codes until one repeats, 2,000 times.
python3 - <<'EOF'
import math
import random
import statistics
rng = random.Random(2026) # a seeded simulation, so you get the same numbers
space = 62**3 # 238,328 three-character codes: small enough to collide quickly
firsts = []
for _ in range(2_000): # 2,000 runs: draw codes until one repeats
seen = set()
while (code := rng.randrange(space)) not in seen:
seen.add(code)
firsts.append(len(seen) + 1)
print(f"median draw of the first repeat: {statistics.median(firsts):6.1f}")
print(f"formula 1.1774 * sqrt(N): {1.1774 * math.sqrt(space):6.1f}")
print(f"mean draw of the first repeat: {statistics.mean(firsts):6.1f}")
print(f"formula sqrt(pi * N / 2): {math.sqrt(math.pi * space / 2):6.1f}")
EOFmedian draw of the first repeat: 571.0
formula 1.1774 * sqrt(N): 574.8
mean draw of the first repeat: 608.7
formula sqrt(pi * N / 2): 611.905. Step 4: Insert with a uniqueness check and retry
The database enforces uniqueness; the application retries with a new code. The demo uses SQLite and deliberately tiny three-character codes so that retries actually happen. It passes a seeded generator only to make the output repeatable; production code keeps the default secrets source.
python3 - <<'EOF'
import random
import sqlite3
from base62 import random_code
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE links (code TEXT PRIMARY KEY, note_id INTEGER NOT NULL)")
demo_rng = random.Random(7) # seeded only so the demo repeats; use the default
def create_link(note_id: int, length: int = 3, attempts: int = 5) -> tuple[str, int]:
for attempt in range(1, attempts + 1):
code = random_code(length, rng=demo_rng)
try:
with db: # one transaction; the primary key rejects a duplicate
db.execute("INSERT INTO links VALUES (?, ?)", (code, note_id))
return code, attempt - 1
except sqlite3.IntegrityError:
continue # taken: draw a new code
raise RuntimeError("no free code after several attempts; use longer codes")
retries = sum(create_link(note_id)[1] for note_id in range(20_000))
print("links:", db.execute("SELECT count(*) FROM links").fetchone()[0])
expected = sum(k / (62**3 - k) for k in range(20_000)) # k codes already taken
print("retries:", retries, "| expected on average:", round(expected))
EOFlinks: 20000
retries: 872 | expected on average: 889Each attempt collided with probability n / N for the n codes already stored, so retries grew as the table filled; the total of 872 sits close to the expected 889. With the 12-character codes chosen below and 50 million links stored, a new link needs a retry about once in 65 trillion attempts. So a retry in production is more likely to mean a broken random source than bad luck: log it, and give up with an error after a few attempts.
06. Step 5: Size the code for guessing, not only for collisions
Collisions are now handled, so the length is decided by requirement 3. Each random guess hits a live link with probability n / N, so an attacker who makes G guesses a day finds about G × 365 × n / N notes a year. State the assumptions: 50 million live links, and guess rates from one script (10,000 a day) to a large botnet (100 million a day).
python3 - <<'EOF'
n = 50_000_000 # live links at the end of year five
print("guesses/day length 8 length 10 length 12 (expected hits per year)")
for per_day in (10**4, 10**6, 10**8): # one script, a small botnet, a large botnet
hits = [per_day * 365 * n / 62**length for length in (8, 10, 12)]
print(f"{per_day:>11.0e}" + "".join(f"{h:12.2g}" for h in hits))
EOFguesses/day length 8 length 10 length 12 (expected hits per year)
1e+04 0.84 0.00022 5.7e-08
1e+06 84 0.022 5.7e-06
1e+08 8.4e+03 2.2 0.00057At 8 characters a modest attacker finds dozens of notes a year. At 12 characters (71.5 bits) even the botnet case finds about 0.0006 a year, and the high estimate of 200 million links only multiplies that by four. For comparison, the OWASP Session Management Cheat Sheet asks for at least 64 bits of entropy in session IDs. Rate limiting lowers G, and watching the rate of unknown codes shows a scan in progress. This is not a theoretical risk: in 2016, Georgiev and Shmatikov showed that the 5- and 6-character tokens of URL shorteners could be scanned, exposing OneDrive folders and shared map directions.
Why not just use a UUID? RFC 9562 says implementations should not assume UUIDs are hard to guess and must not use them as security capabilities: a generator is not strictly required to use a secure random source, and any predictability becomes a vulnerability. Draw share codes from secrets yourself. If a link grants write access or exposes very sensitive data, use more bits, such as secrets.token_urlsafe(16) (128 bits in 22 characters), and add expiry and revocation.
07. Step 6: Store the codes case-sensitively
Base62 depends on a and A being different. A column that compares text without regard to case undoes that. SQLite's NOCASE collation shows the effect:
python3 - <<'EOF'
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE links (code TEXT COLLATE NOCASE PRIMARY KEY)")
db.execute("INSERT INTO links VALUES ('aB3xK9pQ')")
try:
db.execute("INSERT INTO links VALUES ('Ab3XK9pq')") # a different base62 code
except sqlite3.IntegrityError as err:
print("rejected:", err)
print("lookup of 'AB3XK9PQ' finds:", db.execute(
"SELECT code FROM links WHERE code = 'AB3XK9PQ'").fetchone())
print(f"8-character space: {62**8:.2e} as designed, {36**8:.2e} case-insensitive")
EOFrejected: UNIQUE constraint failed: links.code
lookup of 'AB3XK9PQ' finds: ('aB3xK9pQ',)
8-character space: 2.18e+14 as designed, 2.82e+12 case-insensitiveThis is not only a SQLite issue: the MySQL manual states that its default collation, utf8mb4_0900_ai_ci, compares strings without regard to case. In such a column, the unique index and every lookup treat the alphabet as 36 symbols, so an 8-character space is 77 times smaller than designed. Give the code column a binary or case-sensitive collation. If people must type codes by hand, use a case-free alphabet instead and add characters to make up the lost bits.
The final design: 12 base62 characters from secrets, a case-sensitive unique column, insert with retry and an alert on any retry, rate limits and monitoring on the share endpoint, and links that the owner can revoke.
08. Check your understanding
09. Apply it
Design the codes for a different product: gift card claim codes that customers type from a printed card. Assume 5 million cards a year for ten years.
- Pick an alphabet without look-alike characters (no 0 and O, 1 and I or l) and without case, and compute the bits per character.
- State an attack model (guesses per day, how many cards are live and unredeemed) and choose a length from it, as in Step 5.
- Use
birthday.pyto report the chance of any collision and the per-insert retry rate at the end of year ten. - Compare your design with a public URL shortener, where codes should be as short as possible: which of the four requirements changes, and why?
10. Review prompt
Without looking back: how many bits does one base62 character carry? Write the formulas for the chance that the next insert collides, the expected number of colliding pairs, and the chance of at least one collision, and say which question each answers. Why does a secret permutation of a counter not make codes hard to guess? What sets the length of a private share code? And what does a case-insensitive column do to a base62 code space?
References
- RFC 9562: Universally Unique IDentifiers (UUIDs), Section 8 (Security Considerations)
- Python documentation: secrets
- OWASP Session Management Cheat Sheet: session ID entropy
- Georgiev and Shmatikov (2016): Gone in Six Characters, Short URLs Considered Harmful for Cloud Services
- MySQL 8.4 Reference Manual: Case Sensitivity in String Searches
- SQLite documentation: Datatypes, collating sequences
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.