A URL shortener like TinyURL or bit.ly turns https://example.com/some/very/long/path?with=params into https://sho.rt/aZ3kP9q. It looks trivial, but at scale it's a great tour of read-heavy design: unique ID generation, encoding, caching, database choice, redirects and analytics.
Think of it like
A coat check
You hand over a bulky coat (the long URL) and get a small numbered ticket (the short code). Later, anyone holding the ticket gets the coat back instantly. The hard parts: never hand out the same ticket twice, and keep the counter fast when millions of people arrive at once.
1. Requirements
Functional
- Given a long URL, return a unique short URL
- Visiting the short URL redirects to the original
- Optional custom aliases (
sho.rt/my-launch) - Optional expiration time
- Click analytics (counts, referrers, geography)
Non-functional
- Very high availability: broken links are unacceptable
- Low redirect latency (p99 < 50 ms)
- Short codes must not be guessable in sequence
- Read-heavy: about 100 redirects per URL created
2. Back-of-the-envelope estimation
Assume 100 million new URLs per month and a 100:1 read-to-write ratio. Each record (short code, long URL, owner, timestamps) is about 500 bytes. See Back-of-the-Envelope Estimation for the technique.
Writes
~40 /s
100M ÷ (30 × 86,400 s)
Redirects
~4,000 /s
100 × writes, peaks ~20k/s
Storage (5 yrs)
~3 TB
6B URLs × 500 B
Cache
~20 GB
80/20 rule on daily hot URLs
3. API design
# Create a short URL
POST /api/v1/urls
{ "longUrl": "https://example.com/very/long", "customAlias": "launch", "expiresAt": "2027-01-01" }
-> 201 Created { "shortUrl": "https://sho.rt/aZ3kP9q" }
# Redirect
GET /aZ3kP9q
-> 302 Found Location: https://example.com/very/long
# Analytics
GET /api/v1/urls/aZ3kP9q/stats -> { "clicks": 18234, "topCountries": [...] }4. Data model
| Column | Type | Notes |
|---|---|---|
short_code | VARCHAR(10) | Primary key / partition key |
long_url | TEXT | Up to ~2 KB |
user_id | BIGINT | Nullable for anonymous links |
created_at | TIMESTAMP | |
expires_at | TIMESTAMP | Nullable; a TTL index cleans up expired rows |
short_code, so a NoSQL store (DynamoDB, Cassandra) or a sharded relational table both work well.5. High-level architecture
Writes and reads have very different profiles, so we split them into separate stateless services behind a load balancer. Redirects are served from a cache first, and click events are published asynchronously so they never slow down the redirect. Press play on a flow to watch a request travel through the system.
6. Deep dive: generating short codes
This is the heart of the problem. There are three common approaches, each with different trade-offs around collisions, coordination and predictability.
Hash + truncate
base62(md5(longUrl))[0:7]- Same URL always gives the same code (free dedup)
- Collisions are possible, so you must check and re-hash
- Extra DB round trip on every write
Counter + base62
- Global auto-increment ID, encoded in base62
- No collisions by construction
- Sequential codes are guessable
- Counter is a coordination bottleneck (use ranges per server)
Key Generation Service
- Pre-generate random unique codes offline
- Servers fetch batches into memory
- No collisions and no write-path coordination
- Lost batches on crash waste a few keys (acceptable)
Base62 encoding
Base62 converts a numeric ID into a compact string by repeatedly dividing by 62. ID 125 becomes "21" because 125 = 2 × 62 + 1. Combined with a distributed ID generator such as Unique ID Generation (Snowflake), each server can mint codes independently.
7. Scaling and reliability
- Caching: a cache-aside Redis cluster with LRU eviction absorbs most redirects; hot links stay resident. See Caching.
- Database: partition by
short_codehash so reads spread evenly. See Sharding & Partitioning and Consistent Hashing. - Replication: replicate across availability zones; redirects can tolerate slightly stale reads.
- Rate limiting: cap link creation per user/IP to stop spam and abuse. See Rate Limiting.
- Expiry: a background job or database TTL deletes expired links and returns their codes to the pool.
- Abuse: scan new long URLs against malware/phishing lists before activating them.
Implementation
Convert numeric IDs to short codes and back.
ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
def encode(num: int) -> str:
if num == 0:
return ALPHABET[0]
out = []
while num:
num, rem = divmod(num, 62)
out.append(ALPHABET[rem])
return "".join(reversed(out))
def decode(code: str) -> int:
num = 0
for ch in code:
num = num * 62 + ALPHABET.index(ch)
return numKey takeaways
- Start from the 100:1 read/write ratio: it justifies caching, read replicas and a key-value data model.
- Seven base62 characters give 3.5 trillion codes, enough for decades of growth.
- A Key Generation Service (or Snowflake IDs + base62) avoids collisions without coordination on the write path.
- Use 302 redirects if analytics matter; publish click events asynchronously.
Common pitfalls
- Hashing long URLs and ignoring collisions after truncation.
- Exposing sequential codes that let anyone enumerate every link.
- Writing analytics synchronously in the redirect path, adding latency to every click.
- Forgetting expiry and abuse handling (phishing links, spam).
Interview tips
- Clarify scale, custom aliases, expiry and analytics up front.
- Do the estimation out loud: QPS, storage, cache size and code length.
- Offer all three ID strategies, then pick one and defend the trade-off.
Practice problems
Test yourself
Roughly how many unique codes do 7 base62 characters provide?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.