System design · Question 47 of 50

Design a URL shortener.

What they're checking

A classic design, end to end.

The answer

Requirements first: shorten a long URL, redirect fast, maybe custom aliases and click counts. Reads far outnumber writes, often 100 to 1. Seven base62 characters give 62⁷, about 3.5 trillion codes. Make them from a unique counter or id encoded in base62 (no collisions; give each server its own range of ids so they do not share one counter), or from a hash of the URL, cut short, with a collision check.

Store code → long URL as a key-value lookup (DynamoDB, Cassandra, or Postgres with an index). Redirect: GET /abc1234 → the cache (Redis) → the database → 301 (browsers cache it: less load, but you lose click counts) or 302 (every click reaches you). Count clicks asynchronously through a queue, and add rate limits and checks for malicious URLs.

The picture

POST /shorten ─▶ id 125 → base62 "cb" ─▶ DB: cb → https://long...
GET /cb ─▶ [ cache ] ─ miss ─▶ [ DB ] ─▶ 302 Location: https://long...
                      └─ click event ─▶ queue ─▶ analytics
The follow-up they'll ask

301 or 302?

Show the answer

301 is cached by browsers, so less load but no click tracking; 302 sends every click through you. Shorteners with analytics mostly use 302.

Your progress stays on this device.