Design a URL shortener (like bit.ly)

Turn long URLs into short links, like bit.ly/x7Kp2a, that redirect to the original.

Why interviewers ask it

It's the classic first HLD question: small enough to finish, and it covers APIs, unique IDs, caching, database choice and read-heavy scaling.

Functional requirements

Non-functional requirements

From version 1 to the final design

  1. Version 1: one server and one database table mapping code → URL, with a counter in the database for IDs.
  2. Version 2: a Redis cache for redirects, so most requests never touch the database.
  3. Version 3: many stateless app servers behind a load balancer, with ID ranges reserved per server so there's no single counter.
  4. Version 4: shard the table by code when it outgrows one database, and send click analytics through a queue.

The design, step by step

  1. Write: the API generates a unique code and stores code → long URL.
  2. Read: GET /{code} → check the Redis cache → on a miss, read the database → redirect.
  3. Code generation: a distributed counter (ID ranges per server) encoded in Base62, or a hash of the URL cut to 7 characters, with collision checks.
  4. Very popular links can also be cached at the edge.

Deep dives

Common mistakes

Not true: 301 redirect: each click still reaches your server, so analytics work.
In fact: Browsers remember a 301 (permanent) redirect, so later clicks never reach your server. Use 302 (temporary) when every click has to be counted.

In the interview

It's a read-heavy key-value lookup. Writes generate a unique 7-character Base62 code from a distributed counter, with ID ranges reserved per server, and store code → URL. Reads go through a Redis cache in front of the database and return a 302, so we can count clicks; click events go onto a queue for background analytics.

Part of Unit 8: High-level design questions in the free System Design course.