System designworking

How would you design a URL shortener?

Cover id generation, the read path, and what you cache.

Points worth saying

  • Writes are rare compared with redirects. Optimize the read.
  • Generate an unguessable id, or accept a custom slug with a uniqueness check.
  • Cache the mapping at the edge. The database is the source of truth.

A full answer

The write path accepts a long URL, validates the scheme, and stores a mapping from a short id to that URL. I would generate a 64-bit id and encode it in base62 so the public slug is short. A hash of the URL is a poor primary key because collisions and later edits become awkward.

The read path is a redirect. Look up the slug in cache, then in the database, then 302 or 301 to the long URL. Use 302 while you still want to change the target or count clicks. Use 301 only when the mapping is permanent and you accept that browsers will cache it.

Cache aggressively. A popular slug will be requested far more often than it changes. Set a TTL and delete the cache entry on edit. Partition the table by id if volume demands it. The first version is a single table and a cache.

Mention abuse. Reject private network addresses if the service fetches the URL, rate-limit creates, and allow the owner to disable a slug. Click analytics can be a sampled log, not a synchronous write on the redirect path.

Mark your progress

Create a practice profile to mark this question.