Design a URL Shortener
Design a URL shortening service like bit.ly. Generate short, unique aliases for long URLs, handle redirection, track click analytics, and support custom aliases and expiration dates.
You'll practice
Functional Requirements
- Create a short URL from a long URL
- Optionally support custom alias
- Optionally support an expiration time
- Be redirected to the original URL from the short URL
Non-Functional Requirements
- Low latency on redirects (~200ms)
- Scale to support 100M DAU and 1B redirects
- Ensure uniqueness of short code
- High availability, eventual consistency for URL shortening
Frequently Asked Questions
How do you generate unique short URLs without collisions?
Common approaches include base62-encoding an auto-incrementing counter (guaranteed unique), hashing the long URL with MD5/SHA and taking the first N characters (check for collisions), or pre-generating random codes in batches. Counter-based approaches are simplest and most reliable for avoiding collisions.
How do you handle high-throughput redirects?
The redirect path (short URL → long URL lookup) should be optimized for reads. Use an in-memory cache (Redis) in front of the database, as URL mappings are immutable once created. With proper caching, redirect latency can be sub-10ms even at hundreds of thousands of requests per second.
Should short URLs expire?
It depends on the use case. Supporting optional expiration adds flexibility. Implement it with a TTL field on each URL record. Expired URLs should return 410 Gone (not 404) so clients know the resource existed but was intentionally removed. Consider lazy deletion — check expiry at read time rather than running background cleanup.
How do you track click analytics efficiently?
Log click events asynchronously — don’t block the redirect. Write raw events to a message queue or append-only log, then process them in batches for aggregation. Store aggregated metrics (daily counts by country, device, referrer) separately from raw events. This keeps the redirect path fast while enabling rich analytics.
Ready to design this system?