Distributed Link Shortener for Extreme Redirect Loads

Medium · System Design · Software Engineer · Onsite

Prompt

Architect a globally distributed link-shortening platform built to sustain massive, heavily skewed redirect traffic. A client submits a full destination web address—optionally specifying a custom slug or an expiration timestamp—and receives a compact short URL; anyone opening that short link is routed to the original destination via an HTTP redirect.

Traffic volumes and product rules are intentionally left open so you can state explicit assumptions up front and size every component from them: establish daily link creations versus peak redirects per second, decide whether submitting the same destination URL twice mints a fresh code or reuses an existing one, define custom-alias constraints and link lifetime defaults, determine whether per-link click counts are tracked, and specify how resistant generated codes must be to sequential enumeration.

Scope & Expectations

  • API Contracts & Redirect Semantics: Specify the link-creation and redirect endpoints, request/response schemas, input validation, abuse rate limits, error codes, and the caching and control trade-offs behind your chosen HTTP redirect status code.
  • Keyspace Math & Distributed Code Minting: Derive minimum short-code length from multi-year capacity estimates, design a low-coordination mechanism for generating unique codes across distributed servers, and prevent collisions across both generated codes and custom aliases.
  • Storage, Sharding & Multi-Tier Caching: Choose a persistence engine, data model, and partition key; scale read and write paths independently; and layer caches to absorb viral hot-key traffic spikes as well as scans of non-existent codes.
  • High Availability & Link Expiration: Keep redirects serving through node, cache, database, or regional outages via replication and graceful degradation, while enforcing link expiration and takedowns promptly across caches without recycling retired codes.

