10/10
Technical Architecture & AI Engineering · 7 min read

System Design: Global URL Shortener and Edge Redirector With Async Analytics

Architect a 10,000-redirects/sec global edge redirector with sub-20ms latency, collision-free Base62 key range leasing, 301 vs. 302 trade-offs, and ClickHouse analytics.

Why This Matters at Engineering Leadership Scale

The URL shortener remains an L6/L7 system design staple because it tests read-heavy global edge caching (100:1 read/write), lock-free distributed ID generation, HTTP caching trade-offs (301 vs. 302), celebrity hot-key spikes, and real-time phishing takedowns. In production, the exact same architecture powers branded SaaS invite links, dynamic QR routers, and email click tracking.

Core Mental Model & Architecture

Anchor capacity, keyspace, and Pareto cache math first:

  • Traffic & SLO (100:1 Read/Write): 10,000 redirects/sec peak (~300M to 864M/day), 100 writes/sec peak (~3M to 8.6M new URLs/day), <20ms global p95 redirect.
  • Base62 Keyspace Math: 7-char Base62 (0-9a-zA-Z) = 62^7 = 3.52 trillion unique codes - lasting >1,100 years at 8.6M writes/day.
  • Storage & Pareto Cache Math: 3.1B URLs/year * ~300 bytes = ~930 GB/year (~2.8 TB over 3 years). Caching the hottest 100M active URLs (~250 bytes each) needs only ~25 GB across Edge KV / regional Redis for a >95% edge cache hit rate.
  • Click Analytics Math: 500M clicks/day * 250 bytes = 125 GB/day raw (~11 TB/year compressed in ClickHouse).
ChoiceOption AOption B (Chosen)Rationale
HTTP Code301 Permanent (browser caches; misses clicks)302 Found (hits edge; analytics + instant kill)Preserves analytics & <2s phishing blocks; optional 301 for static SEO
Code AllocationMD5(url)[:7] + DB retryLeased Base62 blocks + Feistel shuffleZero collisions, zero DB lock contention, non-sequential codes
Click CountingSync Postgres UPDATEEdge waitUntil -> Kafka -> ClickHouseKeeps <15ms redirects and prevents viral row-lock meltdowns

Step-by-Step Implementation Tutorial

1. Architect Global Edge Redirects and Range-Leasing Writes

Serve reads at 300+ global Edge PoPs so users avoid 180ms cross-ocean hops.

text
WRITES (100 QPS, Zero Collisions):
API Gateway -> Pop ID from leased 10k block -> 42-bit Feistel shuffle -> 7-char Base62
  -> Partitioned Postgres + Edge KV + Async Phishing/Safe-Browsing Scanner

READS (10k QPS, <20ms p95):
Edge PoP Worker -> L1 RAM -> Edge KV (>95% hit) [Miss -> Regional Redis -> Postgres Replica]
  -> If `BLOCKED` return HTTP 451; else return `HTTP 302` IMMEDIATELY
  -> `ctx.waitUntil()`: Async click event -> Kafka -> ClickHouse

2. Implement Range Leasing SQL and Non-Blocking Edge Worker

Updating the allocator once per 10,000 IDs eliminates write contention completely.

sql
-- Atomic 10,000-ID Lease per App Pod (Zero Per-Write Contention)
UPDATE key_range_allocator SET next_id = next_id + 10000 WHERE shard_id = $1
RETURNING next_id - 10000 AS range_start, next_id - 1 AS range_end;

CREATE TABLE short_urls (
  short_code  VARCHAR(10) PRIMARY KEY,
  tenant_id   UUID NOT NULL,
  long_url    TEXT NOT NULL,
  status      TEXT NOT NULL DEFAULT 'ACTIVE' CHECK (status IN ('ACTIVE', 'BLOCKED', 'EXPIRED')),
  created_at  TIMESTAMPTZ NOT NULL DEFAULT NOW()
) PARTITION BY HASH (short_code);
typescript
export default {
  async fetch(req: Request, env: { URL_KV: KVNamespace; CLICK_API: string }, ctx: ExecutionContext) {
    const code = new URL(req.url).pathname.slice(1);
    if (!/^[0-9a-zA-Z]{6,10}$/.test(code)) return new Response("Not Found", { status: 404 });

    const rec = await env.URL_KV.get<{ url: string; status: string; tenantId: string }>(code, "json");
    if (!rec) return new Response("Not Found", { status: 404 });
    if (rec.status === "BLOCKED") return new Response("Blocked for safety.", { status: 451 });

    ctx.waitUntil(
      fetch(env.CLICK_API, {
        method: "POST",
        body: JSON.stringify({ code, tenantId: rec.tenantId, country: req.headers.get("CF-IPCountry"), ts: Date.now() }),
      }).catch(() => {})
    );
    return Response.redirect(rec.url, 302);
  },
};

