How to Design URL Shortener in a System Design Interview:
1. Requirements
Functional:
→ Shorten a long URL into a short code.
→ Redirect a short code back to the original URL.
→ Support optional custom aliases and expiry dates.
Non-functional:
→ Read-heavy: links are created once and clicked many times.
→ Low latency on redirects.
→ High availability and horizontal scalability.
2. API Design
You mainly need two endpoints.
→ POST /shorten: takes long_url, plus optional custom_alias and expiry_date, and returns the short URL.
→ GET /{short_code}: looks up the original URL and returns a 301 redirect.
Handle the error cases too: 404 when the code does not exist, 410 when the link has expired.
3. High-Level Architecture
Since the system is read-heavy, split reads from writes.
→ A URL Generation Service handles writes.
→ A Redirection Service handles reads.
A load balancer routes traffic to each. The redirection path sits behind a Redis cache, so popular links are served from memory. On a cache miss, you read from the database and populate the cache.
4. Database Schema
The access pattern is a simple lookup by short code, so a NoSQL store like DynamoDB fits well and scales to billions of rows.
url_mappings:
→ short_code (primary key)
→ long_url
→ user_id
→ created_at
→ expiry_date
→ click_count
users:
→ user_id (primary key)
→ email, name, password
5. Short Code Generation
Skip random strings, since they cause collisions and force extra database checks.
Use a counter instead.
→ A Redis counter creates a unique number with an atomic INCR.
→ Base62 encoding turns it into a short string like 8ryaqQ.
INCR is atomic, so no two requests ever get the same number. With a 7-character code, you get about 62^7, roughly 3.5 trillion combinations.
What else would you like to add to the design? Let me know in the comments.
♻️ Repost to help others get better at System Design