Designbench

Lesson 6.1 · 25 min

URL shortener

Size a shortener from three sliders, generate codes four ways and see the collision math, then cache a Zipf-skewed read path and choose 301 or 302.

The idea in plain words

A URL shortener swaps a long web address for a short code, like a coat-check ticket: hand in the ticket and you get the coat back. The service mostly answers “which link is this code?”, billions of times.

The problem it solves

Long links are awkward to share. A shortener gives each one a short code and redirects anyone who opens it, billions of times, quickly and without ever sending people to the wrong place.

How it works

  1. To create: generate a unique short code and store code → long URL.
  2. To open: look up the code and reply with a redirect to the long URL.
  3. Reads vastly outnumber writes, so cache popular codes in memory.
  4. Generate codes so two links can never get the same one: counters, or random codes inserted only if unused.

Example

7 characters from a–z, A–Z and 0–9 give 62⁷ ≈ 3.5 trillion codes. At 100 million new links a month that lasts thousands of years. With 100 clicks per link, the redirect path handles about 4,000 requests per second, mostly from cache.

Key terms

Short code
The few characters after the domain, such as aZ3k9Qx.
Redirect
The server telling the browser to go to the long URL instead.
301 vs 302
301 means moved permanently (browsers may cache it); 302 means temporary (every click comes back to you).
Base62
Writing numbers with 0–9, a–z and A–Z, so 7 characters give about 3.5 trillion codes.
Collision
Two different links getting the same code.

In this lesson you'll learn

Sections

  1. Requirements and numbers
  2. API and data
  3. Architecture
  4. Short codes
  5. Read path
  6. Design review

Cheat sheet

Code lengthsmallest L with 62^L ≫ links
Unique codesleased counter ranges
Random codesput-if-absent; collide n/N
Hot linksZipf: tiny cache, high hit ratio
302 vs 301analytics/edits vs offload

The interactive simulations and the scored design review load with JavaScript.