The Question
"Design a URL shortening service like bit.ly."
Why They Ask
System design questions test your ability to think about architecture, trade-offs, and scale. A URL shortener is a classic problem that covers hashing, databases, caching, and distributed systems.
Requirements
Functional
- Given a long URL, generate a short URL
- Redirecting a short URL should take the user to the original URL
- Short URLs should expire after a configurable time (optional)
Non-Functional
- Low latency for redirects
- High availability
- Short URLs should be as short as possible
High-Level Design
Client → API Gateway → URL Service → Database
→ Cache (Redis)
Key Components
1. Short URL Generation
Use Base62 encoding (a-z, A-Z, 0-9) on an auto-incrementing ID or a hash:
- 6 characters → 62^6 = ~56 billion unique URLs
- 7 characters → 62^7 = ~3.5 trillion unique URLs
2. Database Schema
CREATE TABLE urls (
id BIGSERIAL PRIMARY KEY,
short_code VARCHAR(7) UNIQUE NOT NULL,
long_url TEXT NOT NULL,
created_at TIMESTAMP DEFAULT NOW(),
expires_at TIMESTAMP
);3. Read Path (Redirect)
- User hits
short.ly/abc123 - Check Redis cache for
abc123 - Cache hit → redirect immediately
- Cache miss → query database, populate cache, redirect
4. Write Path (Shorten)
- Receive long URL
- Generate unique short code (Base62 of ID or MD5 hash truncated)
- Store mapping in database
- Return short URL
Scale Considerations
- Read-heavy workload — Use caching aggressively (Redis)
- Database partitioning — Shard by short code hash
- Rate limiting — Prevent abuse on the write path
- Analytics — Track click counts, referrers, geolocation
Key Takeaway
Start with requirements, sketch the high-level architecture, then dive into each component. Always discuss trade-offs — there's no single "right" answer in system design.