Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Notes › System Design

Design a URL Shortener

Like TinyURL or bit.ly: https://example.com/blog/2025/very/long/path?ref=abc → https://sho.rt/aZ3x9Kq.

1. Requirements

Functional

Non-functional

2. Capacity estimates

3. API

POST /api/urls
{ "longUrl": "https://example.com/...", "alias": "my-event", "expiresAt": "2026-12-31" }
→ 201 { "shortUrl": "https://sho.rt/aZ3x9Kq" }

GET /{code}
→ 302 Location: https://example.com/...      (404 if unknown, 410 if expired)

GET /api/urls/{code}/stats   → clicks, countries, referrers

4. Data model

urls
  code        VARCHAR(10)  PRIMARY KEY
  long_url    TEXT
  user_id     BIGINT
  created_at  TIMESTAMP
  expires_at  TIMESTAMP NULL

clicks (or an analytics store)
  code, clicked_at, country, referrer, device

Access pattern is a simple key → value lookup with no joins → a NoSQL key-value/wide-column store (DynamoDB, Cassandra) scales easily; PostgreSQL/MySQL also works fine at this size with sharding later.

5. Generating the short code

Option A: hash the long URL

MD5(longUrl) → base62 → take the first 7 characters.

Option B: unique counter + base62 ✅ (common answer)

Give each URL a unique number, then encode it in base62.

const CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
function toBase62(n) {
  let s = '';
  do { s = CHARS[n % 62] + s; n = Math.floor(n / 62); } while (n > 0);
  return s;
}
toBase62(125);          // "21"   (2 × 62 + 1)
toBase62(3_500_000_000); // a 6-char code

Option C: pre-generated key service (KGS)

A separate service generates random unique 7-char keys in advance and stores them in an "unused" table. App servers take a batch into memory and mark them used.

Custom aliases: check availability and insert with a unique constraint; reject reserved words (api, admin).

6. Redirect: 301 or 302?

301 Moved Permanently 302 Found (temporary)
Browser caches it yes — next clicks skip your server no — every click hits you
Server load lower higher
Analytics you miss repeat clicks every click counted
Can change/expire the link later hard (cached) easy

bit.ly-style services usually use 302 (or 307) because analytics and editable links matter.

7. High-level architecture

            ┌──────────── write path ────────────┐
Client → LB → URL service → ID range / KGS → DB (sharded by code)
            └──────────── read path ─────────────┘
Client → CDN/edge? → LB → Redirect service → Redis cache → (miss) DB
                                   ↓
                         click event → Kafka queue → analytics workers → analytics DB

8. Other details

Interview one-liners

More System Design notes