Sub topic 6
Handling collisions
This chapter assumes you have read the chapters on base62 encoding and short code generation. You should be comfortable with SQL constraints and basic Python.
What a collision is
A collision happens when two different long URLs map to the same short code. If the service stored both, one code would redirect to the wrong destination. Collisions are a concern mainly for hash-based and random generation. A counter gives each URL a distinct number, so its codes cannot collide.
How likely is a collision?
With 7 base62 characters there are 62^7 = 3,521,614,606,208 possible codes. Suppose the table already holds 1 billion codes. A new random code then hits an existing one with probability about 1,000,000,000 / 3.5 trillion, or 0.03%. That is rare, but at thousands of writes per second it happens every day. The probability grows as the table fills, so the design must handle collisions instead of hoping they don't occur.
Let the database detect them
Do not check whether a code exists and then insert it. Two servers can both see "free" and both insert. Instead, rely on the primary key on short_code. The database rejects a duplicate atomically, whatever the timing.
The strategy is to insert, catch the duplicate error, and retry with a new code. The hash generator takes an attempt number, so each retry produces a different code for the same URL.
A working implementation
This example uses SQLite so you can run it as shown. The table has the same primary key as the production schema.
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: str, max_attempts: int = 5) -> str:
for attempt in range(max_attempts):
code = short_code_from_url(long_url, attempt)
try:
db.execute(
"INSERT INTO urls (short_code, long_url) VALUES (?, ?)",
(code, long_url),
)
db.commit()
return code
except sqlite3.IntegrityError:
row = db.execute(
"SELECT long_url FROM urls WHERE short_code = ?", (code,)
).fetchone()
if row and row[0] == long_url:
return code # same URL was shortened before
raise RuntimeError("could not allocate a short code")
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE urls (short_code TEXT PRIMARY KEY, long_url TEXT NOT NULL)")
print(create_short_url(db, "https://example.com/a/very/long/path"))
print(create_short_url(db, "https://example.com/a/very/long/path"))Both calls print the same code. The second insert fails on the primary key, and the stored URL matches, so the function returns the existing code.
Common errors
- Check-then-insert. A
SELECTfollowed by anINSERThas a race window. Use the constraint instead. - Retrying without changing the input. If the retry hashes the same string, it yields the same code and fails forever. The
attemptvalue must go into the hash. - Treating every duplicate as a collision. A duplicate where the stored URL is identical is not a conflict. Return the existing code.
- No retry limit. Cap the attempts and return an error. Repeated failures usually mean a bug or a nearly full code space.
- Truncating the hash too far. A short code taken from only a few hash bits collides more often than the arithmetic above suggests.
Exercise
A table holds 3.5 billion codes of length 7 out of about 3.5 trillion possible. Roughly what share of first attempts will collide, and what is the expected number of attempts per insert?
Show answer
About 3.5 billion / 3.5 trillion = 0.1% of first attempts collide. The expected number of attempts is about 1 / (1 - 0.001), which is roughly 1.001, so retries add almost no cost at this fill level.