FullStack AI Hub
Studio
System Design · 09. Whole Systems
11 min
10 steps
Beginner

Design a URL Shortener

Engineer a 100K redirect/sec link service using Base62 keyspace math, collision-free KGS blocks, Redis hot caching, and async click analytics.

System Design09. Whole SystemsLesson 3 of 4
11 minBeginner10 steps

Design a URL Shortener

Engineer a 100K redirect/sec link service using Base62 keyspace math, collision-free KGS blocks, Redis hot caching, and async click analytics.

REDIRECT PEAK
100K/s
CREATE PEAK
1,000/s
READ : WRITE
100 : 1
5-YR STORAGE
3.0 TB
100:1 R/WEdge LB40%GET vs POSTRedirectTier48%100K peakShorten Tier18%1K peakURL Store34%5-Year Sizing EstimateTotal Links100M/mo × 60 = 6B linksRow Size500 B × 6B ≈ 3.0 TBHot Set (5%)150 GB fits in Redis RAM
redirect lookup (GET)
shorten write (POST)
fast 302 cache hit
async click stream / retry
KGS key lease / TTL sweep
hash collision / drop
In This LessonStep 1 of 10
What You Will Master
  • ✓Size a 100:1 read-heavy URL shortener for 100K redirects/s, 1K creates/s, and 5-year storage
  • ✓Calculate 7-char Base62 keyspace (3.52T keys) and replace hash retries with a dedicated KGS
  • ✓Choose between HTTP 301 vs 302 redirects and absorb 92%+ of clicks with Edge PoPs and Redis LRU
  • ✓Scale storage across hash-sharded KV nodes and decouple viral click counters via Kafka and OLAP

Architectural Trade-Off Comparison Matrix

PatternBest ForKey Trade-Off
Base62 + Dedicated KGSHigh-throughput short link creation with O(1) RAM minting, zero collisions, and unpredictable keysRequires a standby KGS and pre-populated unused-keys database
HTTP 301 vs 302 Redirect301 minimizes origin load via browser caching; 302 gives 100% accurate analytics & instant link edits301 blinds analytics on repeat clicks and cannot easily revoke abusive links
Edge PoPs + Redis LRU CacheZipfian viral link skew where the top 5% of links drive 92%+ of 100K redirects/sec in < 10 msMust publish cache invalidation whenever a link is edited or flagged for abuse
Async Kafka → ClickHouse AnalyticsRecording geo, referrer, and click totals without creating row-lock hotspots on viral linksAnalytics dashboards trail real-time clicks by ~5 seconds

Step-by-Step Architectural Breakdown (10 Steps)

Full architectural walkthrough transcript and state transitions for Design a URL Shortener.

STEP 01 · SETUPJump to step →

The 100:1 read-heavy workload profile

At `100M new URLs/month` (`~1,000 creates/s` burst) and `10B redirects/month` (`~100,000 redirects/s` peak), a URL shortener is **100:1 read-heavy**.

At `500 bytes` per record, 5 years of links (`6B URLs`) needs only `3.0 TB`—so your real challenge is **sub-20 ms redirect latency** and **collision-free ID minting**, not raw disk capacity.

idea:Writes need uniqueness and durability (1K rps); reads need ultra-fast global fan-out (100K rps)—separate both tiers from step one.

100:1 Read SkewCapacity EstimationRead/Write Separation
STEP 02 · PROBLEMJump to step →

Why single-DB auto-increment breaks at scale

A naive MVP inserts each link into one Postgres table with `SERIAL PRIMARY KEY` (`10001, 10002, 10003...`).

Two fatal flaws hit immediately: one sequence master becomes a multi-region **write SPOF**, and sequential IDs let scrapers enumerate private links and spy on your exact daily link creation rate.

watch:Predictable sequential URLs (`/a1B2` → `/a1B3`) leak private shared documents and expose your daily business growth to competitors.

Sequence ContentionURL Enumeration RiskWrite SPOF
STEP 03 · TECHNIQUEJump to step →

Base62 math: why 7 characters = 3.52 trillion URLs

URL-safe alphanumeric symbols give us **62 characters**: `0–9` (10), `a–z` (26), and `A–Z` (26). We skip `+`, `/`, and `=` from Base64 so links never break inside emails or SMS.

At length 6, `62^6 = 56.8B` keys; at length 7, **`62^7 = 3.52 trillion` keys**! Even creating `1,000 links/sec` nonstop, 7 characters last **111 years**.

good:7 Base62 characters hit the ideal balance: compact for QR codes and SMS, yet 580× larger than our entire 5-year target of 6B links.

Base62 EncodingKeyspace MathURL-Safe Symbols
STEP 04 · PROBLEMJump to step →

Why truncating MD5 / SHA-256 forces DB retries

