URL Shortener: Short Codes
Base 62.
How short can the codes be? If we use lowercase letters, uppercase letters, and digits, that's sixty two characters. Each extra character multiplies the number of possible codes by sixty two.

- a–z, A–Z, 0–9
- 62 characters
- Each one × 62
How many codes?
Let's count. Run it. Six characters give fifty six billion codes, which is plenty for six billion links. Seven characters give three point five trillion, for lots of growth.
for length in [5, 6, 7]:
print(f"{length} chars: {62 ** length:,} codes")5 chars: 916,132,832 codes 6 chars: 56,800,235,584 codes 7 chars: 3,521,614,606,208 codes
Base 62 encoding
To make a code, we take a unique number, like a snowflake ID, and write it in base sixty two, just as we'd write a number in base ten. Then we shuffle the number first, so codes aren't easy to guess in order. Run it. Neighbouring numbers give completely different short codes.
ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
def base62(n):
out = ""
while n:
n, r = divmod(n, 62)
out = ALPHABET[r] + out
return out or "0"
def scramble(n): # a reversible shuffle of the number
return (n * 0x5DEECE66D + 11) % 62 ** 7
for n in [1000, 1001, 1002]:
print(n, "->", base62(scramble(n)))1000 -> 9Vcbbvt 1001 -> amIClS8 1002 -> aOf3weN
Summary
Base sixty two turns a unique number into a short code. Seven characters give trillions of codes, and scrambling stops guessing. Next, the whole design.
Key takeaways- 62 characters
- 7 chars ≈ 3.5 trillion
- Scramble, then encode