AlgoViz

Design a URL shortener

medium 45 min

Turn a long URL into a short code and redirect anyone who opens it.

Remember it

The few things worth knowing cold, and how to make them stick.

Memory hook

Write once, read a hundred times: count IDs, scramble them, cache in three tiers, count clicks on the side.

A cloakroom. You hand in a long coat (the URL) and get a small numbered ticket (the code). Attendants each hold their own roll of tickets (ID ranges), so two guests never get the same number. The coats everyone keeps asking for hang by the door (the cache), and someone else tallies visits (analytics) without holding up the queue.

Design a URL shortener in one picture

Cheat sheet

Traffic
1,150 w/s, 115K r/s
Peak (3x)
3,500 w/s, 350K r/s
Code
base62, 7 chars, 3.5T
Storage, 5 years
183 TB, 550 TB with 3 copies
Cache shares
65 / 30 / 5
Average latency
about 24 ms
ID range
1M, refill at 90%
Redirect header
302, s-maxage=60
Clicks
1 TB raw, 100 GB rolled up

Spot it when you see

  • Short codes for long things: links, invites, coupons, file shares.
  • Extremely read-heavy key-value lookups.
  • Unique IDs from many servers.
  • Counting events without slowing the request.

Tricks that stick

  • SACRED: Scope, API, Capacity, aRchitecture, Edge cases, Deep dives.
  • Six is small, seven is heaven: 62^7.
  • 65, 30, 5: edge, Redis, database.
  • 302 comes back to you.

Do not forget

  • private on a response the CDN should cache.
  • Calling sequential codes unguessable.
  • Check-then-insert for aliases.
  • A click counter in the link row.
  • Adding hourly uniques.
  • Reusing expired codes.