Sub topic 5
Generating short codes: hash, counter, or random
This chapter compares three ways to produce the short code in a URL shortener. It assumes you know basic HTTP, have used a relational or key-value database, understand hashing and number bases at a high level, and can read simple Python. The earlier chapters on capacity estimation and base62 encoding supply two inputs. The estimate says how many codes you need, and base62 turns numbers into compact strings.
What the generator must do
A short code is the path segment in https://sho.rt/Ab3dE9x. The generator has to meet four requirements:
- Unique: two different long URLs must never share a code.
- Short: seven characters is the usual target.
- Fast: creation is the rare path, but it should not need a slow global lock.
- Hard to guess: if links are meant to be private-ish, codes should not be enumerable.
No strategy wins on all four. The choice depends on which one your product cares about most.
The code space
Base62 uses 0-9, A-Z and a-z. The table shows how length determines how many codes exist.
| Length | Possible codes | Approximate size |
|---|---|---|
| 6 | 62^6 | 56.8 billion |
| 7 | 62^7 | 3.5 trillion |
| 8 | 62^8 | 218 trillion |
Suppose the capacity estimate says you create 100 million links per year and keep them for 10 years. That is about 1 billion codes, so 7 characters leaves roughly 0.03% of the space used. Six characters would be too tight for random strategies, as the collision section shows.
Here is the base62 code from the previous chapter. The later examples reuse it.
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 n
assert decode(encode(3_500_000_000)) == 3_500_000_000Strategy 1: hash the URL
Hash the long URL, then reduce the digest to a fixed-length base62 string.
import hashlib
# Uses ALPHABET and encode() from the previous block.
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])
print(short_code_from_url("https://example.com/a/very/long/path"))The code takes the first 8 bytes (64 bits) of SHA-256 and reduces them modulo 62^7. The rjust call pads with 0 so every code has exactly seven characters.
Strengths
- It needs no shared state. Any server can compute the code.
- It is deterministic. The same URL with
attempt=0gives the same code, which gives you free deduplication.
Weaknesses
- Truncation causes collisions. Two different URLs can map to the same 7-character code even though SHA-256 itself has no practical collisions.
- Deduplication is not always wanted. If two users shorten the same URL, they share one code, and you cannot give them separate analytics or separate expiry.
- If you add a per-user salt to avoid sharing, you lose determinism and gain nothing over random codes.
On a collision you increment attempt and hash again. To tell a real collision from a duplicate submission, compare the stored long_url with the incoming one.
Strategy 2: counter plus base62
Keep a monotonically increasing integer ID, which can be a database sequence, and encode it.
| Counter value | Code |
|---|---|
| 1 | `1` |
| 125 | `21` |
| 3,521,614,606,207 | `zzzzzzz` |
Strengths
- Collisions are impossible by construction, because every ID is used once.
- It is the most compact approach. Early codes are short, and the code space fills evenly.
- There is no retry loop.
Weaknesses
- Codes are guessable. Anyone can walk
…/1,…/2,…/3and harvest every link. Treat this as a privacy problem, not a cosmetic one. - A single counter is a bottleneck and a single point of failure. The chapter on allocating IDs across servers covers range allocation, which removes the bottleneck.
- Codes leak volume. A competitor can create two links a week apart and read your growth rate from the difference.
If you want a counter's uniqueness without its predictability, scramble the number before encoding. A reversible scramble maps each integer in [0, 62^7) to a different integer in the same range, so uniqueness survives.
# Uses ALPHABET, encode() and decode() from the earlier block.
M = 62 ** 7
K = 2654435761 # odd and not divisible by 31, so coprime with 62**7
K_INV = pow(K, -1, M) # modular inverse, Python 3.8+
def scrambled_code(counter: int) -> str:
assert 0 <= counter < M
return encode((counter * K) % M).rjust(7, ALPHABET[0])
def counter_from_code(code: str) -> int:
return (decode(code) * K_INV) % M
for i in (1, 2, 3):
c = scrambled_code(i)
print(i, c, counter_from_code(c))Multiplication by a number coprime to M is a bijection (a one-to-one mapping) modulo M, so no two counters collide. This is obfuscation, not encryption. Someone who collects a few pairs can recover K. For stronger protection, use a keyed block cipher or a Feistel network over the counter.
Strategy 3: random codes
Draw seven characters from a cryptographically secure source and let the database arbitrate uniqueness.
import secrets
import sqlite3
ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
def random_code(length: int = 7) -> str:
return "".join(secrets.choice(ALPHABET) for _ in range(length))
def create_short_link(conn, long_url: str, max_attempts: int = 5) -> str:
for _ in range(max_attempts):
code = random_code()
try:
conn.execute(
"INSERT INTO urls (short_code, long_url) VALUES (?, ?)",
(code, long_url),
)
conn.commit()
return code
except sqlite3.IntegrityError:
continue # primary key rejected a duplicate; draw again
raise RuntimeError("could not allocate a unique code")
conn = sqlite3.connect(":memory:")
conn.execute(
"CREATE TABLE urls (short_code VARCHAR(10) PRIMARY KEY, long_url TEXT NOT NULL)"
)
print(create_short_link(conn, "https://example.com/"))Use secrets, not random. The random module is predictable once an attacker sees enough outputs, which defeats the purpose.
Strengths
- Codes are unguessable. With 3.5 trillion possibilities and 1 billion in use, a guess hits a live link about once per 3,500 tries. That is still enumerable at scale without rate limits, so add them.
- Any server can generate a code with no coordination.
Weaknesses
- Collisions occur and need a retry path.
- Every create does a write that may fail, so the database must enforce uniqueness. The primary key on
short_codedoes this.
How often do collisions happen?
When k codes already exist in a space of size N, a new random code collides with probability k / N.
| Codes stored | Space | Collision chance per new code |
|---|---|---|
| 1 million | 62^7 | about 0.00003% |
| 1 billion | 62^7 | about 0.03% |
| 1 billion | 62^6 | about 1.8% |
At 0.03%, one create in about 3,500 needs a second attempt. Five attempts failing in a row is vanishingly rare, so a small retry cap is safe. At 62^6 with 1 billion codes, retries are routine and the space is nearly exhausted for practical purposes. Pick the length from the estimate, then check this table.
Choosing between them
| Criterion | Hash | Counter | Random |
|---|---|---|---|
| Collisions | Possible, retry | None | Possible, retry |
| Coordination between servers | None | Needed | None |
| Guessable | Not easily | Yes, unless scrambled | No |
| Same URL gives same code | Yes | No | No |
| Code length | Fixed | Grows with count | Fixed |
A common production choice is a counter handed out in ranges to each server, scrambled before encoding. Random codes with a unique-key retry are the simplest design that is safe by default, and they suit a service that has not yet outgrown a single database.
Edge cases to handle
- Case sensitivity. Base62 mixes
Aanda. If any layer lowercases paths, such as a proxy, a CDN rule, or a database collation, two codes merge. Use a case-sensitive collation onshort_code. - Offensive strings. Random seven-character codes will occasionally spell words. Filter a blocklist and redraw.
- Ambiguous characters.
0/Oand1/l/Iare hard to read aloud. Dropping them gives a base58 alphabet, at the cost of a smaller space (58^7 is about 2.2 trillion). - Reserved paths. Codes such as
apioradmincollide with routes. Reserve them or keep routes under a separate prefix. Custom aliases make this more pressing. - Modulo bias. Reducing a 64-bit number modulo 62^7 slightly favors low values. The skew is on the order of 10^-7 and is harmless here.
Exercise
A service stores 2 billion codes and uses random 7-character base62 codes. About what fraction of new creates need at least one retry, and does the answer change if codes are 6 characters long?
Show answer
At 7 characters the space is about 3.5 trillion, so the collision chance per attempt is 2 billion / 3.5 trillion, about 0.057%, or roughly 1 create in 1,750. At 6 characters the space is about 56.8 billion, so the chance is about 2 billion / 56.8 billion, roughly 3.5%, or about 1 create in 28. The shorter length makes retries routine and leaves the space about 3.5% used, so growth will keep making it worse.
Exercise
Why does the scrambled counter in this chapter require K to be coprime with 62^7, and what happens if it is not?
Show answer
Multiplication modulo M is a one-to-one mapping only when K and M share no common factor. Since 62^7 has prime factors 2 and 31, K must be odd and not a multiple of 31. If K shares a factor with M, several counters map to the same product, so two links get the same code. There is also no modular inverse, so pow(K, -1, M) raises an error and you cannot recover the counter from a code.