Sub topic 5
Generating short codes: hash, counter, or random
This chapter assumes you know basic HTTP, can read simple Python, and have seen base62 encoding. It also assumes you have a rough capacity estimate. Seven base62 characters give 62**7, about 3.5 trillion, possible codes. That is far more than most services need.
The generator must produce a unique code for each new long URL. There are three common ways to do it. Each one trades simplicity, predictability, and coordination differently.
The base62 helpers
All three strategies use the same encoder, which turns a number into a short string.
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 nStrategy 1: hash the URL
Hash the long URL, keep part of the digest, and encode it. The same input always gives the same output unless you change it.
import hashlib
def short_code_from_url(url: str, attempt: int = 0, length: int = 7) -> str:
digest = hashlib.sha256(f"{url}:{attempt}".encode()).digest()
n = int.from_bytes(digest[:8], "big") % (62 ** length)
return encode(n).rjust(length, ALPHABET[0])Cutting a digest down to 7 characters means two different URLs can land on the same code. The attempt argument handles this. If the database reports a duplicate, call the function again with attempt + 1 to get a different code. Chapter "Handling collisions" covers the retry loop.
Strategy 2: counter
Keep a global counter. Each new URL takes the next number, and you encode it with encode. Counter 125 becomes 21, and counter 3,521,614,606,207 becomes zzzzzzz.
This never collides, because every number is used once. The cost is coordination. One counter is a single point of failure and a bottleneck. It also makes codes predictable, since anyone can guess that the code after abc123 is the next one. Chapter "Allocating unique IDs across many servers" shows how to split the counter into ranges.
Strategy 3: random
Pick a random number below 62**7 and encode it. Codes are unpredictable and need no shared state. Collisions are possible, so you must check the database. With 1 billion stored codes, the chance that a new random code is already taken is about 1 billion divided by 3.5 trillion, roughly 0.03%. A retry almost always succeeds.
Comparison
| Property | Hash | Counter | Random |
|---|---|---|---|
| Collisions | Possible, retry with `attempt` | None | Possible, retry |
| Predictable codes | No | Yes | No |
| Same URL gives same code | Yes, if `attempt` is 0 | No | No |
| Needs coordination | No | Yes | No |
| Needs a database check | Yes | No | Yes |
Common errors
- Using Python's
hash()for the hash strategy. It changes between runs for strings, so codes would not be stable. Use a fixed hash such as SHA-256. - Skipping the uniqueness check on random codes. A rare collision would silently overwrite a link. Let the primary key on
short_codereject duplicates. - Relying on a hidden counter for private links. Sequential codes let anyone enumerate every link.
- Assuming same URL gives same code is always wanted. Two users shortening one URL may need separate codes for separate analytics.
Exercise
A service stores 3.5 billion links with random 7-character base62 codes. About what fraction of new random codes collide with an existing one, and what should the service do when that happens?
Show answer
The code space is 62**7, about 3.5 trillion, so the fraction is 3.5 billion / 3.5 trillion, about 0.1%. When the database rejects the duplicate primary key, the service generates a new random code and tries again. Retries almost always succeed on the first attempt.