Architecting a High-Throughput URL Shortener

Medium · System Design · Software Engineer · Other

Prompt

Architect a public, internet-scale URL shortening platform. Clients submit an arbitrary destination URL and receive a compact short link; whenever a visitor requests that short link, the platform resolves the token and issues an HTTP redirect back to the target address.

Structure your design around these core rules and priorities:

  • Core functional scope: Minting short links, resolving incoming short codes via HTTP redirects, and honoring optional link expiration (along with owner revocation/deletion). Treat custom vanity slugs and click telemetry as optional extensions once the core design is complete.
  • Strict token uniqueness: Every generated short code must map unambiguously—two distinct target URLs may never share the same code.
  • Read-path dominance: Traffic is heavily skewed toward redirects, and keeping redirect latency minimal and availability near-continuous matters far more than shaving milliseconds off link creation.
  • Explicit capacity modeling: No traffic volumes or retention horizons are given up front, so state concrete assumptions—monthly link creation volume, redirect QPS, multi-year retention, whether duplicate URL submissions mint fresh codes, whether sequential enumeration must be prevented, and analytics freshness—and derive storage, bandwidth, and short-code length directly from those numbers.

Scope & Expectations

  • Define the REST endpoints, HTTP redirect status codes (301 vs. 302 and their browser/CDN caching and telemetry trade-offs), and back-of-the-envelope estimates for QPS, storage, and Base-62 token length.
  • Compare candidate short-code generation approaches (such as hashing, centralized counters, pre-generated token pools, and leased ID ranges with bit permutation) across multi-server collision safety, enumeration resistance, custom vanity aliases, and repeated URLs.
  • Select a database schema and multi-tier caching strategy suited to skewed read traffic, explaining cache invalidation for expired or deleted links, horizontal partitioning, replication, and graceful degradation during component outages.

