Design a URL Shortener

How to turn long links into short ones, keep redirects fast for 100M daily users, and generate codes that never collide.

Easy8 min read1 diagramStorage · CachingSource Code ↗Aditya Trivedi · updated Nov 23, 2026

Problem statement#

Design a URL shortener like Bitly. Given a long URL, return a short one such as sho.rt/4c92xYz. When anyone visits the short link, redirect them to the original URL.

Creating links is rare. Opening them happens constantly, and that gap between reads and writes drives almost every decision in this design.

Requirements#

Spend the first few minutes asking questions. Each answer changes the data model or the hot path.

Functional#

  • A user submits a long URL and gets back a short one.
  • Visiting a short URL redirects to the original long URL.
  • Optionally, the user can choose a custom alias instead of an auto-generated code.
  • Optionally, each URL can have an expiry date.

Non-functional#

  • Uniqueness: two different long URLs must never get the same short code.
  • Low latency: redirects should feel close to real time, low single-digit milliseconds on the server.
  • High availability: aim for 99.99%. A broken shortener breaks every link ever shared, in tweets, emails, QR codes and printed posters.
  • Scalability: about 1 billion URLs over 10 years and ~100M daily active users.

Back-of-the-envelope estimates#

This is the core part to discuss with the interviewer: how much storage you need, and how many reads and writes per second. These numbers justify every decision that follows.

Assume 1 billion URLs over 10 years, ~100M daily active users clicking about 3 links a day, and about 500 bytes per record.

MetricMathResult
Writes1,000,000,000 / (10 × 365 × 86,400)~3 / s
Reads100M users × 3 clicks / 86,400~3,500 / s
Read : write3,500 / 3~1000 : 1
Storage1B × 500 B~500 GB
Cache20% of a day's links × 500 B~30 GB

Two takeaways: writes are tiny, and the set of popular links fits comfortably in memory. Plan for peaks of about 10× (~30 writes/s, ~35k reads/s), and let a cache do most of the work.

API design#

Two endpoints are enough.

http.terminal
1
2
3
4
5
6
POST /api/v1/urls{ "long_url": "https://example.com/a/very/long/path", "alias": null, "expires_at": null }→ 201 { "short_url": "https://sho.rt/4c92xYz" }GET /{code}→ 302 Location: https://example.com/a/very/long/path
➜~http
UTF-86 lines● ready

Return 400 for an invalid URL, 409 Conflict if a custom alias is taken, 404 for an unknown code, 410 Gone for an expired one, and 429 when a client is rate-limited.

High-level design#

Stateless app servers sit behind a load balancer. On a write, a server takes the next ID, encodes it and stores code → long_url. On a read, it checks the cache first and only falls back to the database on a miss.

drawing diagram…
Fig. 1 — High-level architecture. Reads hit the cache first; analytics are written off the hot path.
  1. Write path: POST /urls → load balancer → any app server. The server validates the URL, takes the next ID from its leased range (or uses the custom alias), Base62-encodes it, writes the record and returns the short URL.
  2. Read path: GET /4c92xYz → app server → Redis. On a hit, redirect immediately. On a miss, read the database, fill the cache, then redirect.
  3. Analytics: after responding, publish a click event to a queue. A separate consumer aggregates counts.

Deep dive: generating short codes#

The core question: how do we generate the short code? It has to be short, unique, and cheap to create.

Why Base62?#

If we only use digits 0-9, a 6-character code gives us 10⁶ = 1 million combinations. Nowhere near enough.

Instead we use Base62 encoding:

  • 10 digits (0-9)
  • 26 lowercase letters (a-z)
  • 26 uppercase letters (A-Z)

That's 62 URL-safe characters.

LengthCombinations
662⁶ ≈ 56.8 billion
762⁷ ≈ 3.5 trillion

Six characters would technically cover 1 billion URLs, but 7 characters give 3.5 trillion codes: huge room to grow, and far harder to guess. Base64 is avoided because + and / have special meaning in URLs.

Encoding is just converting a number from base 10 to base 62. For example, 1,000,000 becomes 4c92:

typescript.terminal
1
2
3
4
5
6
7
8
9
10
11
CHARSET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"function encodeBase62(num: number): string {  if (num == 0) return CHARSET[0];  let encoded = "";  while (num > 0) {    encoded = CHARSET[num % 62] + encoded;    num = Math.floor(num / 62);  }  return encoded;}
➜~typescript
UTF-811 lines● ready

Base62 tells us how to turn a number into a short string. The real question is where that unique number comes from. There are three common approaches.

Option 1: hash the URL and truncate#

Take md5(long_url), Base62 it and keep the first 7 characters. It's stateless and naturally dedupes repeat URLs, but truncated hashes collide, so every write needs a check-and-retry against the database.

Option 2: random string plus lookup#

Generate 7 random characters and check whether they're taken. Fine at first, but as the keyspace fills, collisions get more frequent and writes get slower. A variant is a Key Generation Service that pre-generates unused random codes, at the cost of running one more highly available service.

A single global counter would be a bottleneck and a single point of failure. Instead, a small coordinator (ZooKeeper, etcd or a tiny DB table) hands each app server a block of IDs, say 1,000,000 at a time. The server encodes IDs from its block locally, so there's no coordination per request and no collisions. When a block runs out, it leases the next one.

At ~3 writes per second, a block of a million IDs lasts for days, and 3.5 trillion codes is decades of headroom.

Data model#

Access is always by a single key, so a key-value or wide-column store (DynamoDB, Cassandra) fits well and shards cleanly on code. At ~500 GB, PostgreSQL with read replicas also works; what matters is justifying the choice.

sql.terminal
1
2
3
4
5
6
7
8
CREATE TABLE urls (  code        VARCHAR(16) PRIMARY KEY,  long_url    TEXT NOT NULL,  user_id     BIGINT,  is_custom   BOOLEAN NOT NULL DEFAULT FALSE,  created_at  TIMESTAMP NOT NULL,  expires_at  TIMESTAMP);
➜~sql
UTF-88 lines● ready
  • Custom aliases go in the same table. Write them with a conditional insert ("only if not exists") so two users can't claim the same alias, and block reserved words like api or login.
  • Shard by hash(code) with consistent hashing, and keep about 3 replicas per shard so a node failure never takes links down.
  • For expiry, check expires_at on every read and return 410, then let a background job or the database's native TTL delete old rows. Don't reuse expired codes, so an old shared link never starts pointing somewhere new.

Trade-offs#

DecisionChosenAlternativeWhy
Redirect status302301Browsers don't cache it forever, so clicks stay measurable and links can expire or change.
Code length7 characters6 characters3.5 trillion codes instead of 56.8 billion: more headroom and harder to guess.
Code generationID ranges + Base62Hash + retryNo collisions and no coordination per request.
StorageKey-value storeRelational DBSingle-key lookups, no joins, easy to shard.
AnalyticsAsync queueInline writeNever slow down a redirect for a counter.

Follow-up questions#

Spotted a mistake or have a better approach?Send feedback →