AI Hints
Home›System Design Tutorial›Case Study: URL Shortener
System Design · Lesson 93 of 120

URL Shortener: Short Codes

Base 62.

⏱ 2 min read▶ Video at 1:52:25🎓 Free
Watch this lesson in the System Design courseWatch on YouTube ↗Full System Design course

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.

URL Shortener: Short Codes
From the video: URL Shortener: Short Codes
  • 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.

codespace.pypython
for length in [5, 6, 7]:
    print(f"{length} chars: {62 ** length:,} codes")
Output
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.

base62.pypython
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)))
Output
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
Next up: URL Shortener: The Design — putting it together