Lesson 26 / 32

Design a URL Shortener

A read-heavy service turning long URLs into short keys.

Requirements

Create a short link for a URL; redirect on visit; links don't change; optional expiry. Assume 100M new links/month and 100:1 read:write.

Key generation

Take a global counter, base62-encode it → 7 chars covers ~3.5 trillion links. Or hash the URL and take the first 7 chars, handling collisions with a retry.

Data & flow

One table, plus a cache in front of the redirect path.

links(key PK, long_url, created_at, expires_at)

GET /{key}:
  cache.get(key) or db.get(key)
  -> 301 redirect to long_url

Output:

Reads served mostly from cache; DB sharded by key

301 vs 302

301 (permanent) lets browsers cache the redirect — fewer hits, but you lose click analytics. Use 302 if you need to count every visit.