Case Study 01 β URL Shortener
Design a service like bit.ly: turn long URLs into short links and redirect quickly.
Practice first: Read Β§Β§1β2 only, then run the Thinking Loop for 10β15 minutes before scrolling to estimates/HLD. Self-score with Practice Without Spoilers. Hear a sample narration in First 10 Minutes β Walkthrough A.
1. Problem
Users paste a long URL and receive a short URL. Opening the short URL redirects to the original.
2. Requirements
Functional (MVP)
- Create short URL from long URL
- Redirect short β long
- Optional expiry
- Basic click count
Out of scope (initially)
- Custom domains, A/B experiments, malware scanning UI
Non-functional
- Redirects very fast (cacheable)
- High read:write ratio (redirects >> creates)
- Short codes reasonably unique and hard to guess at scale
- High availability for redirects
3. Back-of-the-envelope estimates
We do rough math so we know what to optimize. Exact precision is not the goal β order of magnitude is.
Why we estimate (beginner tip)
Ask three questions:
- How busy? β QPS (requests per second)
- How much data? β storage (GB/TB)
- How fat is the pipe? β bandwidth (MB/s) when media matters
Cheat sheet: 1 QPS β 86,400 requests/day. Peak is often 2β5Γ average.
Assumptions (say these out loud)
- 100M new short URLs per month (creates / writes)
- Each redirect is a read; people click links far more than they create them
- Read:write ratio β 100:1 (100 redirects for every 1 create)
- Each stored row β 500 bytes (
short_code,long_url, timestamps, indexes) - Redirect responses are tiny (HTTP 302 + headers) β bandwidth is not the bottleneck
Step A β Traffic (QPS)
Seconds per month β 30 days Γ 86,400 β 2.6 million
Write QPS (creates):
100M creates / month Γ· 2.6M seconds β 40/s average
Peak (5Γ avg) β 200/s
Read QPS (redirects):
40 writes/s Γ 100 read:write ratio β 4,000/s average
Peak (5Γ avg) β 20,000/s
Daily sanity check:
100M / month β 3.3M creates/day β 3.3M / 86,400 β 38/s β
3.3M Γ 100 β 330M redirects/day β ~3,800/s average β
Step B β Storage
New rows per year:
100M/month Γ 12 months = 1.2 billion URLs/year
Raw data:
1.2B rows Γ 500 bytes β 600 GB/year (mapping data only)
With indexes (+50β100%):
Plan for ~1 TB/year for URL mappings
Analytics (click events) can grow faster β store separately, not in the hot redirect path
Step C β Bandwidth / other (if relevant)
Redirect responses are ~500 bytesβ1 KB each (302 + Location header). At 20,000 peak redirect QPS:
20,000/s Γ 1 KB β 20 MB/s egress β modest for a load balancer tier
Bandwidth is not the first problem here. Read QPS is.
Step D β Read:write ratio
| Path | Approx share | Implication |
|---|---|---|
| Redirect (GET /r/:code) | ~99% of traffic | Must be fast; cache aggressively (Redis) |
| Create (POST /urls) | ~1% of traffic | Can tolerate slightly higher latency |
| Stats / admin reads | Tiny | Async aggregates OK |
What the numbers tell us
- ~20k peak read QPS β Redis cache for
code β long_urlis essential; DB should not serve every redirect - Only ~200 peak write QPS β a single Postgres primary can handle creates for a long time
- ~600 GBβ1 TB/year β one DB shard is fine initially; shard by
hash(short_code)only when rows hit billions - Click analytics are fire-and-forget β queue + workers so redirects never wait on stats writes
- 100:1 read:write is the classic cache-friendly shape β optimize reads first
Common mistake for this problem
Beginners put click counting inside the redirect path (sync DB write on every click). That turns a 99% read workload into a write-heavy one and kills latency β enqueue clicks asynchronously instead.
4. High-Level Design (HLD)
Components
| Component | Role |
|---|---|
| URL Service | Create codes, redirect |
| Postgres | Source of truth code β url |
| Redis | Hot mapping cache |
| Queue + workers | Async click events |
Flows
Create
- Validate URL
- Generate unique short code
- Insert DB
- Optionally warm cache
- Return short URL
Redirect
- Lookup code in Redis
- On miss, DB β fill cache
- HTTP 302 to long URL
- Enqueue click event (donβt block redirect)
Trade-offs
- 302 (temporary) vs 301 (permanent browser cache) β 302 gives more control/stats
- Random codes vs counter-based β random avoids enumerable guessing; counter needs coordination
5. Low-Level Design (LLD)
APIs
POST /api/v1/urls
Body: { "longUrl": "...", "expiresAt": null }
β { "shortCode": "aZ9kQ2", "shortUrl": "https://short.ly/aZ9kQ2" }
GET /r/:code
β 302 Location: <longUrl>
β 404 if missing/expired
GET /api/v1/urls/:code/stats
β { "clicks": 12345 }
Schema
urls (
short_code VARCHAR(10) PRIMARY KEY,
long_url TEXT NOT NULL,
user_id BIGINT NULL,
created_at TIMESTAMPTZ NOT NULL,
expires_at TIMESTAMPTZ NULL,
is_active BOOLEAN DEFAULT TRUE
)
-- optional aggregated stats
url_stats (
short_code VARCHAR(10) PRIMARY KEY,
click_count BIGINT DEFAULT 0
)
Modules
UrlController
UrlService
ShortCodeGenerator
UrlRepository
UrlCache
ClickEventProducer
Algorithm β short code generation
Base62 alphabet: 0-9a-zA-Z (62 chars).
7 chars β (62^7 β 3.5 \times 10^{12}) possibilities.
function createShortUrl(longUrl):
validate(longUrl)
for attempt in 1..5:
code = base62(randomBits(48)).take(7)
try:
repo.insert(code, longUrl)
cache.set(code, longUrl, ttl=1 day)
return code
catch DuplicateKey:
continue
fail("could not allocate code")
Alternative: distribute ranges of a global counter (or Snowflake IDs) then base62-encode β fewer collisions, more coordination.
Algorithm β redirect
function redirect(code):
longUrl = cache.get(code)
if longUrl is null:
row = repo.findActive(code)
if row is null: return 404
if row.expired: return 410
longUrl = row.longUrl
cache.set(code, longUrl, ttl)
enqueueClick(code, timestamp, userAgentHash)
return 302(longUrl)
Concurrency & correctness
PRIMARY KEY (short_code)prevents duplicates across servers- Cache TTL + delete cache on disable/delete
- Clicks are eventually consistent aggregates
6. Scale evolution
| Stage | Change |
|---|---|
| MVP | Single Postgres + Redis |
| Hot keys | Larger Redis cluster; CDN only if using 301 carefully |
| Huge data | Shard urls by hash(short_code) |
| Global | Regional caches; replicate mappings |
7. Recap
- Redirect path is sacred β cache aggressively
- DB unique constraint is the source of code uniqueness
- Analytics async so redirects stay fast
Practice: redraw HLD from memory, then implement create + redirect pseudocode without looking.