Skip to the content

Lesson 239 of 296

Design: URL shortener

What you will learn

  • A complete walkthrough of the classic first design question
  • Generating short codes: three approaches
  • 301 vs 302 redirects
  • Scaling reads with caching
  • Analytics without slowing redirects
  • Abuse prevention
On this page

1. Requirements

Functional:

  • Create a short URL for a long URL.
  • Visiting the short URL redirects to the long one.
  • Optional: custom alias, expiry date, click statistics.

Non-functional:

  • Very high availability for redirects (broken links are very visible).
  • Low redirect latency (under about 50 ms server-side).
  • Short codes must be unique and should not be easily guessable in sequence (to stop people listing all links).
  • Read-heavy: about 100 reads per write.

2. Estimates

From Lesson 232: about 40 writes and 4,000 reads per second (10,000 at peak), 6 billion links and 3 TB over five years. A 7-character Base62 code gives about 3.5 trillion combinations.

3. API

POST /api/urls
  body: { "longUrl": "https://...", "customAlias": "summer-sale", "expiresAt": "2027-01-01T00:00:00Z" }
  201: { "code": "aZ3kP9x", "shortUrl": "https://sho.rt/aZ3kP9x" }

GET /{code}          → 302 Found, Location: https://...   (or 404 / 410 if expired)
GET /api/urls/{code}/stats → { "clicks": 1204, "byDay": [...] }

4. Data model

urls: code (primary key), long_url, owner_id, created_at, expires_at

Access is almost always "get by code": a key-value lookup. Either PostgreSQL (simple, unique constraint on code, fine at this size with caching) or DynamoDB (partition key code, scales automatically). Both are good answers if you explain why.

5. High-level design

Client → CDN / edge ─→ Load balancer ─→ Redirect service (stateless) ─→ Redis cache ─→ Database
                                        Create service ──────────────────────────────→ Database
                                        Click events ─→ Queue/stream ─→ Analytics workers ─→ Analytics store
  • Create: validate the URL, generate a code, insert, return.
  • Redirect: look up the code in Redis (cache-aside, Lesson 205); on a miss read the database and fill the cache; respond with a redirect; publish a click event asynchronously.

6. Deep dive: generating codes

Option A: hash the URL. Take MD5 or SHA-256 of the long URL, Base62-encode, keep the first 7 characters. Same URL gives the same code (natural de-duplication), but collisions are possible: check the database and, on collision, add a salt and retry.

Option B: a unique counter, Base62-encoded. Each new link gets the next number from a counter; encode it in Base62 (digits, lower and upper case letters). No collisions ever.

TypeScript
const ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

export function toBase62(value: bigint): string {
  if (value < 0n) throw new Error("Value must not be negative");
  if (value === 0n) return "0";
  let result = "";
  let n = value;
  while (n > 0n) {
    result = ALPHABET[Number(n % 62n)] + result;
    n /= 62n;
  }
  return result;
}

export function fromBase62(code: string): bigint {
  let value = 0n;
  for (const char of code) {
    const digit = ALPHABET.indexOf(char);
    if (digit === -1) throw new Error(`Invalid Base62 character: ${char}`);
    value = value * 62n + BigInt(digit);
  }
  return value;
}

BigInt (Lesson 32) avoids precision problems with very large numbers. Problems with a plain counter: codes are sequential and guessable (aZ3kP9x, aZ3kP9y...), and a single counter is a bottleneck and a single point of failure. Fixes:

  • Range allocation: each server reserves a block of 10,000 numbers at a time from the database or a coordination service (ZooKeeper, a Redis INCRBY), then hands them out from memory. No central call per link.
  • Obfuscation: shuffle the number with a reversible scrambling function (or use an ID generator like Snowflake, which combines time, machine ID and a sequence) so codes do not look sequential.

Option C: random codes. Generate 7 random Base62 characters (from crypto.randomInt, not Math.random) and insert with a unique constraint; on the rare conflict, retry. Simple, unguessable, no coordination. With 3.5 trillion possibilities and billions used, collisions stay rare, but the retry handles them.

Custom aliases: check availability and insert under the same unique constraint (the database decides races); reserve words such as api and admin.

Deep dive: 301 vs 302

301 Moved Permanently302 Found (temporary)
Browser cachingBrowsers cache it and may skip your server next timeBrowser asks your server every time
AnalyticsYou lose clicks after the firstEvery click is counted
Changing the target laterUsers with a cached redirect keep the old targetWorks

Most shorteners with analytics use 302 (or 307). Use 301 if you want maximum speed and do not need click data.

Deep dive: scaling reads

  • Redis in front of the database; popular links stay in cache (LRU). At a 95% hit ratio, the database sees only a few hundred reads per second.
  • CDN or edge caching of redirects for very popular links, with a short TTL.
  • Read replicas or DynamoDB for the database.
  • Redirect servers are stateless: auto scale horizontally.

Deep dive: analytics

Never update a counter row synchronously on every redirect (a hot row under heavy load). Instead publish a click event (code, time, country from IP, referrer, user agent) to a queue or stream (Kafka, Kinesis, SQS), and let workers aggregate counts per link per day into an analytics store (a columnar database such as ClickHouse, or pre-aggregated tables). The redirect stays fast; statistics are a few seconds behind (eventual consistency is fine here).

7. Wrap-up

  • Abuse: check long URLs against malware and phishing lists (for example Google Safe Browsing), rate limit link creation per user and IP, allow reporting and disabling links.
  • Expiry: return 410 Gone; clean up expired rows with a scheduled job or a TTL (DynamoDB TTL).
  • Availability: multiple availability zones; the redirect path depends only on cache and database reads.
  • Monitoring: redirect latency, cache hit ratio, 404 rate, creation rate.

How to say it in an interview

"For a URL shortener I agree creating links and redirecting as core features, estimate about 40 writes and 4,000 reads per second and 3 TB over five years, and choose 7-character Base62 codes giving 3.5 trillion combinations. Codes come from random generation with a unique constraint and retry, or a counter with range allocation and obfuscation. The redirect path is stateless servers reading through Redis with cache-aside and returning 302 so every click can be counted, while click events go to a stream for asynchronous aggregation. I add malware checks, rate limits on creation, expiry with 410, and monitoring of hit ratio and latency."

Key words

WordMeaning
Base62Encoding with 0-9, a-z and A-Z
Range allocationReserving blocks of IDs to avoid a central counter call per item
Snowflake IDA unique ID built from time, machine ID and a sequence
301 vs 302Permanent (cached) vs temporary redirect
Hot rowA database row updated so often it becomes a bottleneck

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.