Step-by-step walkthrough

  1. Clarify requirements and priorities

    A URL shortener looks simple from the outside, yet under the hood it combines two completely asymmetric workloads: a low-volume write path that must mint globally unique, non-guessable short codes without servers stepping on each other, and a massive, skewed read path that must redirect visitors in milliseconds even if parts of the backend fail.

    Functional requirements

    • Shorten a URL: Accept a long http/https URL and return a unique short URL (such as https://lnk.io/Kp9mR4z).
    • Redirect: When anyone visits https://lnk.io/{code}, redirect their browser to the original long URL.
    • Lifecycle controls: Support optional expiration timestamps, plus allowing the link's owner to disable or delete a link.
    • Extensions: Optional custom human-readable aliases (such as /autumn-launch), optional secret high-entropy links, and asynchronous click analytics.

    Non-functional requirements

    • Ultra-low redirect latency: Under 20 ms at the origin (99th percentile, or p99, excluding client network transit), and even faster when served from an edge cache.
    • Asymmetric availability: Redirects target 99.99% uptime (< 53 minutes downtime/year); link creation targets 99.9% uptime (we prioritize keeping existing links working over creating new ones during partial outages).
    • Permanent uniqueness and durability: Once created, a link is stored for at least 10 years, never silently changes target, and never reuses an expired or deleted short code for a different URL.

    Clarifying questions and assumed answers

    • What traffic scale should we size for? 100 million new links/month and a 100:1 read-to-write ratio (10 billion redirects/month), retained for 10 years.
    • If two requests submit an identical destination URL, should we reuse one code or mint a fresh one? Mint a fresh one by default — two different users shortening the same news article expect independent click counts and expiration controls. An authenticated owner may optionally request per-owner deduplication.
    • Can short codes be sequential (0000001, 0000002)? No — sequential codes let competitors count total volume and scrape every created link in order. Standard codes must look random; truly confidential links can opt into a longer 12-character secret code.
    • How fresh must click analytics be? Within 1–2 minutes is fine, and analytics collection must never add latency or failure risk to redirects.
  2. Back-of-the-envelope estimates and code length

    Sizing the lifetime link count first tells us the exact short-code length, database size, and cache footprint we need:

    1. Write and read throughput (1 month ≈ 30.44 days ≈ 2.63 million seconds)
       Create rate (writes)   100M / 2.63M s = ~38 creates/s avg  -> assume 5x peak  = ~200 creates/s
       Redirect rate (reads)  10B  / 2.63M s = ~3,800 reads/s avg -> assume 10x peak = ~40,000 reads/s
       Egress bandwidth       40,000 reads/s x ~400 bytes per HTTP redirect = ~16 MB/s (trivial)
    
    2. Lifetime link count & short-code length (Base-62 alphabet: [0-9, A-Z, a-z] = 62 symbols)
       10-year link total     100M/month x 12 months x 10 years = 12 billion links
       6 chars: 62^6          = 56.8 billion   -> 12B fills 21.1%! (1 in 5 random guesses hits a real link)
       7 chars: 62^7          = 3.52 trillion  -> 12B fills 0.34%  (1 in ~294 random guesses; plenty of headroom)
       8 chars: 62^8          = 218 trillion   -> 12B fills 0.0055%
       12 chars (secret mode) = 3.23 x 10^21   -> virtually impossible to guess by brute force
       Choice: 7 Base-62 characters for standard links; 12 random Base-62 characters for secret links.
    
    3. Persistent storage (10 years)
       Row size               code (7 B) + long_url (~100 B avg, max 2,048 B) + metadata/overhead ≈ 250 B
       Dataset size           12B rows x 250 B = ~3 TB logical -> x3 replicas = ~9 TB per region
    
    4. Cache memory (Pareto / power-law skew: most clicks hit a small fraction of active links)
       Assume ~30M distinct links are clicked on a given day, and the hottest 10M drive >90% of clicks:
       10M cached entries x ~200 bytes = ~2 GB RAM -> fits comfortably inside a single Redis instance!
    
    5. Stateless redirect servers
       At ~5,000 cached redirects/s per server -> 8 servers handle 40,000/s peak (run 16 per region for N+2 headroom)
    

    Three insights anchor the entire design: - 7 characters is the sweet spot. 6 characters becomes 21% full over 10 years, making random enumeration trivial; 7 characters stays 99.66% empty (3.52 trillion slots for 12 billion links). - 200 creates/s is tiny. We can afford clean, strongly consistent coordination on link creation as long as the redirect path stays completely independent of it. - 2 GB of RAM caches the daily hot set. Even though the database holds 3 TB of historical links, almost all 40,000 redirects/s will be answered from edge and memory caches without touching disk.

  3. Public API and choosing 302 vs 301

    1. Create a short link
       POST /v1/links
       Headers: Authorization: Bearer <token>   (optional; anonymous callers get stricter IP rate limits)
                Idempotency-Key: <client-uuid>  (prevents duplicate links on network retry)
       Body:    { "long_url": "https://example.org/q4-deck",
                  "custom_alias": "autumn-launch",        // optional
                  "secret": false,                        // optional: true -> 12-char random code
                  "deduplicate": false,                   // optional: reuse caller's prior code for URL
                  "expires_at": "2027-06-01T00:00:00Z" }  // optional
       Responses:
         201 Created  { "code": "Kp9mR4z", "short_url": "https://lnk.io/Kp9mR4z", "expires_at": ... }
         400 Bad Request        (non-http/https scheme, > 2,048 bytes, malformed URL, or reserved alias)
         409 Conflict           (custom_alias is already taken)
         422 Unprocessable      (destination URL flagged by malware/phishing check)
         429 Too Many Requests  (caller exceeded creation rate limit)
    
    2. Follow a short link (the hot read path)
       GET /{code}
       Responses:
         302 Found              Location: <long_url>
                                Cache-Control: public, max-age=0, s-maxage=60
         404 Not Found          (short code has never existed)
         410 Gone               (link expired, or was disabled/deleted by owner)
         503 Service Unavailable (temporary backend failure — NEVER return 404 on server errors!)
    
    3. Manage an existing link (authenticated owner)
       GET    /v1/links/{code}  -> metadata + aggregated click stats
       PATCH  /v1/links/{code}  -> { "status": "ACTIVE" | "DISABLED", "expires_at": ... }
       DELETE /v1/links/{code}  -> 204 No Content (soft-deletes to status="DELETED"; code is never reused)
    

    Why 302 Found beats 301 Moved Permanently here: - 301 Moved Permanently tells browsers to cache the redirect indefinitely in local disk cache. Once a user clicks a 301 link, future clicks in that browser jump straight to the destination without ever contacting us — blinding click analytics and making it impossible to expire, delete, or block a hijacked destination for returning visitors! - 302 Found with Cache-Control: public, max-age=0, s-maxage=60 gives us the best of both worlds: - max-age=0 instructs private browser caches not to store the redirect, so browsers always check back. - s-maxage=60 allows our shared CDN edge servers (Content Delivery Network nodes close to users) to serve viral bursts from memory for 60 seconds while streaming CDN access logs into our analytics pipeline and letting us purge or expire links within ~60 seconds. (Owners who genuinely want permanent browser caching and no analytics can opt into 301.) - Why 404 vs 410 vs 503 matters: 410 Gone tells browsers and search crawlers a link intentionally ended, whereas returning 404 during a database timeout tricks clients into caching a valid link as broken. Backend errors must always return 503.

  4. Data model and database choice

    Every redirect is a pure single-key lookup (WHERE code = ?) with zero relational joins or multi-row transactions. A distributed wide-column / key-value store such as Apache Cassandra (or Amazon DynamoDB) hashes code evenly across nodes, scales horizontally to 12 billion rows (~9 TB per region with 3x replication) without manual sharding, and supports conditional inserts (IF NOT EXISTS) for custom aliases.

    1. Primary lookup table: links (Cassandra, RF = 3 per region)
       Partition key: code (text)
         long_url       text        up to 2,048 bytes
         owner_id       bigint      nullable for anonymous links
         created_at     timestamp
         expires_at     timestamp   nullable (null = never expires)
         status         text        "ACTIVE" | "DISABLED" | "BLOCKED" | "DELETED"
         redirect_type  smallint    302 (default) or 301
         version        int         incremented on every edit/delete to guard cache updates
       Note: NO automatic Cassandra TTL deletion! Keeping expired/deleted rows (already budgeted in 3 TB)
             ensures old codes reliably return 410 Gone and can never be reclaimed by someone else.
    
    2. Owner dashboard index: links_by_owner (Cassandra)
       Partition key: (owner_id, year_month)   -- month bucket prevents active enterprise accounts from
       Clustering:    created_at DESC, code    -- creating an unbounded multi-GB partition!
    
    3. Optional per-owner URL deduplication: owner_url_index (Cassandra)
       Partition key: (owner_id, sha256_normalized_url) -> code
    
    4. Idempotency cache (Redis / Cassandra, 24 h TTL)
       Key: (caller_id_or_ip, idempotency_key) -> created response JSON
       (Scoped by caller so one user cannot replay another user's UUID to inspect their link!)
    
    5. Range allocator table: id_blocks (PostgreSQL or etcd in the home write region)
       region (PK) | next_id (bigint)   -- hands out non-overlapping blocks of 10,000 integer IDs
    
  5. High-level architecture

    We split Redirect Service (stateless, read-only, deployed in every region) from Create Service (write path, anchored in one home write region so uniqueness checks never require slow cross-continent consensus).

                                 Users / Browsers
                                        |
                              Anycast / GeoDNS routing
                                        |
                         CDN Edge (caches 302s for s-maxage=60s)
                                        |
      +------------------------- Regional Stack (x3 Regions) -------------------------+
      |                         Layer-7 Load Balancer                                 |
      |                          /                 \                                  |
      |                         v                   v                                 |
      |             Redirect Service             Create Service                       |
      |        (in-process LRU + request       (non-home regions forward              |
      |         coalescing, read-only)          writes to Home Region)                |
      |               |           |                 |         |         \             |
      |               v           |                 |         |          v            |
      |        Redis Cluster      |                 |         v     URL Safety Check  |
      |        (~2 GB hot set)    |                 |   ID Block Allocator            |
      |               |           |                 |   (Postgres/etcd, Home)         |
      |               +-----------+-----------------+                                 |
      |                           |                                                   |
      |                           v                                                   |
      |               Cassandra "links" (RF=3 per region, async multi-region)         |
      |                                                                               |
      |   Async side-channel: Redirect Servers + CDN Logs --> Kafka --> ClickHouse    |
      +-------------------------------------------------------------------------------+
    
  6. Compare code generation schemes

    How do 20 application servers generate millions of 7-character codes concurrently with zero collisions and minimal server-to-server coordination? Let's compare five standard candidates:

    Generation scheme How uniqueness is guaranteed Coordination cost per link Server restart impact Predictability / flaws
    1. Truncated URL hash (Base62(SHA256(url))[:7]) Not unique! Must run conditional INSERT IF NOT EXISTS and retry with salt on collision 1 multi-round database conditional write per link Stateless (nothing lost) Anyone can compute the code of a known public URL; forces global sharing across owners
    2. Single global counter (AUTO_INCREMENT / Redis INCR) Strictly increasing integer 1 network call per link to a single bottleneck node Counter outage halts all creates Sequential (0000001, 0000002): competitors can enumerate every link!
    3. Pre-generated Key Service (KGS) Background job fills DB of random 7-char strings; servers lease batches 1 batch fetch per ~10,000 links Unused batch in RAM (~5,000 keys) is discarded Unpredictable, but requires storing, locking, and replenishing terabytes of unused keys
    4. Pure random code + IF NOT EXISTS Database rejects duplicates; retry on collision 1 Paxos conditional insert per link Stateless (nothing lost) Truly random and simple! Usually uses 8 chars to keep collision retries near zero, paying Paxos latency on every create
    5. Leased counter ranges + keyed permutation (Chosen) Disjoint numeric blocks [start, start+10000) + 1-to-1 reversible bit shuffle 1 tiny DB update per 10,000 links (plain fast insert into Cassandra!) Discards at most 9,999 unused IDs (harmless!) Zero collisions by math, non-sequential appearance, 7-char codes, near-zero coordination

    Checking the restart waste math for Scheme 5: Even if 100 create servers restarted every single day for 10 years and threw away a full 10,000-ID block each time, 100 * 3,650 * 10,000 = 3.65 billion wasted IDs — just 0.1% of our 3.52 trillion 7-character namespace!

  7. Deep dive: Range allocation, Feistel permutation, and custom aliases

    1. Leasing non-overlapping ID blocks: In the home region's Postgres allocator, a create server grabs 10,000 IDs in one atomic statement:

    UPDATE id_blocks
    SET next_id = next_id + 10000
    WHERE region = 'us-east'
    RETURNING next_id - 10000 AS block_start;
    

    At 200 creates/s globally, the allocator handles just 1 query every 50 seconds! Each server prefetches its next block in the background when its current block hits 50% used, so allocation latency on the create path is literally zero. (To keep future multi-region active-active writes open, we can also partition the 41-bit ID range into 6 disjoint slices of 2^39 ≈ 550 billion IDs per region, since 6 * 2^39 = 3.30T < 3.52T.)

    2. Scrambling sequential IDs without collisions (Feistel permutation + cycle-walking): If we convert 10001, 10002, 10003 directly to Base-62, users get sequential codes. Instead, we pass the integer through a keyed permutation — a deterministic, one-to-one mathematical shuffle controlled by a secret key, so two different input IDs provably never produce the same output number!

    A Feistel network builds a reversible shuffle on an even number of bits (42 bits, where 2^42 = 4.40 trillion is the smallest even power of two above 62^7 = 3.52 trillion). It splits the 42-bit integer into two 21-bit halves (left, right) and runs 4 rounds of new_left = right, new_right = left XOR hash(secret_key, round, right). Because XOR cancels itself out ((A ^ B) ^ B == A), every step is strictly reversible — meaning collisions are mathematically impossible! If the 42-bit output lands between 3.52T and 4.40T (outside 7 Base-62 characters), we simply feed it through feistel again until it lands below 62^7 (cycle-walking, which averages 4.40T / 3.52T ≈ 1.25 calls and preserves exact one-to-one uniqueness).

    import hashlib
    import hmac
    
    ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
    CODE_LEN = 7
    DOMAIN = 62 ** CODE_LEN          # 3,521,614,606,208 total 7-character Base-62 codes
    HALF_BITS = 21                   # Two 21-bit halves = 42 bits (2**42 = 4.40T >= DOMAIN)
    HALF_MASK = (1 << HALF_BITS) - 1
    ROUNDS = 4
    
    
    def _round_prf(secret_key: bytes, round_idx: int, right_half: int) -> int:
        """Keyed pseudo-random function returning 21 bits from (round_idx, right_half)."""
        msg = bytes([round_idx]) + right_half.to_bytes(3, "big")
        digest = hmac.new(secret_key, msg, hashlib.sha256).digest()
        return int.from_bytes(digest[:3], "big") & HALF_MASK
    
    
    def _feistel_42bit(secret_key: bytes, value: int) -> int:
        """Reversible 1-to-1 permutation over [0, 2**42)."""
        left = value >> HALF_BITS
        right = value & HALF_MASK
        for round_idx in range(ROUNDS):
            # Swap halves and XOR left with keyed hash of right; strictly invertible!
            left, right = right, left ^ _round_prf(secret_key, round_idx, right)
        return (left << HALF_BITS) | right
    
    
    def permute_id(secret_key: bytes, link_id: int) -> int:
        """Bijection mapping link_id in [0, 62**7) to a scrambled integer in [0, 62**7)."""
        scrambled = _feistel_42bit(secret_key, link_id)
        # Cycle-walking: if >= 62**7, keep stepping along the permutation cycle (~1.25 steps avg).
        while scrambled >= DOMAIN:
            scrambled = _feistel_42bit(secret_key, scrambled)
        return scrambled
    
    
    def encode_base62(num: int) -> str:
        """Convert an integer in [0, 62**7) into a fixed 7-character Base-62 string."""
        chars = []
        for _ in range(CODE_LEN):
            num, remainder = divmod(num, 62)
            chars.append(ALPHABET[remainder])
        return "".join(reversed(chars))
    
    
    def generate_short_code(secret_key: bytes, link_id: int) -> str:
        """Turn a unique numeric link_id into a unique, non-sequential 7-char code."""
        return encode_base62(permute_id(secret_key, link_id))
    

    If generate_short_code happens to contain a banned substring from an in-memory profanity filter, the server simply discards link_id and moves to link_id + 1 in RAM. Also note: a 4-round 42-bit Feistel shuffle prevents casual sequential scraping (for formal cryptographic strength, swap in NIST SP 800-38G FF1 format-preserving encryption), while real protection against brute-force scanning comes from low namespace density (0.34% full -> 293 failed 404s per lucky hit), strict IP rate-limiting on 404 responses (e.g., 100 404s/minute), and 12-character random codes (62^12 ≈ 3.2 x 10^21) whenever a user marks a link as secret.

    3. Keeping custom aliases and generated codes completely collision-free: Custom aliases (3–30 characters from [A-Za-z0-9_-], validated against reserved routes like api, v1, admin, login) could collide with a future 7-character generated code unless we separate their namespaces! We enforce one simple validation rule: a custom alias cannot be a 7-character string made solely of [0-9A-Za-z] (7-character aliases with - or _, or aliases of length 3–6 or 8–30, are welcome). Because no custom alias or 12-character secret code ever enters the 7-character Base-62 namespace: - Generated 7-character codes write to Cassandra with a fast plain INSERT (no Paxos overhead!). - Custom aliases and 12-character secret codes use INSERT ... IF NOT EXISTS in the home region (returning 409 Conflict if a custom alias is already claimed). - Optional per-owner URL deduplication normalizes the URL (lowercasing scheme/host, stripping default ports :80/:443, preserving path, query, and fragment) and checks owner_url_index first.

  8. Deep dive: Multi-layer caching, coalescing, and versioned invalidation

    Popularity on the web follows a steep power law: a viral post receives 50,000 clicks/s while billions of old links get zero. Four nested layers shield the database:

    Incoming GET /{code}
      |
      +--> [Layer 1: CDN Edge]       Cached 302 (s-maxage=60s) -> absorbs global viral spikes (~0 ms origin load)
      |       (miss)
      +--> [Layer 2: In-Process LRU] 100,000 hot codes (~20 MB RAM/server, TTL=30s) -> ~1 microsecond, 0 network
      |       (miss -> Request Coalescing / Singleflight merges concurrent identical misses on this server!)
      +--> [Layer 3: Regional Redis] Cache-aside (~2 GB RAM, TTL=min(24h, time_to_expiry)) -> ~1 ms
      |       (miss)
      +--> [Layer 4: Cassandra]      LOCAL_ONE read (~3 ms). If missing:
                                       1. Retry LOCAL_QUORUM locally (catches local replica lag after write).
                                       2. In non-home regions, query Home Region behind a 300 req/s rate cap
                                          (catches brand-new links < 1s old without letting 404 scanners flood WAN!).
                                       3. Still missing -> return 404 + write negative cache (Redis 60s, LRU 10s).
    

    Three mechanisms keep this read path fast and consistent under edge cases:

    • Request coalescing (Singleflight): If a cold link suddenly goes viral on television and 2,000 requests hit a redirect server before Redis has it cached, request coalescing lets one request query Redis/Cassandra while the other 1,999 wait in memory for its result and share the response — preventing a cache stampede (thousands of identical misses hammering one database partition).
    • Bounded read-after-write consistency + negative caching: When a user creates a link in us-east and immediately shares it with a friend in eu-west 200 ms later, async Cassandra replication might still be in flight. Pushing newly created links onto a fast cross-region Kafka stream warms every region's Redis within ~200 ms, and our rate-capped (300 req/s) home-region fallback catches sub-200 ms misses without allowing botnets scanning random 404s to amplify cross-region traffic! Confirmed 404 misses are negative-cached (status = MISSING in Redis for 60 s, LRU for 10 s) so repeat guesses stop at RAM.
    • Version-guarded cache invalidation (preventing stale-replica zombies):
      • Natural expiration needs zero cache purges: expires_at is stored inside the 200-byte cached object, checked against current time on every request, and caps CDN s-maxage = min(60, seconds_left).
      • Owner delete, disable, or abuse block: In the home region, Create Service increments version = version + 1 in Cassandra and publishes {code, version, new_record} to a cross-region Kafka invalidation topic. In every region, an invalidator consumer runs a 5-line atomic Redis Lua script that overwrites Redis only if incoming.version > cached.version, broadcasts an in-process LRU eviction to redirect pods, and calls the CDN purge API.
      • Why version numbers beat DEL code: If you simply delete code from Redis in eu-west while eu-west's Cassandra replica is still 1 second behind, the very next click misses Redis, reads the stale ACTIVE row (version = 1) from Cassandra, and caches the deleted link back into Redis for 24 hours! Because cache-miss fills also check version, version = 1 can never overwrite version = 2 (DELETED). Even if a best-effort LRU broadcast or CDN purge packet drops, staleness heals automatically within 30 s (LRU) + 60 s (CDN) = ~90 seconds.
  9. Partitioning, failure modes, monitoring, and trade-offs

    Partitioning and multi-region replication: Cassandra hashes code with Murmur3 across a 12–15 node ring per region (RF = 3 across 3 Availability Zones). Every region stores the full ~9 TB dataset so normal redirects never leave the user's region.

    Graceful behavior during failures:

    Component failure Impact on users Automated mitigation
    Regional Redis down Cache misses fall through to Cassandra In-process LRU still absorbs top 100k hot links; per-pod concurrency limiter sheds excess cold misses with 503 + Retry-After to protect Cassandra
    1 Availability Zone down Zero user impact Load balancer drains AZ; Cassandra LOCAL_ONE reads and LOCAL_QUORUM writes (2 of 3 replicas) succeed seamlessly
    Cassandra partition slow/down Uncached cold links on that token range fail Serve slightly expired Redis entries (serve-stale-on-error); return 503 (never 404 and never negative-cache errors!)
    Entire region outage Regional edge shifts GeoDNS / Anycast health checks route users to nearest healthy region (each region provisioned with 1.5x capacity)
    ID Block Allocator down Zero impact for 4–12 minutes Each of 10 create pods holds 5,000–15,000 pre-leased IDs in RAM (~20 creates/s per pod = 250–750 s runway) while standby Postgres promotes

    Key metrics to monitor: - Redirect availability (99.99% SLO) and p50/p99 latency at CDN edge and origin. - Cache hit ratio per tier (CDN, in-process LRU, Redis) and Cassandra read QPS (a sudden drop in hit ratio is the earliest warning of a scanner attack or broken invalidator). - 404 rate per client subnet (detects enumeration bots) and 5xx rate. - Remaining ID block runway on create servers and cross-region invalidation lag.

    Summary of core trade-offs: - 302 + 60s CDN cache vs. 301: Preserves link revocation, expiration, and click analytics at the cost of periodic CDN/origin requests (~90 s max takedown window). - Range-leased IDs + Feistel shuffle vs. random 8-char Paxos inserts: Achieves compact 7-character codes, zero collision retries, and plain fast Cassandra inserts, trading off a tiny Postgres block allocator. - Single home write region vs. multi-master writes: Eliminates cross-continent alias race conditions while adding ~80–150 ms to link creation from distant continents — an ideal trade for a 100:1 read-heavy service.

Intuition & how it works

Think of a URL shortener like the coat-check counter at a 100,000-seat stadium. Checking a coat in (creating a link) happens calmly at the doors, whereas retrieving coats (redirecting visitors) happens in massive waves — and strangely, thousands of fans keep asking to look at the same 50 celebrity coats on display! To keep lines moving without two clerks ever handing out the same ticket number: 1. Instead of making 20 clerks shout across the room for the next ticket number on every single coat, a manager hands each clerk a pre-printed roll of 10,000 sequential numbers, and the ticket printer scrambles each number with a reversible cipher so guests see random-looking 7-character codes (Kp9mR4z) instead of 0010001, 0010002. 2. Instead of walking into the huge back warehouse (database) every time someone asks for a popular item, clerks pin a photo of the hottest items right on the counter (CDN edge and in-memory caches), answering 99% of requests in milliseconds.

Naive designs fail in two predictable ways: using a single auto-increment database counter bottlenecks link creation on one server and lets anyone scrape every private link by counting 1, 2, 3..., while querying the database directly on every redirect melts under viral traffic spikes and wastes resources on a workload with a 100:1 read-to-write ratio.

Tiny concrete walkthrough: 1. Create (POST /v1/links): Server A holds pre-leased ID block [20,000 .. 29,999] in RAM. It pops 20,001, runs the 42-bit Feistel permutation (a reversible mathematical bit-shuffle that guarantees two different integers never collide) plus Base-62 encoding ([0-9A-Za-z]) to get "Kp9mR4z", writes {code: "Kp9mR4z", long_url: "https://example.org/q4-deck", version: 1, status: "ACTIVE"} to Cassandra, and returns 201 Created. 2. First click (GET /Kp9mR4z): Misses CDN -> misses server in-process LRU cache (Least Recently Used memory cache) -> misses regional Redis -> reads Cassandra in 3 ms, populates Redis (TTL = 24 h) and LRU (TTL = 30 s), and returns 302 Found with Cache-Control: public, max-age=0, s-maxage=60 while dropping a click event into an async memory buffer for Kafka. 3. Next 50,000 viral clicks: Answered directly by CDN edge nodes for 60 seconds and in-process LRU caches in microseconds — zero database reads! 4. Owner deletes link (DELETE /v1/links/Kp9mR4z): Home region writes status = "DELETED", version = 2 and emits an invalidation event. Regional consumers atomically update Redis to version = 2, purge the CDN and LRU, and subsequent clicks immediately receive 410 Gone.

Key trade-offs

  • 302 Found (with 60s CDN s-maxage) vs. 301 Moved Permanently. Returning 301 lets browsers cache redirects forever, minimizing server cost, but permanently blinds click analytics and prevents owners or abuse teams from disabling, expiring, or blocking a link for anyone whose browser already cached it. Returning 302 with max-age=0, s-maxage=60 forces browsers to re-check while letting our CDN absorb viral bursts, bounding takedown delay to ~60–90 seconds.
  • Leased ID blocks + Feistel permutation vs. random codes + conditional inserts. Leasing 10,000-ID blocks and permuting them produces compact 7-character codes (62^7 = 3.52 trillion) with zero collision retries, 1 allocator query per 10,000 creates, and fast plain inserts into Cassandra — trading off a tiny Postgres range allocator and non-cryptographic order hiding. Generating random 8-character codes (62^8 = 218 trillion) needs no allocator or secret key, at the cost of 1 character longer URLs and paying a multi-round Paxos conditional write (INSERT IF NOT EXISTS, a consensus protocol requiring extra network round trips) on every create.
  • 7-character standard links vs. 12-character secret links. At 12 billion links over 10 years, 7 Base-62 characters are 0.34% full (1 in ~294 random guesses hits an existing link), which is ideal for compact public links protected by 404 IP rate limits, whereas truly confidential links trade length for unguessability with 12 random characters (62^12 ≈ 3.2 x 10^21).
  • Partitioned wide-column/KV store (Cassandra/DynamoDB) vs. relational database (PostgreSQL). Redirects only ever look up one row by primary key code with no joins, so Cassandra scales linearly across ~9 TB per region without manual application sharding, trading away multi-table SQL transactions the hot path never uses.
  • Versioned cache updates + short edge TTLs vs. simple cache DEL on delete. Issuing a plain DEL in Redis during async database replication suffers from a classic race condition: an immediate cache miss can read a lagging database replica (version = 1) and re-cache a deleted link for 24 hours. Writing tombstones with monotonically increasing version numbers via an atomic Redis Lua script prevents stale overwrites, while 30s LRU + 60s CDN TTLs guarantee self-healing within ~90 seconds even if a purge message drops.
  • Single home write region vs. multi-region active-active writes. Routing all creates/edits (~200/s peak) to one home region makes custom-alias uniqueness (IF NOT EXISTS) trivial with zero cross-continent conflicts, trading +80–150 ms on link creation from distant regions so that all 40,000 redirects/s stay 100% local in every region.

Common mistakes

  • Defaulting to 301 Moved Permanently "for performance", without realizing browsers cache 301s indefinitely — breaking click analytics, link expiration, and malware takedowns.
  • Choosing 6-character codes based only on Year-1 traffic, which reaches 21% occupancy at 12 billion lifetime links (62^6 = 56.8B), causing frequent random collisions and letting bots guess valid links 1 time out of 5.
  • Encoding raw sequential IDs (1, 2, 3...) directly into Base-62, allowing anyone to deduce exact business volume and scrape every created URL in sequence.
  • Truncating a SHA-256 hash to 7 characters without collision handling, silently overwriting one user's URL with another's when two URLs share a 7-character prefix.
  • Checking custom alias availability with SELECT followed by INSERT, creating a time-of-check to time-of-use (TOCTOU) race where two concurrent requests both see empty and overwrite each other; always use an atomic conditional insert (IF NOT EXISTS).
  • Allowing 7-character alphanumeric custom aliases without checking the generated space, letting a future counter-generated code silently overwrite a user's custom alias unless 7-character pure Base-62 aliases are disallowed.
  • Returning 404 Not Found (or negative-caching) when the database times out, causing browsers and search engines to treat a temporary backend blip as a permanently dead link (always return 503).
  • Deleting expired rows from the database to "save disk", which allows old printed QR codes or shared links to return 404 instead of 410 Gone — or worse, get reassigned to a phishing site!
  • Skipping request coalescing (Singleflight), so a single cold link shared to millions of followers triggers thousands of simultaneous cache misses against one Cassandra partition.

Follow-up questions

  • How can you capture per-link click telemetry without adding latency or failure points to the redirect path? Never write to a database or wait on network acknowledgments inside the GET /{code} handler. Instead, redirect servers append a lightweight event (code, timestamp, coarse GeoIP country, referrer domain, device class) to a bounded in-memory ring buffer and return 302 immediately; a background worker flushes batches to Kafka (dropping and counting events on extreme backpressure rather than blocking redirects), while CDN-served clicks arrive via real-time CDN log streams. A stream processor (such as Apache Flink) filters known bot signatures, rolls up per-minute click totals and HyperLogLog sketches (compact ~1.5 KB probabilistic counters that estimate unique visitors within ~1–2% error) per code, and writes aggregates to an analytical columnar store like ClickHouse — giving owners ~1-minute fresh dashboards with zero impact on redirect latency.
  • What defenses prevent bad actors from abusing your shortener to distribute phishing or malware URLs? Defend both synchronously at creation and asynchronously afterward, because attackers often point a clean URL at a phishing page after shortening it. At POST /v1/links, enforce http/https schemes only, block links pointing to other URL shorteners (which hide redirect chains), check the domain and URL against low-latency threat feeds (such as Google Safe Browsing and internal domain blocklists), and apply strict per-IP and account-trust rate limits with CAPTCHAs for anonymous bursts. Asynchronously, a background scanner crawls every newly created destination (following full redirect chains in a headless sandbox) within minutes and re-scans popular links daily; if flagged (status = "BLOCKED", version + 1), our versioned Kafka invalidation updates Redis globally in seconds and purges CDN/LRU caches within ~90 seconds so visitors see an interstitial safety warning page instead of being redirected.
  • How would you evolve the deployment across multiple geographic regions so global visitors experience fast local redirects? Place a global CDN at the edge using Anycast (where multiple worldwide PoPs advertise the same IP address so BGP naturally routes packets to the closest edge node) backed by GeoDNS across 3+ regional origin stacks (e.g., US-East, EU-West, AP-Northeast). Because the entire 10-year links dataset is ~9 TB with 3x replication, every region holds a full local Cassandra replica, its own 2 GB Redis cluster, and stateless redirect pods — meaning 99.99%+ of redirects never cross an ocean. Writes (~200/s) forward to the single home write region, which asynchronously replicates to Cassandra and immediately streams new records over Kafka to warm remote Redis caches within ~200 ms; if a user in Tokyo clicks a brand-new link 50 ms after creation and misses locally, a rate-capped (300 req/s) fallback check to the home region resolves it cleanly without exposing the cross-region link to random 404 flood attacks.
  • Trace how your caching, storage, and telemetry layers behave when a single celebrity link suddenly drives an extreme traffic spike. Almost the entire tsunami is absorbed before reaching our core storage: hundreds of global CDN edge locations serve the cached 302 (s-maxage=60) directly from RAM, forwarding at most ~1 request per edge location per minute to our origin. At the origin, each redirect pod caches the link in its local in-process LRU for 30 seconds — answering hundreds of thousands of requests per second from local process memory without touching Redis over the network (preventing a single-shard hot key bottleneck on one Redis CPU core!) — and request coalescing ensures at most 1 Redis/Cassandra read happens per pod every 30 seconds when that TTL refreshes. Finally, on the analytics side, we partition the raw clicks Kafka topic randomly (or pre-aggregate per-second counters in memory on each redirect pod before publishing) rather than keying raw events by code, ensuring one viral link never overloads a single Kafka partition, while also triggering an automatic priority safety re-scan of the sudden viral destination.

Follow-up questions

Similar questions

More Nielsen interview questions

All 5 Nielsen questions →