Hashing the long URL with `SHA-256` and slicing the first 7 Base62 characters looks stateless—until billions of links accumulate and truncated prefixes begin **colliding**.

Every write now needs a **read-before-write** DB check (plus a salt-and-retry loop on conflict), doubling write latency and hammering the unique index.

watch:Even with a Bloom Filter in front, hash truncation turns every create into a check-then-insert loop under unique-index contention.

Hash TruncationBirthday ParadoxRead-Before-Write Overhead
STEP 05 · SOLUTIONJump to step →

Zero collisions: dedicated Key Generation Service (KGS)

Generate shuffled 7-char Base62 keys **offline** in a dedicated **Key Generation Service (KGS)** backed by an `Unused Keys DB`.

Each aligned API server leases a disjoint block of `10,000 keys` into local RAM. Shortening a URL becomes an `O(1)` lock-free RAM `pop()`—**zero collisions, zero DB retries, and unpredictable links!**

good:If an API node crashes mid-block, you simply discard its remaining unused RAM keys—losing 4,000 out of 3.52 trillion keys is completely negligible.

Key Generation Service (KGS)Pre-Allocated RAM BlocksCollision-Free Writes
STEP 06 · TRADE-OFFJump to step →

HTTP 301 Permanent vs 302 Found: speed vs analytics

Returning **`301 Moved Permanently`** lets browsers cache the destination locally—cutting origin load for repeat visits, **but blinding click analytics** and blocking link edits or malware takedowns.

Returning **`302 Found`** routes every click through your fast redirect edge so click counters stay 100% accurate and phishing links can be revoked instantly.

idea:Default to 302 when click analytics, A/B targets, or link moderation matter—pair it with Redis caching so every redirect still finishes under 10 ms.

HTTP 301 vs 302Browser Cache Trade-OffClick Attribution
STEP 07 · SOLUTIONJump to step →

Absorb 92% of 100K redirects/s with Edge & Redis

Short links follow extreme Zipfian skew: the hottest **5%** of links generate **92%+** of all clicks. Serving 100K reads/s from disk would flatten your database.

Place a **Redis LRU Cluster** (`150 GB` holds 300M hot links) behind regional **Edge PoPs**. Cache hits answer in `< 8 ms`, shrinking database load from `100K/s` down to `8K/s`.

good:LRU eviction keeps viral links hot automatically; publish an instant cache-delete message whenever a link is edited or banned.

Zipfian Read SkewRedis LRU CacheCache Invalidation
STEP 08 · TECHNIQUEJump to step →

Sharded KV store, custom aliases & lazy TTL expiry

Since 99% of database lookups are exact point reads (`short_code → long_url`) with zero joins, a hash-sharded KV store (`DynamoDB` / `Cassandra`) partitioned by `hash(short_code)` scales effortlessly across aligned shards.

Custom vanity aliases (`/launch-2026`) share the same primary keyspace. For link expiration, check `expires_at` **lazily on read** (`410 Gone`) and let a quiet background compactor reclaim expired rows overnight.

idea:Lazy expiry avoids scanning 6 billion rows every minute—expired links return 410 Gone immediately while nightly compaction frees disk.

Hash PartitioningCustom Vanity AliasesLazy TTL Expiration
STEP 09 · SOLUTIONJump to step →

Non-blocking click analytics via Kafka & OLAP

Never run `UPDATE urls SET clicks = clicks + 1` inside the redirect hot path! A viral link taking `20,000 clicks/sec` creates a catastrophic single-row lock hotspot.

Instead, fire-and-forget compact click events `{code, ts, geo, device}` to **Kafka**. Stream aggregators collapse 10-second windows in memory and flush 100:1 batched inserts into **ClickHouse OLAP**.

watch:Synchronous counter updates turn viral clicks into a DB outage—async Kafka batching keeps redirect overhead below 0.5 ms.

Async TelemetryHot-Row Lock AvoidanceWindowed OLAP Aggregation
STEP 10 · RECAPJump to step →

Production URL Shortener: 100K redirects/s end-to-end

Every layer clicks together: **Edge Rate Limit + Malware Filter** shields abuse, **Redirect Fleet + Redis LRU** answers 92% of clicks in `8 ms`, **KGS** leases collision-free 7-char Base62 blocks in RAM, **Sharded KV** stores 6B links cleanly, and **Kafka → ClickHouse** computes live analytics asynchronously.

good:Interview Gold Checklist: 100:1 read skew · 62^7 = 3.52T keys · KGS RAM blocks · 302 + Redis LRU (92% hit) · Sharded KV · Lazy TTL · Kafka → OLAP clicks.

Full URL ShortenerEdge Rate LimitingEnd-to-End Resilience

Related Production Deep-Dives & Simulators

Included In Free Course
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.