Ankit KanojiyaIntermediate

Evergreen guide by Ankit Kanojiya · Intermediate · System Design

Design a URL Shortener: A Worked System Design Example

A complete walkthrough of designing a URL shortener: requirements, API, key generation strategies, data model, read scaling, and the real trade-offs, in the structure a system design interview expects.

Designing a URL shortener is a classic exercise because it is small enough to finish yet rich enough to touch key generation, storage, caching, and read scaling. The value is in the structured reasoning, not the product itself.

Clarify requirements

Before drawing anything, pin down scope.

Functional:

  • Given a long URL, return a short one.
  • Visiting the short URL redirects to the original.
  • Optionally support custom aliases and expiration.

Non-functional:

  • Redirects must be fast; this is the hot path.
  • The system is read-heavy. A link is created once and visited many times.
  • Short codes must be unique and hard to guess in bulk.

Estimate scale

Rough numbers guide the design. Assume 100 million new URLs per month and a 100:1 read-to-write ratio.

  • Writes: ~40 per second on average.
  • Reads: ~4,000 per second.
  • Storage over 5 years: 100M * 12 * 5 = 6 billion rows. At ~500 bytes each, roughly 3 TB.

The conclusion that matters: reads dominate by two orders of magnitude, so the design optimizes redirects above all.

Design the API

POST /urls        { "long_url": "https://..." }  -> { "short": "abc123" }
GET  /{short_code}                               -> 301 redirect

Use 301 (permanent) to let browsers and proxies cache the redirect and cut load, or 302 (temporary) if you need every visit to hit your server for analytics. The choice is a real trade-off between load and tracking.

Generate the short code

A code of length 7 over a 62-character alphabet (a-z, A-Z, 0-9) yields 62^7, about 3.5 trillion combinations, far more than enough. The hard part is generating codes that are unique without collisions.

Option 1: hash the URL. Hash with something like MD5 and take the first few characters. Simple, but hashes collide, and the same URL always maps to the same code (which may or may not be desired).

Option 2: counter plus base62. Maintain a global incrementing counter and encode it in base62.

id = 1,000,000
code = base62(id) = "4c92"

This guarantees uniqueness with no collision checks, and codes stay short. The challenge is a distributed counter. A single counter is a bottleneck and a single point of failure. Solve it by handing each application server a range of IDs from a central service (for example 10,000 at a time), so servers mint codes locally and only occasionally coordinate.

Option 3: random codes with a uniqueness check. Generate a random code and insert with a unique constraint; retry on the rare collision. Simple and unguessable, at the cost of an occasional retry.

The counter-plus-ranges approach is a strong default: no collisions, no per-write coordination.

Data model

A key-value shape fits naturally.

CREATE TABLE urls (
  short_code  VARCHAR(10) PRIMARY KEY,
  long_url    TEXT NOT NULL,
  created_at  TIMESTAMPTZ DEFAULT now(),
  expires_at  TIMESTAMPTZ
);

Lookups are by primary key, so this stays fast even at billions of rows, and it shards cleanly on short_code if needed.

Serve redirects fast

The read path is the whole game. A redirect is a single key lookup, and most traffic concentrates on a small set of popular links, which makes caching extremely effective.

GET /abc123
  -> check cache (Redis)
     hit  -> 301 to long_url
     miss -> read DB, populate cache, redirect

With a high cache hit rate, the database handles only a fraction of the 4,000 reads per second. Put a CDN or edge cache in front for globally popular links to cut latency further.

Scale the storage

At billions of rows, one database may not suffice:

  • Read replicas absorb lookups that miss the cache.
  • Sharding by short_code (hash-based) spreads both reads and writes evenly, and since every lookup carries the short code, no query ever needs to span shards.

Because the access pattern is pure key lookup, this workload shards about as cleanly as any.

Handle expiration and edge cases

  • Store expires_at and treat expired links as not found; a background job reclaims old rows.
  • Validate and normalize input URLs to avoid storing junk or redirect loops.
  • Rate-limit creation to deter abuse and bulk scraping of the code space.

Summary of trade-offs

  • 301 caches well but hides analytics; 302 tracks every hit but adds load.
  • Counter-based codes avoid collisions but need distributed ID allocation.
  • Caching plus a key-value model makes the read-heavy path cheap and the system straightforward to scale.

The takeaway is the method: clarify, estimate, let the numbers point at the bottleneck, then design for it.