Design a URL Shortener
Design a URL shortening service like bit.ly or TinyURL. The system should generate short URLs from long ones and redirect users.
Use Base62 encoding with auto-increment IDs or hash-based approach. Store mappings in a distributed key-value store with caching.
Consider 301 vs 302 redirects for SEO
Think about how to generate unique short codes
Consider expiration and cleanup
functional
- •Shorten long URLs
- •Redirect to original URL
- •Custom short URLs (optional)
- •Analytics (optional)
non functional
- •High availability
- •Low latency redirects
- •Scale to billions of URLs
reads
100:1 read/write ratio = 4000 redirects/second
writes
100M URLs/month = ~40 URLs/second
storage
500 bytes/URL × 100M × 12 months × 5 years = 3TB
api
create
POST /api/shorten { longUrl, customAlias? }
redirect
GET /{shortCode} -> 301/302 redirect
components
- •Load Balancer
- •Application Servers
- •Database (NoSQL)
- •Cache (Redis)
- •Analytics Service
urls table
- •id (PK)
- •short_code (unique index)
- •long_url
- •user_id
- •created_at
- •expires_at
analytics table
- •id
- •short_code
- •timestamp
- •referrer
- •user_agent
- •ip_geo
database choice
Cassandra or DynamoDB for write-heavy, Redis for read-heavy
caching strategy
Cache popular URLs in Redis, use LRU eviction
handling collisions
Check existence before insert, retry with different encoding
approach 1
Base62 encode auto-increment ID (a-z, A-Z, 0-9)
approach 2
MD5/SHA hash and take first 7 chars
approach 3
Pre-generate keys with Key Generation Service