Catalog My learning Blog
System Design Interview Prep: Framework and Questions · Phase 1 · Lesson 5 · 5 min read

Design a URL Shortener: Interview Answer

On this page
  1. The problem: design a URL shortener like bit.ly
  2. URL shortener requirements and capacity estimate
  3. Generating short codes: base62 counter vs hashing
  4. Data model, redirects and 301 vs 302
  5. What a strong URL shortener answer includes
  6. Check yourself

The problem: design a URL shortener like bit.ly

"Design a URL shortener like bit.ly." Try it yourself before reading on: give yourself 30 minutes and go through all five stages.

URL shortener requirements and capacity estimate

Functional: create a short link for a long URL; visiting the short link redirects to the original. Optional: custom aliases, expiry dates.

Non-functional: redirects must be fast, since they sit in every user's click; the system is heavily read-dominated; a short code must never point to two different URLs.

Estimate. Assume 100 million new links a month and 100 reads per write.

Code
Writes   100,000,000 / month ÷ (30 × 100,000 s)  ≈ 35-40 per second
Reads    × 100                                   ≈ 4,000 per second average, far higher when a link goes viral
Storage  100M links × 500 bytes × 12 months      ≈ 600 GB per year
Codes    62^6 ≈ 56 billion, 62^7 ≈ 3.5 trillion

The numbers already tell a story: writes are tiny, reads are large and spiky, and storage is modest. Expect caching to be the main performance lever. They also size the code: at about 1.2 billion links a year, 6 characters last roughly 47 years and 7 characters nearly 3,000, so 7 is a safe length.

Generating short codes: base62 counter vs hashing

This is the core decision. Present two options and choose, rather than picking one silently.

Option A: counter + base62. Keep an increasing integer id and write it in base 62 (a-z, A-Z, 0-9). Id 125 becomes cb. Codes are short, and collisions are impossible by construction. A single global counter would be a bottleneck, so give each API server a block of ids at a time, say 10,000, from a coordination service or database sequence. If a server crashes, the rest of its block is simply skipped.

Option B: hash the URL. Take the first 7 characters of a hash of the long URL. No coordination, but two different URLs can produce the same prefix, so every insert needs a uniqueness check and a retry with a changed input on collision.

Counter + base62Hash prefix
CollisionsNonePossible; detect and retry
CoordinationHand out id blocksNone
Same URL twiceTwo codes (fine, or dedupe by lookup)Same code naturally
Codes guessable?Sequential; shuffle or encrypt the id if that mattersNot sequential

I'd pick the counter for its simplicity and lack of collisions, and mention that sequential codes let anyone enumerate links. If links might be private, run the id through a reversible scramble before encoding.

Data model, redirects and 301 vs 302

One table: code (primary key), long_url, created_at, expires_at, owner_id. No joins. A relational database or a key-value store both work; the access pattern is "look up by code".

Creating a link takes a long URL, validates it, draws an ID from a pre-allocated range and encodes it in base62, so codes never collide, then stores code to URL. Reads check a cache first, since a code never changes and there is nothing to invalidate, and fall back to the database before redirecting.
Creating a link takes a long URL, validates it, draws an ID from a pre-allocated range and encodes it in base62, so codes never collide, then stores code to URL. Reads check a cache first, since a code never changes and there is nothing to invalidate, and fall back to the database before redirecting.

Create: validate the URL, take the next id from the server's block, encode, insert, return the short link. Custom aliases go through the same table with a uniqueness constraint, so a custom alias can never clash with a generated code.

Redirect: look up the code in the cache, fall back to a read replica, then return the redirect. A code never changes once created, so the cache needs no invalidation, the easiest caching case there is. Expired links can be removed by a background job and given a cache TTL no later than their expiry.

Which redirect status? 301 (permanent) lets browsers cache the redirect, which cuts load but hides repeat clicks from your analytics. 302 (temporary) sends every click through you. If click analytics is a feature, choose 302.

Then don't write to the database on every redirect. At 4,000 or more redirects a second, that turns the read path into a write path. Publish a click event to a queue such as Kafka and let a separate consumer aggregate counts in batches. The redirect stays a cache lookup, and a slow analytics store can't slow down anyone's click.

What a strong URL shortener answer includes

  • Estimates that point to caching as the main lever.
  • Two code-generation options compared, with a clear choice.
  • Collision-free creation, including custom aliases.
  • A cache with no invalidation problem, and why.
  • An opinion on 301 versus 302.
  • Click analytics recorded asynchronously, off the redirect path.
  • Abuse: rate-limit link creation (Day 6) and check new URLs against a malware list, because open shorteners get used to hide phishing links.
  • Failure handling: if the cache dies, can replicas absorb 4,000+ reads per second?

Check yourself

A code's target never changes after creation, so cached entries never go stale. There's no invalidation logic, only expiry for links with an end date.

Pre-allocate blocks of ids to each server from a central sequence. Each server hands out ids from its block locally and requests a new block when it runs out.

302 Found. A 301 Moved Permanently lets browsers and proxies cache the redirect, so repeat clicks go straight to the destination without reaching your servers, and you'd undercount. A 302 makes every click come back to you, at the cost of more traffic.

Take counting off the redirect path. Emit a click event to a queue and aggregate in a separate consumer, so a redirect is only a cache read.

Hashing gives the same code for the same URL without coordination between servers. The risk is collisions when you truncate the hash to a short length, so you must detect them and retry with a salt, which adds a lookup on every creation.