Skip to main content
← CONCEPTS / SYSTEM-DESIGN
An end-to-end domain learning journey

Base62 URL Shortening
& Edge Redirection.

Base62 URL shortening maps 64-bit distributed counter IDs into compact 7-character alphanumeric codes (62^7 = 3.52T combinations), pairing collision-free writes with edge-cached HTTP 301/302 redirection.
Start the journey7 sections· Last modified Nov 24, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When traffic spikes expose hidden coupling, prefer pre-allocated ZooKeeper/Snowflake counter ranges + Base62 encoding over MD5/SHA hashing to avoid collision retries, and choose HTTP 302 over 301 whenever click analytics are required.

TL;DR30-second simplified summary
▾

Production URL shorteners pair ZooKeeper-leased counter ranges (1M IDs/block) with Feistel-permuted Base62 encoding to avoid hash collisions and enumeration. On the read path, an in-memory Bloom filter absorbs random 404 cache-penetration scans.

L1 in-process LRU caches protect Redis shards from viral hot keys, while HTTP 302 handlers push click telemetry asynchronously via bounded queues to Kafka and ClickHouse.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Consistent Hashing & Virtual Nodes
Consistent hashing assigns data keys to servers in a way that limits how many keys move when servers are added or removed. This helps avoid widespread cache misses and sudden load on databases.
Distributed Web Crawler & Mercator URL Frontier
The Mercator URL Frontier separates crawl priority (Front Queues) from per-host politeness (Back Queues) so high-priority domains are crawled fast without DDoSing any single origin server.
Full walkthrough · 7 stages
01
foundation

Base62 Encoding & Key-Space Math.

Why this matters: Calculate slug length capacity and convert 64-bit integers cleanly into URL-safe Base62 strings.

Using [0-9a-zA-Z] gives 62 characters.

A 6-char slug holds 62^6 = 56.8B URLs; a 7-char slug holds 62^7 = 3.52T URLs (over 100 years at 1,000 writes/sec).

Stage 1 - Base62 Math

64-Bit ID to 7-Char Base62 Encoder

64-Bit Counter IDsourceBase62 Div-Mod LoopprocessorFixed/Min 7-CharSlugcache3.52T Key SpacesinkMap remainders to chars

1.Obfuscation: XOR or Feistel-permute the integer ID before Base62 encoding so sequential URLs aren't enumerable.

2.Custom Aliases: Reserve a separate prefix or validation check for user-chosen vanity slugs.

Base62 encoding over integer IDs guarantees uniqueness without collision-retry loops.

02
foundation

Counter Ranges vs. Truncated Hashing Trade-offs.

Why this matters: Compare distributed counter range allocation against MD5/SHA-256 truncation.

Think of Counter Ranges vs. Truncated Hashing Trade-offs as the intuition layer for Base62 URL Shortening & Edge Redirection: Compare distributed counter range allocation against MD5/SHA-256 truncation.

Truncating MD5(long_url) to 7 chars risks birthday-paradox collisions, forcing a SELECT check (and salt-and-retry loop) on every write. Pre-allocating disjoint ID blocks (e.g., 1M IDs per worker from ZooKeeper/etcd) lets each API server generate unique Base62 slugs purely in memory with zero cross-node coordination per request.

Stage 2 - ID Generation

ZooKeeper Range-Based ID Allocator

ZooKeeper / etcdstorageWrite Worker 1processorWrite Worker 2processorCassandra /DynamoDBsinkLease next 1M block

1.Zero Hot-Spot: Workers increment atomic local counters in RAM, hitting ZooKeeper only once per 1M writes.

2.Crash Safety: Discarding unused IDs on worker crash wastes at most 1M of a 3.52T space.

Leased counter ranges eliminate per-write coordination and database collision checks.

Engineering Decision Framework
Problem
How to implement Base62 URL Shortening & Edge Redirection without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
When traffic spikes expose hidden coupling, prefer pre-allocated ZooKeeper/Snowflake counter ranges + Base62 encoding over MD5/SHA hashing to avoid collision retries, and choose HTTP 302 over 301 whenever click analytics are required.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Base62 URL Shortening & Edge Redirection experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
intermediate

HTTP 301 vs. 302 Redirection Semantics.

Why this matters: Choose the right HTTP redirect status code based on analytics, mutability, and caching needs.

Think of HTTP 301 vs. 302 Redirection Semantics as the intuition layer for Base62 URL Shortening & Edge Redirection: Choose the right HTTP redirect status code based on analytics, mutability, and caching needs.

HTTP 301 Moved Permanently tells browsers and CDNs to cache the target URL indefinitely, minimizing origin traffic but preventing click tracking and link updates. HTTP 302 Found (or 307) forces clients to hit the redirection server on every click, enabling real-time analytics, A/B routing, and instant phishing takedowns.

