URL Shortener · Stage 1 of 3
Base-62 Encoding of Unique IDs
Encode a unique number into a short code with no collision check
Foundations
Base 62 writes a number with 62 symbols: digits, lowercase letters, and uppercase letters. Each symbol carries about 6 bits, so 7 symbols cover 62^7, about 3.5 trillion values. Encoding is repeated division: divide by 62, map the remainder to a symbol, and continue with the quotient until it reaches 0; reading the remainders backward gives the string.
Encoding a number that is already unique produces a string that is unique too, so no lookup is needed to check that it is free. Random strings, by contrast, must be checked against every string already issued, and collisions grow as the space fills. The unique numbers come from an id generator, the next lesson's topic.
Take the id 1000. 1000 = 16 × 62 + 8, so the last symbol is index 8, 8, and the quotient 16 is the first symbol, index 16, g: the string is g8. Two symbols replace four digits, and any id below 62^7 fits in seven symbols.
1000 in base 62
symbol index
place value
16 × 62 + 8 = 1000, and symbols 16 and 8 are g and 8, so 1000 encodes as g8: two symbols instead of four digits.- Open lesson
Requirements
Each worked system starts from a scoped list of verbs and numbers.
- Open lesson
Caching
The read path sits behind cache-aside.
Case Scenario
The design brief
Design Pastebin
Users save a text snippet and receive a link. Anyone with the link can read the text. Snippets expire.
- Input
- n = 11157
- Output
- "2TX"
To see how encoding unique ids gives short, collision-free names, consider Pastebin, a cousin of URL shorteners like bit.ly: a user saves a text snippet and receives a link that anyone can open until it expires. Each paste's unique id is encoded in base 62 as its short code, and the snippet's bytes go to object storage.
A paste link looks like a shortener until the value behind it can be 1 MB and must expire. A create needs a compact unique code, a read must stay fast, and keeping large text beside lookup metadata can make the hottest row unwieldy. The design must generate each code without a collision lookup and keep the 1 MB snippet bytes out of the mapping row.
Pro
The rest of this is on Pro
The idea above is free. The walkthrough, the cost, and the practice are on Pro.