Step-by-step walkthrough

  1. Clarify requirements and scope

    Creating short links is a modest, steady write workload. The hard problem is the redirect path: traffic is heavily read-skewed, viral links concentrate millions of clicks on a single key, latency directly slows down page loads, and redirects must stay up even when link creation or analytics is degraded. At the same time, no cached redirect may outlive an expired or disabled link.

    Functional requirements

    • POST /v1/links takes a long URL (plus an optional custom alias, expiration time, or private-link flag) and returns a short URL.
    • GET /{code} redirects callers to the original long URL.
    • Link owners can inspect metadata, shorten or extend expiry, disable or delete links, and view per-minute click counts.
    • Links expire automatically at expires_at, and abusive links can be taken down rapidly.

    Non-functional requirements

    • Redirect latency and availability: p99 < 50 ms at the edge for cached links, p99 < 100 ms for cold links in their home region, and 99.99% availability (stricter than link creation).
    • Create latency and availability: p99 < 200 ms and 99.9% availability.
    • Uniqueness invariant: A short code never points to two different destination URLs at any point in the service's lifetime.

    Assumptions confirmed up front

    • Scale: 100M new links created per day and 1,000,000 redirects per second at peak (~200,000 redirects/s average, or ~17.3B redirects/day).
    • Custom aliases: Allowed (4 to 32 characters from [A-Za-z0-9_-]), except exact 7-character and exact 16-character base62 strings (base62 encodes numbers using the 62 alphanumeric characters 0-9, A-Z, a-z). Reserving lengths 7 and 16 keeps generated codes, private codes, and custom aliases in disjoint shapes so they can never collide.
    • Duplicate long URLs: Shortening the same long URL twice creates a fresh short code by default because ownership, expiration, and click stats belong to an individual link; authenticated callers may pass dedupe: true to reuse their own existing active link.
    • Expiration and reuse: Signed-in links default to no expiry (with optional expires_at); anonymous links expire after 1 year. Retired or expired codes are never reissued.
    • Guessability: Standard 7-character codes look random so outsiders cannot count through links sequentially, whereas truly unguessable links opt into private: true (16 characters).
    • Geography: 3 active-active regions globally, routing users to their nearest healthy region.
  2. Back-of-the-envelope numbers

    Every architectural choice—code length, database type, cache RAM, and server count—follows directly from sizing the workload.

    1. Traffic rates
       New links:    100,000,000 / 86,400 s = ~1,160 creates/s average, ~6,000 creates/s at 5x peak
       Redirects:    200,000 / s average (17.3B/day), 1,000,000 / s at viral peak
       Read : write: ~170 : 1 on average
    
    2. Short-code length (target horizon: 10 years = 100M x 365 x 10 = 365 billion links)
       6 chars:  62^6 = 56.8 billion codes    -> exhausted in ~1.6 years (too short)
       7 chars:  62^7 = 3.52 trillion codes   -> ~10.4% full after 10 years (sweet spot)
       8 chars:  62^8 = 218.3 trillion codes  -> adds 1 extra character to every URL unnecessarily
    
    3. Database storage
       Row size:     ~500 bytes (long URL ~200 B + owner, timestamps, status, index overhead)
       1 year:       36.5B rows x 500 B = ~18.3 TB per copy
       10 years:     ~183 TB per copy; across 3 replicas x 3 regions (9 copies) = ~1.65 PB
    
    4. Redirect bandwidth & multi-layer read fan-in at 1,000,000 redirects/s peak
       HTTP 302 response size: ~400 bytes -> 1M/s x 400 B = 400 MB/s (~3.2 Gbps), absorbed mostly at the CDN edge
       Layer 1 - CDN edge (~90% hit on skewed links):   900,000/s served at edge  -> 100,000/s reach origin (3 regions)
       Layer 2 - In-process server LRU (~50% hit):       50,000/s served in RAM   ->  50,000/s reach regional Redis
       Layer 3 - Regional Redis (~95% hit):              47,500/s served by Redis ->   2,500/s reach the database
    
    5. Origin fleet & cache memory per region
       Redirect servers: ~10,000 req/s per stateless server; if 1 of 3 regions fails, each surviving region
                         handles 50,000/s -> 5 servers needed, run 10 per region for 2x headroom
       Regional Redis:   ~200M active codes clicked/day x ~300 B = ~60 GB RAM (8 primary shards x 8 GB + 8 replicas)
       In-process LRU:   1,000,000 hottest entries x ~300 B = ~300 MB RAM per redirect server
    

    Three design lessons jump out: 7 characters is the minimum safe length; 6,000 writes/s is small enough to afford per-key uniqueness checks; and caching layers must absorb ~99.75% of peak redirects so the database sees a calm ~2,500 reads/s.

  3. Link creation and redirect APIs

    POST /v1/links
      Headers:  Authorization: Bearer <token>          (optional for rate-limited anonymous tier)
                Idempotency-Key: <client-uuid>         (safe retries return the exact same short link)
      Body:     { "long_url": "https://docs.example.org/releases/2026-q4?ref=launch",
                  "alias": "q4-notes",                 // optional, 4-32 chars, not 7 or 16 base62 chars
                  "expires_at": "2027-06-01T00:00:00Z",// optional ISO-8601 UTC timestamp
                  "private": false,                    // true -> 16-char unguessable code
                  "dedupe": false }
      Responses:
        201 Created   { "code": "9Kp3mVx", "short_url": "https://go.example/9Kp3mVx",
                        "long_url": "...", "created_at": "...", "expires_at": "..." }
        200 OK        (returned when dedupe=true matches an existing active link for this owner)
        400 Bad Request         invalid scheme (only http/https), >2,048 chars, self-referential short URL,
                                reserved alias ("api", "admin", "login"), or invalid expiry
        409 Conflict            custom alias is already taken
        422 Unprocessable       destination matches phishing/malware blocklist
        429 Too Many Requests   token-bucket rate limit exceeded (includes Retry-After header)
        503 Service Unavailable create path degraded (redirects remain unaffected)
    
    GET /{code}   (and HEAD /{code})
      302 Found      Location: <long_url>
                     Cache-Control: max-age=0, s-maxage=<min(60, remaining_seconds)>   (or no-store if <1 s left)
      404 Not Found  code was never created; Cache-Control: max-age=0, s-maxage=10
      410 Gone       link expired, disabled, or deleted; Cache-Control: max-age=0, s-maxage=60
    
    PATCH  /v1/links/{code}    update expires_at or set status="DISABLED" (owner or abuse tool)
    DELETE /v1/links/{code}    retires link (status="DELETED"); code is never reused
    GET    /v1/links/{code}/stats?from=...&to=...&granularity=minute|hour|day
    

    An idempotency key is a unique client-generated request ID stored briefly by the server so that if a mobile client times out and retries POST /v1/links, it receives the already-created short link instead of minting a duplicate.

    Why 302 Found beats 301 Moved Permanently:

    • 301 Moved Permanently triggers heuristic caching—browsers and corporate proxies are allowed by HTTP standards (RFC 9110) to cache a 301 locally for days or months even when no Cache-Control header is sent. Once a user's browser caches a 301, future clicks never leave their laptop: click analytics go blind, shortened expires_at deadlines are ignored, and phishing takedowns cannot protect anyone who clicked once.
    • 302 Found with Cache-Control: max-age=0, s-maxage=60 gives us the best of both worlds. max-age=0 instructs end-user browsers not to cache, while s-maxage=60 allows our CDN (Content Delivery Network—hundreds of geographically distributed edge servers that we control) to cache the redirect for up to 60 seconds. Because the CDN logs every edge cache hit to our analytics stream and obeys instant purge commands on takedowns, we shed 90% of origin traffic without losing visibility or control.
  4. Data model and database choice

    links                          Partition key: code
      code                         string (7-char generated, 16-char private, or 4-32 char custom alias)
      long_url                     string (<= 2,048 chars)
      owner_id                     string (nullable for anonymous links)
      created_at, expires_at       int64 epoch seconds (expires_at nullable)
      status                       ACTIVE | DISABLED | DELETED
      redirect_status              302 (default) | 301 (verified enterprise opt-in only, capped max-age)
      version                      int64 (starts at 1, increments on every update/disable/delete)
    
    owner_links                    Partition key: owner_id, Clustering key: (created_at DESC, code)
                                   Supports "list my links" pagination without scanning the main table
    
    dedupe_index                   Partition key: (owner_id, sha256(normalized_long_url)) -> code
                                   Populated only when dedupe=true
    
    id_superblocks                 Stored in global consensus store (etcd / ZooKeeper):
                                   (superblock_id, start_int, end_int, owning_region, allocated_at)
    

    Why a partitioned key-value / wide-column store (such as DynamoDB Global Tables or Cassandra/ScyllaDB):

    • The hot redirect read is a single lookup by primary key (code), and creation is a single-row conditional write (an atomic database insert such as INSERT IF NOT EXISTS that succeeds only if that key is currently absent). We never run multi-table SQL joins on the redirect path.
    • At ~18.3 TB of new rows per copy per year, horizontal hash partitioning and built-in multi-region replication avoid manual SQL shard splits.
    • Crucial multi-region nuance: Under asynchronous multi-region replication, a conditional write only checks the local region before returning 201 Created; if two regions accidentally picked the same code within the same millisecond, last-writer-wins replication would silently overwrite one URL! Therefore, cross-region uniqueness must be guaranteed by how we generate codes, not by slow cross-ocean database locks.
  5. High-level architecture

     End-User Browser / Mobile App:  GET https://go.example/9Kp3mVx
            |
            v
     [ CDN Edge (hundreds of global PoPs) ]  -- caches 302 up to 60 s, coalesces concurrent misses,
            |                                   rate-limits 404 scanners, streams all hit+miss logs
            | (cache miss: ~10% of peak)
            v
     [ Global Anycast / Geo-DNS ] ------------> routes to nearest healthy region (3 active-active regions)
            |                                                  |
            | GET /{code}                                      | POST /v1/links, PATCH, DELETE
            v                                                  v
     [ Redirect Service (x10/region) ]                  [ Create & Management Service ] ---> Safe-Browsing / URL Check
       1. Allocated-range check (RAM)                          |  fetches 100k ID block           ^
       2. In-process LRU (~300 MB)                             v                                  | async re-scan
            | (miss)                                    [ Regional ID Allocator ] <-- 1B range -- [ Global etcd ]
            v                                                  |
     [ Regional Redis Cluster (~60 GB) ]                       | conditional write (local region)
            | (miss)                                           v
            +-----------------------------------------> [ Partitioned Links Store ] <=== async multi-region replication
    
     Async side pipelines (never block GET /{code}):
       CDN Edge Logs + non-CDN Origin Events ---> [ Kafka: click_events ] ---> [ Stream Aggregator ] ---> [ Analytics DB ]
       Link Disable / Delete / New Alias     ---> [ Kafka: invalidations ] --> CDN Purge + Redis Versioned Overwrite + LRU Evict
    

    Separating the Redirect Service from the Create Service into independent deployments ensures that a sudden burst of API link creations, a slow threat-list check, or an allocator hiccup cannot consume CPU or threads needed by redirects. Likewise, click events are pushed non-blocking (and CDN misses carry an X-Via-CDN header so origin servers only emit click events for direct non-CDN callers, preventing double-counting).

  6. Deep dive 1: Code generation, range allocation, and collision safety

    Comparing three strategies for minting short codes:

    1. Derive from URL hash (base62(sha256(long_url) mod 62^7)): Needs zero cross-server coordination, but two different URLs can hash to the same 7-character code. Once 10% of the key space is occupied (365B links out of 3.52T), 10% of all new links collide on their first try, requiring salted retry loops and conditional cross-region locks.
    2. Time-based 64-bit Snowflake IDs (41-bit ms timestamp + 10-bit worker + 12-bit sequence): Avoids a central allocator, but shifting the timestamp left by 22 bits produces integers above 62^10 within ~6.3 years (200B ms x 2^22 > 62^10), forcing short links to grow to 10 or 11 characters instead of 7, and breaking if a server clock jumps backward.
    3. Hierarchical range allocation + keyed permutation (our choice): Assign each new link a strictly unique integer from [0, 62^7), amortized across two range levels so servers never coordinate per request:
    Global Consensus Store (etcd / ZooKeeper across regions)
      |-- grants Region A superblock [0 .. 999,999,999]          (1B IDs = ~30 days of regional creates)
      |-- grants Region B superblock [1,000,000,000 .. 1.999B]   (disjoint! Region A and B can NEVER collide)
            |
            v
    Regional Allocator (in-region etcd)
      |-- grants Create Server 2 block [200,000 .. 299,999]      (100k IDs = ~5.5 min at 300 creates/s)
            |
            v
    Create Server 2 (in-memory atomic counter)
      |-- increments counter in RAM (0 network calls per create; prefetches next 100k block at 50% usage)
    
    • Allocator failure modes: If the regional allocator restarts, create servers coast for minutes on their current + prefetched 100k blocks; if the global allocator is unreachable, regions coast for weeks on their 1B superblocks. If a create server crashes, at most 100k unused integers are skipped—wasting a negligible fraction of our 3.52-trillion budget.

    Obfuscating sequential counters without losing uniqueness. Encoding 1, 2, 3 directly into base62 (0000001, 0000002) leaks total business volume and lets scrapers enumerate every link. We pass each counter through a 42-bit Feistel network before base62 encoding. A Feistel network is a lightweight, reversible cipher structure that scrambles numbers using a secret key, forming a mathematical bijection (a strict one-to-one mapping where two different input counters are guaranteed to produce two different output integers). Because 2^42 = 4.40T is slightly larger than 62^7 = 3.52T, if a scrambled number lands above 62^7 - 1, we simply apply the Feistel scramble again (cycle walking—averaging just 4.40 / 3.52 = 1.25 passes) until it lands inside [0, 62^7):

    import hashlib
    import hmac
    
    ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
    CHAR_TO_VAL = {ch: idx for idx, ch in enumerate(ALPHABET)}
    CODE_LEN = 7
    DOMAIN = 62 ** CODE_LEN          # 3,521,614,606,208 valid 7-char codes
    HALF_BITS = 21                   # Two 21-bit halves = 42 bits (2**42 >= 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 for one Feistel round."""
        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_forward(secret_key: bytes, x: int) -> int:
        """Reversible 4-round bit scramble on 42-bit integers."""
        left = x >> HALF_BITS
        right = x & HALF_MASK
        for r in range(ROUNDS):
            # Swap halves and XOR left with a keyed hash of right (reversible!).
            left, right = right, left ^ round_prf(secret_key, r, right)
        return (left << HALF_BITS) | right
    
    
    def feistel_inverse(secret_key: bytes, y: int) -> int:
        """Exact inverse of feistel_forward: recovers original counter x."""
        left = y >> HALF_BITS
        right = y & HALF_MASK
        for r in reversed(range(ROUNDS)):
            left, right = right ^ round_prf(secret_key, r, left), left
        return (left << HALF_BITS) | right
    
    
    def permute_counter(secret_key: bytes, counter: int) -> int:
        """One-to-one mapping on [0, DOMAIN) using cycle walking."""
        scrambled = feistel_forward(secret_key, counter)
        while scrambled >= DOMAIN:
            scrambled = feistel_forward(secret_key, scrambled)
        return scrambled
    
    
    def unpermute_counter(secret_key: bytes, scrambled: int) -> int:
        """Recovers the original allocated counter to check whether it was issued."""
        candidate = feistel_inverse(secret_key, scrambled)
        while candidate >= DOMAIN:
            candidate = feistel_inverse(secret_key, candidate)
        return candidate
    
    
    def to_base62(num: int) -> str:
        """Encodes an integer in [0, 62**7) into a fixed 7-character base62 string."""
        chars = []
        for _ in range(CODE_LEN):
            num, remainder = divmod(num, 62)
            chars.append(ALPHABET[remainder])
        return "".join(reversed(chars))
    
    
    def from_base62(code: str) -> int:
        """Decodes a 7-character base62 string back into its integer in [0, 62**7)."""
        value = 0
        for ch in code:
            value = value * 62 + CHAR_TO_VAL[ch]
        return value
    

    Private links and custom aliases:

    • Why 7 characters cannot be secret: At 10% fill, 1 in 10 random 7-character guesses hits a real link regardless of cryptography! When private: true is requested (for unlisted shared documents or receipts), the server generates 93 cryptographic random bits + a 2-bit region_id (95 bits < 62^16) and encodes it as 16 base62 characters. Embedding region_id makes cross-region collisions mathematically impossible (0), a local conditional write catches any same-region collision, and even with 1 billion private links, a random guess succeeds with probability 10^9 / 62^16 = ~2 x 10^-20.
    • Custom aliases: Because aliases forbid exact lengths 7 and 16 in base62, an alias like "autumn-launch" can never collide with a generated or private code. To prevent two regions from claiming "autumn-launch" simultaneously, alias creations (~1% of creates, ~60/s at peak) route to one designated alias home region and execute a conditional INSERT IF NOT EXISTS (409 Conflict if taken).
  7. Deep dive 2: Absorbing 1,000,000 redirects per second

    Five defense layers stand in front of the database during heavy traffic:

    Layer                       What it handles                        TTL / Footprint          Remaining load
    -----------------------------------------------------------------------------------------------------------
    1. CDN Edge                 ~90% of redirects (viral/popular)      s-maxage <= 60 s         100,000 req/s
    2. Allocated-range check    90-99% of random 7-char guesses -> 404 ~5 KB range table in RAM drops bogus scans
    3. In-process LRU cache     ~50% of origin traffic (hottest keys)  ~300 MB/server, <=30 s    50,000 req/s
    4. Regional Redis cluster   ~95% of remaining working set          ~60 GB/region, <=24 h      2,500 req/s
    5. Partitioned Links Store  Cold tail of old, rarely clicked links ~18 TB/yr/copy            ~2,500 req/s
    

    Stopping cache penetration (bots scanning non-existent codes):

    • Exact allocated-range check: When a 7-character code arrives on a cache miss, the redirect server runs unpermute_counter(secret_key, from_base62(code)) in ~2 microseconds and checks whether the resulting integer falls inside any allocated id_superblocks range cached in server RAM (just a few dozen [start, end, region] tuples!). Because unpermuting maps random strings uniformly across [0, 3.52T), ~99% of random guesses in Year 1 (and ~90% in Year 10) land outside allocated superblocks and return 404 immediately with zero Redis or database calls. By contrast, a Bloom filter (a probabilistic bit-array set that tests membership with a tunable false-positive rate) at a 1% false-positive rate requires ~9.6 bits/item x 36.5B links / 8 = ~44 GB of RAM per year of links (~440 GB over 10 years)!
    • Negative caching (storing a temporary "NOT_FOUND" placeholder in Redis for missing keys): Handles non-existent custom aliases, unallocated gaps inside active blocks, and bogus 16-char private codes for 60 seconds in Redis (and 10 seconds at the CDN). Whenever a new custom alias is created, publishing its code on the invalidation stream clears any "NOT_FOUND" entry immediately.

    Stopping hot-key stampedes: At both the CDN edge and inside each redirect server, request coalescing (single-flight) merges concurrent misses for the exact same code into a single downstream request while waiting callers share the result. Even if 500,000 users click a viral link in the same second, each of our 30 redirect servers sends at most 1 request to Redis every 30 seconds.

    import time
    
    NOT_FOUND = "NOT_FOUND"
    BASE62_CHARS = set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
    
    
    def is_standard_generated_code(code: str) -> bool:
        return len(code) == 7 and all(ch in BASE62_CHARS for ch in code)
    
    
    def compute_internal_ttl(entry, now: float, max_active_ttl: int) -> int:
        """Computes safe cache TTL for Redis and in-process LRU."""
        # Already-expired or disabled rows are cached for 60s as tombstones
        # so repeat clicks return 410 from cache instead of hitting the DB every second.
        if entry.status != "ACTIVE":
            return 60
        if entry.expires_at is not None and entry.expires_at <= now:
            return 60
        if entry.expires_at is None:
            return max_active_ttl
        remaining = int(entry.expires_at - now)
        return max(1, min(max_active_ttl, remaining))
    
    
    def edge_cache_control(entry, now: float) -> str:
        """Computes CDN Cache-Control header so edge caches never outlive expires_at."""
        if entry.expires_at is None:
            return "max-age=0, s-maxage=60"
        remaining = int(entry.expires_at - now)
        if remaining <= 0:
            # Less than 1 full second left: forbid CDN caching so it cannot overshoot expiry.
            return "no-store"
        return f"max-age=0, s-maxage={min(60, remaining)}"
    
    
    def handle_redirect(code: str, superblocks, lru_cache, redis_cache, db_store):
        now = time.time()
    
        # 1. Zero-I/O range filter rejects unissued 7-char codes immediately.
        if is_standard_generated_code(code) and not superblocks.was_allocated(code):
            return 404, None, "max-age=0, s-maxage=10"
    
        # 2. Check in-process server LRU, then regional Redis, then database.
        entry = lru_cache.get(code)
        if entry is None:
            entry = fetch_from_redis_or_db(code, redis_cache, db_store, now)
            if entry != NOT_FOUND:
                lru_cache.put(code, entry, compute_internal_ttl(entry, now, 30))
    
        if entry == NOT_FOUND:
            return 404, None, "max-age=0, s-maxage=10"
    
        # 3. Re-verify status and exact expiration on every single read.
        if entry.status != "ACTIVE" or (entry.expires_at is not None and entry.expires_at <= now):
            return 410, None, "max-age=0, s-maxage=60"
    
        return entry.redirect_status, entry.long_url, edge_cache_control(entry, now)
    
    
    def fetch_from_redis_or_db(code: str, redis_cache, db_store, now: float):
        entry = redis_cache.get(code)
        if entry is not None:
            return entry
        # Single-flight collapses concurrent misses per server into one DB read.
        entry = db_store.get(code)
        if entry is None:
            redis_cache.set_with_ttl(code, NOT_FOUND, 60)
            return NOT_FOUND
        # Version-guarded Lua write prevents stale DB replicas from overwriting newer tombstones.
        ttl = compute_internal_ttl(entry, now, 86400)
        redis_cache.set_if_version_not_older(code, entry, entry.version, ttl)
        return entry
    
  8. Deep dive 3: Expiration and takedowns no cache outlives

    No cached redirect may ever outlive its link—whether from a scheduled expires_at deadline or an urgent abuse takedown (status = "DISABLED"):

    • Scheduled expiration (expires_at): Browsers never cache (max-age=0), the CDN caps s-maxage at remaining seconds (and switches to no-store inside the final second), and redirect servers check entry.expires_at <= now on every read before emitting a 302. Once expired, callers receive 410 Gone (signaling intentional retirement) rather than 404 Not Found.
    • Immediate takedowns and deletions (closing the stale-replica race): When an owner deletes a link or abuse tooling disables it, the Management Service writes status = "DISABLED", version = old_version + 1 to the database and publishes (code, updated_entry) to a multi-region Kafka invalidations stream. Stream consumers call the CDN Purge API, evict local server LRUs, and overwrite Redis with the disabled version + 1 row rather than running DEL. Why overwrite instead of DEL? Look at what happens if you merely delete from Redis in a multi-region cluster:
    Time   Event (if we used plain Redis DEL instead of versioned overwrite)
    -----------------------------------------------------------------------------------------------
    t=0 ms Abuse tool sets status=DISABLED (v=2) in Region A and runs DEL in Region B's Redis.
    t=5 ms User in Region B clicks link -> Redis miss -> reads Region B's DB replica (still at v=1!).
    t=6 ms Redirect server writes old ACTIVE (v=1) row back into Region B's Redis for 24 hours!
    

    By overwriting Redis with (status=DISABLED, v=2) and guarding cache fills with a small Lua compare-and-set (only write if incoming.version >= stored.version), the lagging v=1 database read is rejected and the dead link can never resurrect.

    • Storage cleanup and zero code reuse: Database native TTLs (such as DynamoDB TTL) delete expired payloads lazily hours later, so we use native TTL only to reclaim disk bytes on archived URLs while keeping a tiny tombstone (a compact marker row recording that code existed and is now DELETED) or retiring its integer forever. Reusing old short codes is strictly forbidden because links printed on flyers, emails, or QR codes would suddenly redirect visitors to an unrelated stranger's URL.
  9. Database sharding, resharding, and independent scaling

    • Partition key choice: Hash-partition links by code. Every redirect touches exactly one partition, and Feistel-permuted codes distribute writes uniformly across all storage nodes. Partitioning by created_at would funnel 100% of current writes onto a single hot node; partitioning by owner_id would prevent GET /{code} from knowing which shard to query!
    • Owner dashboard queries: Maintain the separate owner_links table partitioned by owner_id (and clustered by created_at DESC) via dual-writes plus an asynchronous reconciliation job—keeping dashboard queries completely isolated from redirect storage partitions.
    • Zero-downtime resharding: Managed wide-column stores split partitions automatically; if running sharded relational databases (such as Postgres), hash code into 4,096 fixed logical shards (crc32(code) mod 4096) mapped to physical clusters via a small shard-map config in memory. Scaling out simply replicates logical shards [2048..2559] to a new host via change-data-capture, verifies checksums, and flips those shard-map pointers atomically without rehashing keys.
    • Independent read vs. write scaling: Peak writes (~6,000/s) scale horizontally by adding stateless Create Servers and storage partitions; peak reads (1,000,000/s) scale independently via CDN edge PoPs, stateless Redirect Servers, and read-only Redis replicas.
  10. Availability, multi-region failover, and trade-off summary

    Prioritize survival strictly by user impact: 1. Redirects (99.99%) > 2. Link creation (99.9%) > 3. Analytics & owner UI.

    Failure scenario              Impact on redirects                   Automated mitigation
    --------------------------------------------------------------------------------------------------------------------
    Single Redirect Server dies   Zero user impact                      Health check drops server from load balancer in <2 s
    Redis primary shard fails     1/8 of regional cache misses briefly  Replica promoted in seconds; DB absorbs ~3k extra reads/s
    Links DB outage / latency     Cold cache misses cannot load         Serve-stale mode: keep serving cached Redis/LRU entries
                                                                        past cache TTL while still enforcing expires_at & purges;
                                                                        Create API returns 503 cleanly
    Regional/Global ID allocator  Zero impact for minutes to weeks      Servers use 100k RAM blocks; regions use 1B superblocks
    Entire cloud region down      Geo-DNS shifts traffic to 2 surviving Each region is provisioned at 2x headroom for 50% of global
                                  regions                               origin traffic; regions create from disjoint superblocks
    CDN provider outage           Origin traffic jumps up to 10x        Multi-CDN DNS steering + auto-scaled Redirect Servers
                                                                        whose 300 MB in-process LRUs absorb hot viral keys
    

    Handling cross-region read-after-write lag: Because multi-region database replication is asynchronous (~200–800 ms lag), suppose a link is created in us-east and clicked 100 ms later by a colleague in eu-west. When eu-west misses locally on a 7-character code, it runs unpermute_counter, sees from id_superblocks that us-east owns that superblock, and makes one direct fallback read to us-east (and similarly to the alias home region for custom aliases)—turning a false 404 into a valid 302 at the cost of one ~80 ms cross-region hop on brand-new cold links.

    Summary of key trade-offs

    • 302 + short CDN s-maxage vs. 301: Pays small CDN edge egress on every click in exchange for accurate click analytics, enforceable expires_at deadlines, and fast phishing takedowns.
    • Region-owned integer ranges + Feistel permutation vs. URL hashing: Requires a lightweight range allocator and skips small gaps on crashes, in exchange for 7-character compactness, zero hash collisions, and zero cross-region write locks.
    • Versioned Redis overwrites vs. plain cache DEL: Adds a 5-line Lua check on cache writes, in exchange for guaranteeing that lagging database replicas never resurrect disabled or deleted links.
    • Asynchronous vs. synchronous cross-region replication: Keeps link creation fast (<50 ms local write) and regions failure-independent, trading away durability of the final ~1 second of brand-new links if an entire region suffers a sudden catastrophic outage.

