URL Length and Encoding Constraints
What You'll Learn
You'll learn how to mathematically determine the optimal short URL length and character set to generate enough unique URLs for your system's scale.
The Math Behind Short URLs
When designing a URL shortener, you need enough namespace (unique combinations) to handle billions of URLs without collisions. This comes down to two decisions:
- Character set size: How many distinct characters can you use?
- URL length: How many characters in each short code?
Choosing Your Character Set
Common options:
- Base62:
[a-zA-Z0-9]= 62 characters (alphanumeric, case-sensitive) - Base64: Adds
+and/= 64 characters (URL-unsafe without encoding) - Base58: Removes confusing characters like
0/Oandl/I= 58 characters
Base62 is the sweet spot: URL-safe, readable, maximum combinations.
Calculating Namespace Size
With Base62 encoding:
- 6 characters: 62^6 ≈ 56 billion unique URLs
- 7 characters: 62^7 ≈ 3.5 trillion unique URLs
If you estimated 500 million URLs created over 5 years (from lesson 1497-1498), even 6 characters provides 100x headroom. Most production systems use 7 characters for safety and future growth.
The Length Constraint
Why not use 10 characters? Longer URLs defeat the purpose of "shortening." The goal is brevity while maintaining uniqueness.
Why not use 4 characters? 62^4 = only 14.7 million combinations—you'd exhaust the namespace quickly at scale.
Analogy
Think of it like license plates: California uses 7 characters because more cars keep registering. Too short and you run out; too long and they're unwieldy.
Key Takeaway:
For a URL shortener, 7-character Base62 encoding (a-z, A-Z, 0-9) provides ~3.5 trillion unique URLs—balancing brevity, readability, and massive scale headroom.