Designing a URL shortener requires handling high read-to-write ratios (100:1) with sub-10ms redirection latencies.
1. Short Key Generation: Base62 Encoding
Convert an auto-incrementing 64-bit integer ID into a 7-character string using Base62 ([a-z, A-Z, 0-9]): $62^7 \approx 3.52 \text{ trillion unique URLs}$
2. Preventing Counter Bottlenecks
Instead of hitting a central DB counter per request, pre-allocate ranges of IDs (e.g. Node 1 gets IDs 1–1,000,000, Node 2 gets 1,000,001–2,000,000) to key generator instances.
3. Redirection Flow & Caching
- HTTP 301 (Permanent Redirect): Browser caches redirection locally. Reduces server load, but hides click analytics.
- HTTP 302 (Found / Temporary): Every click hits the URL shortener service, updating analytics counters while reading destination URLs from Redis.
Cache the top 20% hottest destination URLs in Redis to achieve 99% read cache hit ratios.
Key Architectural Comparison
| Redirection Strategy | Browser Caching Behavior | Analytics Capture Accuracy | Server Load Impact |
|---|---|---|---|
| HTTP 301 Moved Permanently | Browser caches destination URL permanently. | Poor (Cached clicks bypass URL shortener). | Lowest (Reduces server traffic by 80%). |
| HTTP 302 Found (Temporary) | Browser queries URL shortener on every click. | 100% Exact click count and telemetry. | Moderate (Every click hits shortener backend). |