Intuition & how it works

Think of a distributed URL shortener like a massive stadium coat-check system with 100 doors. Handing out unique tickets when guests drop off coats is calm and steady: instead of making every attendant shout across the stadium to agree on the next ticket number, a supervisor hands each booth its own pre-printed roll of 100,000 numbers so attendants issue tickets instantly from memory. The real storm hits when the game ends and 1,000,000 people ask where their item hangs at the exact same second—which only works if popular answers are posted on giant boards right at the outer gates (the CDN), smaller boards sit at each booth (in-memory and Redis caches), bogus ticket numbers outside any printed roll are rejected at a glance, and cancelled tickets are crossed off with version numbers so nobody accidentally re-posts an old sign.

A naive design generates short codes by incrementing a single SQL AUTO_INCREMENT primary key (or truncating an MD5/SHA-256 hash), queries the database on every click, and returns HTTP 301 Moved Permanently. At 100M new links per day and 1,000,000 redirects per second, that design collapses: a single database counter is a write bottleneck and single point of failure, 7-character truncated hashes suffer a 10% collision rate as the table fills, 301 causes browsers to cache redirects permanently (blinding analytics and making expiration and phishing takedowns impossible), and bots scanning random URLs bypass empty caches to crush the database.

Walk through creating and clicking one concrete link to see how our architecture handles every requirement:

  1. Zero-lock creation: Create Server 2 grabs integer 200,001 from its in-memory block [200,000 .. 299,999] (part of Region A's disjoint 1-billion superblock). It scrambles 200,001 through a reversible 42-bit Feistel network (a keyed bit-shuffler that guarantees no two counters ever produce the same output) and encodes it in base62 (0-9, A-Z, a-z) as "9Kp3mVx", saving (code="9Kp3mVx", version=1, expires_at=15:00:00).
  2. Expiry-capped edge caching: A visitor opens GET /9Kp3mVx at 14:59:45 (15 seconds before expiry). The CDN misses once; a Redirect Server verifies 200,001 lies inside Region A's allocated superblock, loads the row, and returns 302 Found with Cache-Control: max-age=0, s-maxage=15—telling browsers not to cache (max-age=0) while letting the CDN edge serve the next 80,000 viral clicks in <10 ms for the remaining 15 seconds (s-maxage=15).
  3. Exact expiration: At 15:00:00, the CDN entry expires automatically, our server's per-read check sees expires_at <= now, and subsequent clicks cleanly receive 410 Gone.

Key trade-offs

  • 302 Found + CDN s-maxage vs. 301 Moved Permanently. Under HTTP rules, 301 allows heuristic caching (browsers caching the redirect indefinitely without checking back), which saves bandwidth but permanently breaks click counting, link expiration, and abuse takedowns for anyone who clicked once. Returning 302 with max-age=0, s-maxage=60 keeps browsers coming to our CDN—which logs every hit and obeys instant purges—at the cost of cheap CDN edge bandwidth.
  • Range-allocated integers + Feistel bijection vs. URL hashing vs. Snowflake. Truncated URL hashes need no allocator but collide on ~10% of creates at 10-year capacity (365B / 62^7). 64-bit Snowflake IDs avoid central coordination but require 10 to 11 base62 characters due to their 22-bit worker/sequence shift. Hierarchical integer blocks permuted by a bijection (a strict one-to-one reversible mapping) keep links to 7 characters with zero collisions and zero cross-region locks, at the cost of a small consensus store (a fault-tolerant coordination service like etcd or ZooKeeper) and harmless skipped IDs when a server restarts.
  • Obfuscation (7 chars) vs. cryptographic secrecy (16 chars). Scrambling counters stops competitors from counting 1, 2, 3 to scrape every URL, yet when 10% of all 62^7 strings exist, 1 in 10 random guesses still hits a valid link. Keeping everyday links crisp at 7 characters while offering an opt-in 16-character random mode (with an embedded 2-bit region tag so regions never collide) reserves extra URL length only for links that truly need secrecy.
  • Allocated-range check vs. Bloom filter for missing codes. Inverting the Feistel permutation on a 7-character code and checking a tiny ~5 KB table of allocated superblocks in RAM rejects 90–99% of random bot guesses with zero false positives. A Bloom filter (a compact probabilistic bit array that checks set membership) at a 1% false-positive rate would consume ~44 GB of RAM per year of created links (~440 GB over 10 years) and require continuous synchronization across servers.
  • Partitioned key-value store vs. sharded relational SQL. A distributed key-value / wide-column database (DynamoDB or ScyllaDB) handles ~18 TB/year per copy of single-key lookups and multi-region replication natively, trading away ad-hoc SQL joins—which we handle separately via an owner_links index table and an analytical store.
  • Versioned cache overwrites vs. cache deletes (DEL) on takedown. Simply deleting a disabled key from Redis allows a concurrent cache miss reading a slightly lagging database replica to write the old ACTIVE row right back into Redis for 24 hours. Publishing (status=DISABLED, version+1) and enforcing monotonic versions via a Redis Lua script adds tiny write complexity to eliminate zombie links completely.
  • Serve-stale availability vs. strict database coupling. During a database outage, serving cached entries past their internal cache TTL (while still enforcing expires_at and invalidation-stream takedowns) keeps 99.99% of hot redirects alive even while POST /v1/links temporarily returns 503.

Common mistakes

  • Returning 301 Moved Permanently to "reduce server load", overlooking that browser caching blinds analytics and makes link expiration and phishing takedowns unenforceable.
  • Picking 6-character codes without key-space math (62^6 = 56.8B, which runs out in ~1.6 years at 100M links/day) or truncating SHA-256 hashes without handling the resulting ~10% collision rate.
  • Using a single relational AUTO_INCREMENT database to issue IDs, creating both a global throughput bottleneck and a single point of failure.
  • Writing click analytics synchronously inside GET /{code}, or keying Kafka click partitions directly by code so one viral link melts a single broker partition.
  • Leaving the database exposed to random 404 scans with neither an allocated-range filter nor negative caching (caching "NOT_FOUND" markers briefly so repeated misses stop at Redis/CDN).
  • Setting fixed 24-hour cache TTLs that ignore expires_at, or relying on lazy database TTL background compaction (which can lag by hours or days) to enforce link expiry.
  • Reusing expired or deleted short codes, which hijacks old links printed on documents or shared in emails and turns them into phishing vectors.
  • Letting custom aliases share the exact 7-character base62 format of generated codes, allowing a future counter permutation to collide with an existing user's custom alias.

Follow-up questions

  • How can you capture per-URL click metrics without adding latency to the redirect hot path? On origin requests that bypass the CDN, the redirect worker writes a compact event (code, timestamp, country, referrer_type) into a lock-free in-memory ring buffer and returns 302 immediately—shedding telemetry with a metric counter rather than blocking if the buffer ever saturates. Because ~90% of redirects terminate at the CDN edge, our main telemetry feed is the CDN's real-time access-log stream (with an internal X-Via-CDN header on origin misses so origin servers skip logging them, counting every click once). Downstream, events enter Kafka round-robin rather than partitioned by code, and stream workers pre-aggregate (code, minute) counts locally before flushing into an analytical database so a 500,000-click/s viral link never melts a single broker partition.
  • Suppose one celebrity post drives a massive fraction of global clicks to a single short code—how does each tier of your architecture behave? Because max-age=0 keeps browsers from caching locally, every click reaches the nearest CDN edge PoP, where request coalescing (single-flight) collapses thousands of concurrent misses into one upstream request per PoP every 60 seconds (and 1–3 origin fetches per minute behind a regional CDN origin shield). At the origin, each Redirect Server holds hot keys in its 300 MB in-process LRU cache (Least Recently Used memory cache) for 30 seconds with local single-flight, so the Redis shard owning that key sees only ~10 reads every 30 seconds per region and the database sees zero reads after the initial miss. Meanwhile, round-robin Kafka ingestion and two-stage stream aggregation shield analytics from hot-key skew, while the spike automatically queues an asynchronous malware re-scan of the destination URL.
  • What defenses would you build to detect, block, and rapidly revoke malicious or phishing destinations? Enforce preventative checks at creation time first: allow only http/https schemes, reject URLs pointing back to our own shortener domains (blocking disguised redirect chains), screen targets against live threat-intelligence feeds and newly registered domain heuristics, and apply strict per-IP and per-account token-bucket limits with verified credentials required for bulk creation. Because bad actors often swap a clean landing page for a credential harvester hours after creation (cloaking), run asynchronous headless-browser re-scans on new links, viral traffic spikes, and abuse reports. Medium-confidence flags route visitors to a warning interstitial page, whereas confirmed threats flip status = "DISABLED" (410) and broadcast on the versioned invalidation stream to purge CDN PoPs, evict server LRUs, and overwrite Redis within seconds.
  • If your storage cluster outgrows its initial partitioning layout, how do you migrate to a new sharding scheme with zero downtime? Because CDN PoPs, server LRUs, and Redis caches address entries directly by code rather than database shard ID, the 1,000,000/s redirect path stays insulated during storage migration. Run a five-phase online cutover: (1) enable dual-writes so every POST, PATCH, and DELETE updates both the legacy cluster (still authoritative) and the target cluster; (2) run a rate-limited background backfill copying historical records into the target cluster via version-guarded idempotent upserts (write only if incoming.version >= stored.version) so backfill jobs never clobber live mutations; (3) validate parity with row-count checksums and asynchronous shadow reads; (4) shift cache-miss reads gradually via feature flag (1% -> 10% -> 50% -> 100%); and (5) maintain dual-writes to the legacy cluster for a 48-hour rollback window before retiring it.

Follow-up questions

Similar questions

More Uber Freight interview questions

All 4 Uber Freight questions →