3. Handle the Minute-25 Curveball: 200k-QPS Celebrity Link + 10k Phishing Attack

"A celebrity posts one short link hitting 200,000 redirects/sec (20x global normal on ONE key), AND an attacker creates 10,000 phishing links on your free tier."

  1. 200,000-QPS Single Hot Key: Global Edge PoPs serve the link directly out of local L1 PoP RAM (cacheTtl: 60s), spreading 200k QPS across 300+ PoPs (~650 QPS/PoP). Zero requests reach origin Redis or Postgres, while Kafka smoothly buffers batched click events into ClickHouse.
  2. 10,000 Phishing Links: Enforce strict free-tier write rate limits plus async Safe Browsing / heuristic scanning. Because redirects default to 302, flagging a link or abusive tenant_id marks status = 'BLOCKED' in Postgres and pushes a global Edge KV purge in <2 seconds, replacing redirects with an HTTP 451 warning page immediately.

4. Split Multi-Squad Ownership

  • Edge Routing & Trust/Safety Squad (5 engineers): Owns Edge Workers/KV, regional Redis/Postgres, Base62 range leasing, custom domains/TLS, and automated phishing takedowns.
  • Click Analytics & Portal Squad (5 engineers): Owns Kafka click ingestion, bot filtering, ClickHouse real-time rollups (country, referrer, device), and customer campaign dashboards.

Worked Production Scenario: Before vs. After

A marketing SaaS served redirects from a single US-East Express + Postgres app running synchronous UPDATE short_urls SET clicks = clicks + 1. One 8,000-QPS viral link locked a single Postgres row, pushing global redirect latency to 3.2s with 18% HTTP 504 timeouts. Moving to Edge Workers + KV, Base62 range leasing, and async Kafka-to-ClickHouse rollups dropped global latency to 14ms even at 200k QPS.

MetricBefore (Origin Postgres + Sync Count)After (Global Edge KV + ClickHouse)Net Impact
Global Redirect p95 Latency420ms normal / 3.2s viral14ms globally (even at 200k QPS)30x to 200x faster
Origin DB Load on Viral Link100% CPU (row-lock meltdown)<2% CPU (99.9% edge hit)Zero viral outages
Write Collision Retries1.8% under concurrent writes0% (leased Base62 ranges)Predictable writes
Phishing Takedown SpeedHours (301 browser cache)<2 seconds (302 + KV purge)Rapid safety control

Common Failure Modes & Anti-Patterns

1. Exposing Sequential Predictable Codes

The trap: Base62-encoding raw counters (10001, 10002) lets attackers enumerate private invite links and scrape competitor volume. The structural fix: Scramble leased integers through a bijective Feistel cipher before Base62 encoding: 100% collision-free yet non-guessable.

2. Counting Clicks Synchronously in Postgres

The trap: Updating a clicks column inside the redirect handler causes hot-row lock contention that crashes Postgres on viral links. The structural fix: Keep redirects read-only against Edge KV and stream clicks asynchronously into ClickHouse.

3. Defaulting to HTTP 301 When You Need Analytics or Kill-Switches

The trap: Browsers cache 301 permanently, hiding repeat clicks and preventing rapid phishing link takedowns. The structural fix: Default to 302 Found with edge-only caching (Cache-Control: private, no-store to browsers).

How to Handle Pushback in the Room

Growth / SEO Lead: "Our SEO agency wants 301 redirects for link equity instead of 302."

Calm Executive Response: "302 gives customers accurate click analytics, editable QR destinations, and sub-2-second phishing takedowns. For static SEO vanity domains that explicitly opt out of repeat-click analytics and edits, we expose a per-link redirect_type: 301 | 302 API option."

Backend Engineer: "If a pod crashes halfway through its leased block of 10,000 IDs, we waste up to 9,999 short codes. Isn't that leaky?"

Calm Executive Response: "7-char Base62 provides 3.52 trillion codes. Even if 100 pods crashed daily throwing away 10,000 IDs each, we would burn under 0.0001% of our keyspace over a decade - an easy trade for zero lock contention and zero collision retries."

Key Takeaways & This Week's Action Rep

  • Lease Base62 ranges + Feistel shuffle: Eliminate write collisions and sequential enumeration simultaneously.
  • Terminate 95%+ of redirects at Edge KV: Deliver <20ms globally and absorb 200k-QPS hot keys with zero origin load.
  • Stream click analytics asynchronously: Never lock Postgres rows on redirect; aggregate in ClickHouse via Kafka.
  • Default to 302 for analytics and safety: Enable sub-2-second global phishing takedowns.
  • This Week's Action Rep: Run a 45-minute timed walkthrough of this URL shortener out loud, finishing the 62^7 keyspace and 25 GB Pareto cache math before Minute 8 and handling the 200k-QPS hot-key + phishing curveballs smoothly.