Stage 3 - Redirect Semantics

301 Permanent vs 302 Tracked Redirect

GET /aB9x2KqsourceHTTP 301 PermanentcacheHTTP 302 FoundrouterAsync Click EventsinkAnalytics / mutable

1.Default to 302: Modern URL shorteners default to 302 (or 307) so analytics and link edits work.

2.Cache-Control: Pair 302 with short CDN edge TTLs only when analytics can be logged at the edge.

Choosing 301 vs 302 trades origin compute savings against click visibility and mutability.

04
intermediate

Bloom Filter Guard Against Cache Penetration.

Why this matters: Protect the NoSQL database from malicious scans of non-existent short codes.

Think of Bloom Filter Guard Against Cache Penetration as the intuition layer for Base62 URL Shortening & Edge Redirection: Protect the NoSQL database from malicious scans of non-existent short codes.

If an attacker requests millions of random 7-char codes (GET /zzzz999), every lookup misses Redis and hits Cassandra/DynamoDB (cache penetration). Maintaining a compact in-memory/Redis Bloom Filter (1B keys at 1% false-positive rate takes ~1.2GB) rejects >99% of invalid codes in microseconds with 404 Not Found before touching the DB.

Stage 4 - Cache Penetration

Bloom Filter 404 Guard

Random 404 ScansourceEdge Bloom FilterrouterRedis Hot CachecacheCassandra /DynamoDBstorageMaybe exists (1% FP)

1.Negative Caching: Also cache confirmed 404s in Redis with a short 60s TTL for the 1% Bloom false positives.

2.Zero False Negatives: Bloom filters never drop valid newly created links when updated synchronously.

Bloom filters absorb random 404 floods before they can exhaust database read capacity.

05
intermediate

Read-Through Caching & Hot-Key Protection.

Why this matters: Serve viral short links at 100K+ RPS without melting a single Redis shard.

Think of Read-Through Caching & Hot-Key Protection as the intuition layer for Base62 URL Shortening & Edge Redirection: Serve viral short links at 100K+ RPS without melting a single Redis shard.

A single celebrity tweet can drive 50K RPS to one short code (hot_key), saturating a single Redis shard's network interface. Placing a tiny L1 in-process LRU cache (e.g., 10K hottest slugs with 30s TTL) inside each Edge/API node absorbs 90%+ of viral hot-key reads locally before Redis is ever touched.

Stage 5 - Hot-Key Defense

Two-Tier L1 In-Memory + L2 Redis Cache

Viral Tweet TrafficsourceL1 Process LRUcacheL2 Redis ClusterprocessorGeo NoSQL StorestorageMiss falls to Redis

1.Sub-Millisecond: L1 RAM hits resolve in <0.2ms with zero network serialization.

2.Singleflight: Use singleflight coalescing on L2/DB misses to stop cache-stampede bursts.

L1 in-memory LRU caches shield Redis shards from viral single-link traffic spikes.

06
advanced

Async Clickstream Analytics & Deduplication.

Why this matters: Capture real-time click metrics without adding latency to the 302 redirect.

The redirect handler must return HTTP 302 immediately without waiting for database inserts.

It pushes a lightweight (short_code, timestamp, ip_hash, user_agent, referrer) event to a local non-blocking ring buffer batched to Kafka.

Stage 6 - Async Analytics

Non-Blocking Kafka + Flink Clickstream

302 HandlersourceKafka Click TopicprocessorFlink AggregatorcacheClickHouseAnalyticssink1-min tumble window

1.Drop-Safe Ring Buffer: Bound the in-memory producer queue so Kafka outages never block redirects.

2.Privacy-First: Hash IPs with a daily rotating salt before emitting analytics events.

Non-blocking Kafka batching keeps click analytics completely off the redirect critical path.

07
advanced

Phishing Detection, TTL Expiration & Tombstone Cleanup.

Why this matters: Prevent abuse, expire temporary links cleanly, and reclaim storage.

URL shorteners are prime targets for phishing campaigns.

Every POST /shorten checks the target URL against Google Safe Browsing / PhishTank bloom/hash lists synchronously and queues deep async page scans.

Stage 7 - Trust & Lifecycle

Safe-Browsing Gate & TTL Compaction

POST /shortensourceSafe-Browsing CheckrouterTTL ExpirationprocessorBackgroundCompactorsinkStore with optional TTL

1.410 vs 404: Return 410 Gone for explicitly expired or banned links so crawlers de-index them.

2.Async Re-Scan: Periodically re-check top-clicked destinations in case a clean domain turns malicious.

Synchronous blocklist checks and async re-scans protect users from shortened phishing links.

Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why is Base62 encoding of pre-allocated distributed counter ranges preferred over truncating an MD5 hash of the long URL?

Recommended Learning Flow