{}DSA Atlas

Design a URL Shortener (TinyURL / bit.ly)

The classic warm-up. Short-code generation strategies (hash, counter + base62, pre-generated keys), a read-heavy redirect path with caching, 301 vs 302, analytics via an event stream, custom aliases, expiry, and abuse prevention.

Intermediate5 interview questions

1. Requirements

Functional

  • Create a short URL for a long URL (optional custom alias, optional expiry).
  • Redirect short URL → long URL.
  • Click analytics per link (counts, geography, referrers).

Non-functional

  • Very high availability for redirects (links are embedded everywhere).
  • Redirect latency p99 < 50 ms server-side.
  • Short codes unpredictable enough to avoid enumeration.
  • Durable: links must not be lost.

Out of scope: user management UI, link-in-bio pages, billing.

2. Estimation

QuantityAssumptionResult
New links100M / month~40 writes/s (peak ~200/s)
Redirects100:1 read ratio~4,000 reads/s avg (peak ~40k–100k/s)
Storage per linkcode 7 B + URL ~200 B + metadata ~300 B~500 B
5 years of links100M × 12 × 5 = 6B links~3 TB
Code length62⁷ ≈ 3.5 × 10¹²7 chars is plenty
Cache20% of daily hot linkstens of GB

Conclusion: small data, read-heavy, latency-sensitive → cache-heavy design; any KV store works.

3. API

HTTP
POST /api/v1/links
Authorization: Bearer <token>
Content-Type: application/json

{"long_url": "https://example.com/very/long/path?x=1", "custom_alias": "launch", "expires_at": "2027-01-01T00:00:00Z"}

201 Created
{"code": "launch", "short_url": "https://sho.rt/launch", "long_url": "...", "expires_at": "..."}
HTTP
GET /launch
302 Found
Location: https://example.com/very/long/path?x=1
Cache-Control: private, max-age=90

GET /api/v1/links/{code}/stats?from=…&to=…&granularity=day returns aggregated analytics.

4. Data model

SQL
CREATE TABLE links (
  code        VARCHAR(16) PRIMARY KEY,     -- partition key
  long_url    TEXT NOT NULL,
  owner_id    BIGINT,
  created_at  TIMESTAMPTZ NOT NULL DEFAULT now(),
  expires_at  TIMESTAMPTZ,
  is_disabled BOOLEAN NOT NULL DEFAULT false
);
CREATE INDEX ON links (owner_id, created_at DESC);    -- "my links" page

Access is by primary key only → DynamoDB/Cassandra or sharded Postgres keyed by code. Analytics go to a separate OLAP store.

5. High-level design

Pastebin / URL shortener architecture: client, web server, write API and read API, SQL database, object store, analytics
A reference architecture for Pastebin/bit.ly with separate read and write APIs. Diagram from The System Design Primer by Donne Martin, licensed CC BY 4.0.
client CDN /LB redirect service link service (writes) Redis cache links KV store ID ranges (ZK) Kafka clicks Flink →ClickHouse redirect path: cache hit ≈ 1 ms; miss → KV read → populate cache; click event async
Separate the hot, read-only redirect path from the low-volume write path.

Create flow: validate URL (format, safe-browsing check) → if custom alias, conditional insert (IF NOT EXISTS) → else take next ID from the server's local range → encode base62 (optionally shuffled) → insert → return.

Redirect flow: look up code in Redis → on miss read KV and populate (with negative caching for misses) → check expiry/disabled → emit click event async → 302 with Location.

6. Deep dives

Code generation with range allocation

ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

def base62(n: int) -> str:
    if n == 0:
        return ALPHABET[0]
    out = []
    while n:
        n, r = divmod(n, 62)
        out.append(ALPHABET[r])
    return "".join(reversed(out))

class IdAllocator:
    """Leases blocks of IDs from a coordinator so most allocations are local and lock-free."""
    def __init__(self, coordinator, block=1_000_000):
        self.coord, self.block = coordinator, block
        self.next = self.end = 0

    def next_id(self) -> int:
        if self.next >= self.end:
            start = self.coord.lease(self.block)      # atomic increment in ZK/DB
            self.next, self.end = start, start + self.block
        self.next += 1
        return self.next - 1
// Bijective shuffle so sequential IDs don't produce guessable codes:
// a 4-round Feistel network over a 42-bit space (62^7 > 2^42).
static final long[] KEYS = {0x3A7F1L, 0x1C2B9L, 0x7E44DL, 0x05F13L};   // secret round keys

static long permute(long id) {
    long l = (id >>> 21) & 0x1FFFFF, r = id & 0x1FFFFF;
    for (int round = 0; round < 4; round++) {
        long f = ((r * 0x5DEECE66DL + KEYS[round]) >>> 7) & 0x1FFFFF;
        long t = r; r = l ^ f; l = t;
    }
    return (l << 21) | r;
}

Custom aliases and uniqueness

Use a conditional write so two users can't claim the same alias: INSERT … IF NOT EXISTS (Cassandra LWT), DynamoDB attribute_not_exists(code), or a unique constraint in SQL. Reserve a namespace for generated codes (e.g., generated codes always 7 chars, aliases ≥ 4 chars and validated against a blocklist) so they never collide.

Expiry

Store expires_at; check on redirect (and set cache TTL ≤ remaining lifetime). Clean up lazily plus a periodic batch job (or the store's native TTL). Don't recycle expired codes quickly — old links in the wild would point somewhere new.

7. Trade-offs and evolution

DecisionChoiceAlternative
Code generationrange allocation + shufflehash + collision check; KGS
Redirect302 for analytics301 for less load
StoreDynamoDB/Cassandra (KV by code)sharded Postgres
Analyticsasync Kafka → OLAPsynchronous counters (slows redirects)
Multi-regionreplicate links globally (read-local), writes to home region—

Failure modes: cache cluster loss → DB read storm (use replicas, request coalescing, gradual warm-up); ID coordinator down → servers keep using leased ranges for a long time; Kafka down → buffer locally and drop analytics after a limit rather than failing redirects.

Interview questions

0 / 5 marked confident

Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.