Sub topic 2
Generating Short Codes for a URL Shortener
Assume you know basic HTTP, database keys, hashing, and simple Python. The short code must be unique, compact, safe to place in a URL, and fast to look up.
Generating short codes: hash, counter, or random
A counter-based generator assigns the next integer to each URL, then encodes it with Base62. Base62 uses 62 letters and digits, so seven characters represent \(62^7\), about 3.5 trillion, values.
ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
def encode(number: int) -> str:
if number == 0:
return ALPHABET[0]
digits = []
while number:
number, remainder = divmod(number, 62)
digits.append(ALPHABET[remainder])
return "".join(reversed(digits))
print(encode(125))A hash-based generator hashes the long URL and converts part of the digest to Base62. The same URL can produce the same candidate, but truncating the hash creates collision risk.
A random generator chooses characters independently. It hides insertion order, but the service must retry when it generates an existing code. Random generation also needs enough code-space to keep retries rare.
| Strategy | Strength | Main concern |
|---|---|---|
| Counter | Compact and predictable | Reveals order; needs distributed allocation |
| Hash | Repeatable for the same input | Truncation can collide |
| Random | Harder to enumerate | Collisions and randomness quality |
Handling collisions
Treat uniqueness as a database rule, not only an application assumption. Insert the candidate under a unique primary key. If insertion fails, generate another candidate, such as by changing a hash attempt number or drawing a new random value.
Data model and choosing a datastore
A relational database fits well when you need constraints, expiry queries, and administrative tools. A key-value store can scale simple code-to-URL lookups with low latency.
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
);Redirecting: 301 versus 302
Use 301 Moved Permanently when the destination will not change and aggressive browser or proxy caching is acceptable. Use 302 Found when the destination may change, or when you need better control over traffic and analytics. A redirect handler should look up the code, reject expired records, and return 404 for an unknown code.
Exercise
Which generator is usually simplest for one database writer, and what protects it from duplicates?
Show answer
A counter encoded with Base62 is simplest. A unique primary key protects it, while distributed writers need allocated ID ranges or another coordination method.