Design a URL shortener
45 min · Intermediate
A URL shortener turns a long link such as https://shoplite.in/products/42?ref=fest into a short one such as sl.in/aZ3k9Qx, and sends anyone who opens the short link to the long one. It is the most common first design question because it is small, yet it touches estimates, APIs, ids, databases and caching.
Topics in this lesson
- Requirements and estimates
- API: create a link and redirect with 301 or 302
- Generating short codes: counter or hash
- Data model, cache and the read path
- Extras: custom aliases, expiry and click analytics
Key points
- State requirements and numbers first: 100 reads per write, about 1,157 reads per second, about 1 TB over five years.
- Two calls:
POST /api/v1/urls(201) andGET /{code}with 302 for analytics or 301 for the least load. - Base62 of a shared counter never collides but is guessable; a hash needs a collision check and retry.
- One table keyed by code, an LRU cache for hot links, and clicks counted by a worker reading a queue.
Interview questions this lesson answers
- Why does a URL shortener care so much about reads?
- Would you use 301 or 302 for redirects?
- How do you generate unique short codes when you have ten app servers?
- What if two different URLs hash to the same code?
- Your counter-based codes are guessable. Is that a problem?
- How would you count clicks without slowing the redirect?
- What happens to your design if one link goes viral?
Sign in to continue this lesson
Create an account to read every lesson, practise with the exercises and keep track of your progress.