Sub topic 6
Handling Collisions
A collision happens when two different long URLs get the same short code. This chapter shows when collisions occur, how often, how to detect them safely, and how to recover.
This chapter assumes you know basic HTTP status codes, how a primary key and a unique constraint work in a relational database, and how to read short Python programs. It also assumes you have seen base62 encoding and the three code generation strategies (hash, counter, random) from earlier chapters.
Where collisions come from
Not every strategy collides in the same way.
| Strategy | Can two URLs get the same code? | Why |
|---|---|---|
| Hash of the URL, truncated | Yes | A 256-bit digest is cut down to about 40 bits (62^7), so many inputs share an output. |
| Random code | Yes | Two random draws can land on the same value. |
| Counter, then base62 | No, if the counter is unique | Each number maps to exactly one code. |
| Custom alias chosen by a user | Yes | The user may pick a code that already exists. |
A counter-based design pushes the uniqueness problem elsewhere. A single counter is a bottleneck, and several counters need coordinated ranges, which a later chapter covers. Hash-based and random designs keep servers independent but accept that collisions will happen and must be handled.
How often collisions happen
A 7-character base62 code has N = 62^7 = 3,521,614,606,208 possible values, about 3.5 trillion. When the table already holds n codes, a new random code collides with probability about n / N.
| Rows already stored | Chance a new code collides |
|---|---|
| 1 million | 0.000028% |
| 1 billion | 0.028% |
| 100 billion | 2.8% |
Two things follow.
- At moderate scale, collisions are rare but not impossible. Over millions of inserts they will happen, so the code path must exist and be tested.
- The rate rises as the table fills. At 100 billion rows, about one insert in 35 needs a retry. A fixed code length therefore has a lifetime, and you may need to move to 8 characters (62^8 is about 218 trillion) before retries become common.
The birthday paradox says something different from the per-insert rate. The chance that some pair among n codes collides is about 1 - e^(-n²/2N). It reaches 50% at roughly 1.18 × √N, which is about 2.2 million codes. That is why a design that "never saw a collision in testing" can still be wrong: if you have stored a few million codes, collisions among them are likely. The per-insert rate is the number that drives the cost of retries.
Detecting a collision correctly
The reliable detector is the database's primary key on short_code. When an insert would duplicate a code, the database rejects it, and the application treats that rejection as a collision.
Do not check first and then insert. This sequence is unsafe:
SELECTthe code and find nothing.INSERTthe new row.
Two servers can both run step 1 for the same code before either runs step 2. Both think the code is free, and one overwrites the other or fails unexpectedly. The unique constraint closes this race because the database serializes the two inserts, so exactly one succeeds. Insert and handle the error.
A collision is not always a conflict
With a hash-based generator, shortening the same URL twice produces the same code. The second insert fails on the primary key, but nothing is wrong. The row already maps this code to this URL.
So when an insert fails, read the existing row.
- If
long_urlmatches, return the existing code. This makes creation idempotent for hash-based codes. - If
long_urldiffers, it is a real collision, so try again with a different input.
Whether you want identical URLs to share a code is a product decision. If each user should get their own link, perhaps for separate analytics, include the user ID or a random salt in the hash input.
Retrying with a salt
The attempt argument in short_code_from_url changes the hashed text from url:0 to url:1 and so on, which gives an unrelated code. This program contains the generator, the insert-and-retry loop, and a test with a deliberately short code length so collisions actually occur.
import hashlib
import sqlite3
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 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])
def create_short_url(db, long_url, length=7, max_attempts=5):
"""Return (code, attempts_used). Raise if every attempt collides."""
for attempt in range(max_attempts):
code = short_code_from_url(long_url, attempt, length)
try:
with db:
db.execute(
"INSERT INTO urls (short_code, long_url) VALUES (?, ?)",
(code, long_url),
)
return code, attempt + 1
except sqlite3.IntegrityError:
row = db.execute(
"SELECT long_url FROM urls WHERE short_code = ?", (code,)
).fetchone()
if row is not None and row[0] == long_url:
return code, attempt + 1 # same URL already stored
raise RuntimeError("could not find a free short code")
if __name__ == "__main__":
db = sqlite3.connect(":memory:")
db.execute(
"""CREATE TABLE urls (
short_code VARCHAR(10) PRIMARY KEY,
long_url TEXT NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
expires_at TIMESTAMP NULL
)"""
)
retries = 0
for i in range(2000):
_, used = create_short_url(db, f"https://example.com/page/{i}", length=3)
retries += used - 1
print("inserted 2000 URLs into a 3-character space, retries:", retries)With 3-character codes there are only 238,328 values. The birthday estimate for 2,000 inserts is about 2000² / (2 × 238,328), which is roughly 8 collisions, so you should see a small, nonzero retry count. The hashes are fixed, so the output is the same on every run. Change length=3 to the default 7 and the retry count will almost certainly be 0.
The loop has these properties.
- Bounded.
max_attemptsstops an infinite loop. At a healthy load factor, needing even three attempts is extremely unlikely, since each attempt fails with probability n / N. If the loop exhausts its attempts, the code space is nearly full or something else is wrong, so surface an error and alert. - Unique input per attempt. Retrying with the same input gives the same code, so the salt must change.
- Idempotent for repeat URLs. The
SELECTafter a failure separates "same URL again" from "real collision".
Other ways to reduce or avoid retries
- Longer codes. Going from 7 to 8 characters divides the collision rate by 62. It costs one character in every link.
- A Bloom filter in front of the database. A Bloom filter is a compact structure that can say "definitely not present" or "possibly present". Checking it first can skip some doomed inserts. It does not replace the primary key, because it can give false positives and does not cover concurrent writers.
- A counter or range allocator. If you never want to retry, generate codes from unique IDs. Encoding the ID with base62 makes collisions impossible by construction. The cost is predictable codes, which matters for enumeration, and coordination between servers.
- Random codes with the same insert-and-retry loop. The loop is identical. Only the generator changes, from a salted hash to a random draw.
Edge cases and gotchas
Case-insensitive collation
Base62 uses both a and A as different digits. Some databases, such as MySQL with a default collation, compare strings without regard to case. In that setting aB3 and Ab3 count as duplicates, which shrinks your effective code space far below 62^7 and creates collisions the math did not predict. Declare short_code with a binary or case-sensitive collation. Test this directly by inserting two codes that differ only in case.
Bias when reducing the digest
The generator takes 64 bits of the digest and reduces it with % 62 ** length. For lengths up to 10 the range is much smaller than 2^64, so the bias is negligible. Past length 10, 62^length exceeds 2^64 and the top codes would never be produced. Take more digest bytes if you go beyond 10 characters. The schema's VARCHAR(10) already caps codes at 10.
Custom aliases
When a user asks for a specific alias, a collision is user-visible. Do not retry with a salt, because the user wants that exact string. Return 409 Conflict and let them choose another. The same primary key also protects against a generated code colliding with an existing alias, so the generation loop needs no special case.
Sharded storage
If the table is sharded by short_code, uniqueness is enforced on the shard that owns the code. A retry produces a different code that may belong to a different shard, which is fine. If you shard by something else, such as user ID, a primary key on each shard can no longer guarantee global uniqueness. You would need a global uniqueness mechanism, which is one reason to shard by code.
Deleted and expired links
If expired rows are deleted, their codes become reusable. Someone holding an old link could be redirected to a new, unrelated destination. Either keep expired codes reserved, for example with a tombstone row, or accept reuse only after a long quiet period.
What to monitor
Log the number of attempts per create request, and alert on two signals: the average attempts per insert trending upward, and any request that exhausts max_attempts. The first shows the code space filling up, so you can lengthen codes before users notice. The second shows a bug, a collation problem, or a broken generator.
Exercise
A service has 10 billion rows and uses random 7-character base62 codes. Roughly what fraction of inserts need at least one retry, and why is a check-then-insert approach worse than catching a duplicate-key error?
Show answer
The chance a new code hits an existing one is n / N = 10^10 / 3.52 × 10^12, which is about 0.28%, so roughly 1 insert in 350 needs a retry. Check-then-insert is worse because two servers can both see that a code is free and then both try to insert it. The primary key lets only one insert succeed, so catching the duplicate-key error is the only race-free check.
Exercise
A hash-based generator receives the same URL twice from the same user. The second insert fails with a duplicate-key error. How should the application decide whether this is a collision, and what should it do in each case?
Show answer
Read the existing row for that code and compare long_url. If it equals the submitted URL, it is not a collision: return the existing code. If it differs, it is a real collision: increase the attempt number, generate a new code, and insert again, stopping after a maximum number of attempts.
Exercise
Your database uses a case-insensitive collation on short_code. Why does this create collisions that the 62^7 calculation does not predict?
Show answer
Base62 treats uppercase and lowercase letters as different digits, but a case-insensitive collation treats them as equal. Codes such as aB3 and Ab3 then count as duplicates, so the usable code space is smaller than 62^7 and collisions occur more often. The fix is a binary or case-sensitive collation on the column.