Sub topic 4
Base62 encoding and decoding
A URL shortener has to turn something it can count or compute, such as a database ID or a hash, into a short string that is safe in a URL path. Base62 is the usual choice. This chapter explains how it works, implements it, and covers the edge cases that cause bugs in production.
This chapter assumes you can read simple Python and know what a number base is. Later chapters cover how the numbers are produced (counters, hashes, random values) and what happens when two codes collide. Here, the input is just a non-negative integer.
Why base62
Base62 writes a number using 62 symbols: the digits 0-9, the uppercase letters A-Z, and the lowercase letters a-z. Decimal uses 10 symbols and hexadecimal uses 16. More symbols per position means fewer positions, so the string is shorter.
Three properties make base62 fit this job:
- URL-safe. Every symbol is a letter or digit, so nothing needs percent-encoding in a path segment. Base64 uses
+and/, which do cause trouble in URLs. Its URL-safe variant swaps in-and_, which are legal but look less clean. - Dense. Each character carries almost 6 bits (log2 of 62 is about 5.95).
- Reversible. Encoding is a one-to-one mapping between integers and strings, so a code can be decoded back to the original number.
The table shows how many codes each length gives you.
| Length | Possible codes (62^length) | Rough size |
|---|---|---|
| 4 | 14,776,336 | 14.8 million |
| 5 | 916,132,832 | 916 million |
| 6 | 56,800,235,584 | 56.8 billion |
| 7 | 3,521,614,606,208 | 3.5 trillion |
| 8 | 218,340,105,584,896 | 218 trillion |
The capacity estimate from the earlier chapter decides which row you need. If the service creates 100 million links per year and keeps them for 10 years, that is 1 billion links, so 6 characters are enough. Seven characters leave room for growth and, as later chapters show, for sparse random codes.
How the conversion works
Encoding is repeated division. Divide the number by 62, keep the remainder as the next symbol, and continue with the quotient until it reaches zero. The remainders come out from least significant to most significant, so you reverse them at the end.
For example, encode 125. Since 125 = 2 × 62 + 1, the first remainder is 1 and the quotient is 2. Then 2 = 0 × 62 + 2, so the second remainder is 2. Reversed, the digits are 2 and 1, so the code is 21.
Decoding goes the other way. Read the string left to right. For each symbol, multiply the running total by 62 and add the symbol's value. This is Horner's method, the same way you read "345" as ((3 × 10) + 4) × 10 + 5.
A reference implementation
This is the implementation from the topic plan. The alphabet's order defines the mapping, so it is part of your data format.
ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
def encode(n: int) -> str:
if n == 0:
return ALPHABET[0]
digits = []
while n > 0:
n, r = divmod(n, 62)
digits.append(ALPHABET[r])
return "".join(reversed(digits))
def decode(s: str) -> int:
n = 0
for ch in s:
n = n * 62 + ALPHABET.index(ch)
return nCheck it with a few values you can verify by hand:
assert encode(0) == "0"
assert encode(61) == "z"
assert encode(62) == "10"
assert encode(125) == "21"
assert encode(1_000_000) == "4C92"
assert decode("4C92") == 1_000_000
assert decode(encode(3_521_614_606_207)) == 3_521_614_606_207The last line is the largest value that fits in seven characters (62^7 − 1), and it encodes to zzzzzzz.
Problems in the reference version
The reference version works for trusted input, but a redirect service decodes strings that come from the public internet. Three problems matter.
- Invalid characters.
ALPHABET.index("-")raisesValueError. If that exception escapes your handler, an attacker who requests/-gets a 500 error instead of a 404. - Negative numbers.
encode(-5)returns an empty string, because the loop never runs. An empty code is a bug waiting to happen. - Speed.
str.indexscans the alphabet, so each decode step costs up to 62 comparisons. A dictionary lookup is constant time.
Here is a hardened version that also supports fixed-width codes.
ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
BASE = len(ALPHABET)
VALUE_OF = {ch: i for i, ch in enumerate(ALPHABET)}
def encode(n: int, width: int = 1) -> str:
if n < 0:
raise ValueError("n must be non-negative")
digits = []
while n > 0:
n, r = divmod(n, BASE)
digits.append(ALPHABET[r])
code = "".join(reversed(digits)) or ALPHABET[0]
return code.rjust(width, ALPHABET[0])
def decode(s: str) -> int:
if not s:
raise ValueError("empty code")
n = 0
for ch in s:
if ch not in VALUE_OF:
raise ValueError(f"invalid character: {ch!r}")
n = n * BASE + VALUE_OF[ch]
return n
if __name__ == "__main__":
print(encode(125)) # 21
print(encode(125, width=7)) # 0000021
print(decode("0000021")) # 125
try:
decode("ab-c")
except ValueError as e:
print(e) # invalid character: '-'The width parameter pads with the zero symbol 0. Leading zeros do not change the value, so 0000021 and 21 decode to the same number. That makes padding safe for display, and it is how the hash-based generator in the next chapter produces codes of exactly seven characters.
Edge cases and gotchas
Padding creates two spellings of one value
Because 21 and 0000021 decode to the same integer, one link can have two valid URLs. This usually does no harm, but it matters if you key a cache or database on the string. Pick one canonical form. A good rule is to always store and look up the exact string the service issued, and never re-encode a decoded value on the read path.
Case sensitivity
Base62 uses both a and A, and they are different symbols. Anything in your stack that ignores case will merge distinct codes:
- A MySQL column with a default case-insensitive collation treats
aBandAbas equal. Withshort_codeas the primary key, the second insert fails as a "duplicate" even though the codes differ, and lookups can return the wrong row. Use a binary or case-sensitive collation for the code column. - If you read codes aloud or print them,
0/Oand1/l/Ilook alike. Base58 drops these characters, at the cost of density. Decide up front whether humans will ever type the code.
Alphabet order is a contract
If you shuffle the alphabet, every existing short link decodes to a different number. Treat the alphabet as a versioned constant. Some services deliberately shuffle it once, at launch, so that sequential IDs do not produce visibly sequential codes. That only hides the pattern. It is obfuscation, not security, because anyone who samples a few codes can recover the mapping. The abuse chapter covers enumeration properly.
Big integers in other languages
Python integers have no size limit. JavaScript numbers are 64-bit floats and are exact only up to 2^53 − 1 (about 9 × 10^15). Seven-character codes are far below that. A 64-bit ID is not, so use BigInt there. Java's long holds up to 2^63 − 1, which needs 11 base62 characters.
Modulo reduction from hashes
The topic plan's hash-based generator reduces a 64-bit value with % 62**7. Because 2^64 is not a multiple of 62^7, small codes are very slightly more likely than large ones. The bias is about one part in five million, which is negligible here. It would matter if you reduced to a much smaller range.
Base62 is not encryption
Encoding a counter does not hide it. decode("4C92") recovers 1,000,000 instantly. If your codes come from a sequential database ID, a visitor can estimate how many links you have and walk through neighbouring codes. If that matters, generate codes some other way, or map IDs through a keyed permutation before encoding.
Choosing a code length
You can compute the length needed for a given maximum ID with logarithms, or just encode it and measure:
def length_for(max_id: int) -> int:
return len(encode(max_id))
print(length_for(10**9)) # 6
print(length_for(10**12)) # 7
print(length_for(10**15)) # 9A counter produces short codes at first (ID 1 gives 1), so lengths grow as the service grows. If you want every code to look the same, pad to a fixed width such as 7. The choice matters for the next chapter: a counter fills the code space from the bottom, while hashes and random values fill it everywhere, which affects how soon collisions appear.
Summary of decisions
- Use the 62-symbol alphabet in a fixed, documented order.
- Reject negative numbers and unknown characters explicitly.
- Choose between variable-length and fixed-width codes, and keep one canonical spelling.
- Store codes with a case-sensitive collation.
- Do not rely on encoding to hide sequential IDs.
Exercise
A service issues codes by encoding database IDs with the hardened encode (no padding). A user requests /0000021, which the service never issued. The handler decodes the string to 21 and finds a row, so it redirects. Give one reason this is a problem and one fix.
Show answer
Padding makes 0000021 and 21 decode to the same ID, so one link now has several valid URLs. This can split cache entries and analytics counts, and it lets people probe the service with variants of a code. Fixes: look up the exact string in the short_code column instead of decoding it, or reject any code whose re-encoded form differs from the requested string (encode(decode(s)) != s).
Exercise
Compute encode(3844) by hand, then say how many characters a code needs to cover IDs up to 100 billion (10^11).
Show answer
3844 = 62^2, so the repeated division gives remainders 0, 0, then 1, and the code is 100. For 10^11: 62^6 is about 5.68 × 10^10, which is too small, and 62^7 is about 3.52 × 10^12, which is enough. So 7 characters are needed.