Design Distributed High-Throughput URL Shortener (Bitly / TinyURL)
Design a high-availability URL shortening service capable of sub-10ms redirection latency using Base62 encoding, distributed unique ID.
Design Distributed High-Throughput URL Shortener (Bitly / TinyURL): Request Topology
4 Stages · 4 Sizing BenchmarksRequest traversal order for Design Distributed High-Throughput URL Shortener (Bitly / TinyURL) (Distributed Systems) under target workload 500M Links Created/Month • 100 Billion Redirects/Month • 100k QPS:
Distributed ID Generator (Snowflake)
Base62 Encoding Module
Multi-Tier Cache (Redis Cluster)
Distributed NoSQL / SQL Store
Functional Requirements
- •Generate unique 7-character short URL from long URL
- •Redirect short URL (301 / 302 redirect) to long destination
- •Custom aliases and click analytics
Non-Functional Requirements
- •99.999% availability
- •Ultra-low redirection latency (<10ms)
- •Zero hash collisions
Capacity & Scale Estimation (Back-of-the-Envelope Math)
Open Live CalculatorEstimate Custom QPS & Storage Growth Live
Calculate bandwidth ingress, 80/20 RAM cache sizing, and multi-year storage growth using our interactive developer utility.
System Topology & Core Architectural Components
+---------------------------------------------------------------------------------------------------+
| [CLIENT WEB / MOBILE] Short URL Redirect Request (e.g. https://helloaihub.tech/s/aB9z1) |
+-------------------------------------------------+-------------------------------------------------+
|
v
+-------------------------------------------------+-------------------------------------------------+
| [EDGE CACHE] Cloudflare Edge Network (HTTP 301 Permanent Redirect on Cache Hit < 5ms) |
+-------------------------------------------------+-------------------------------------------------+
| (Cache Miss)
v
+-------------------------------------------------+-------------------------------------------------+
| [LINK RESOLVER SERVICE] In-Memory Redis Cluster (Top 20% URLs Cached via LRU Policy) |
+-------------------------------------------------+-------------------------------------------------+
| (Cold URL)
v
+-------------------------------------------------+-------------------------------------------------+
| [PERSISTENCE LAYER] Sharded PostgreSQL / DynamoDB (Key: ShortCode, Value: LongURL, CreatedAt) |
+---------------------------------------------------------------------------------------------------+1Distributed ID Generator (Snowflake)
Generates 64-bit globally unique sequential IDs without database coordination using timestamp + worker ID + sequence bits.
2Base62 Encoding Module
Converts numeric 64-bit ID into a 7-character Base62 string (62^7 = 3.52 Trillion unique URLs).
3Multi-Tier Cache (Redis Cluster)
Caches the top 20% most frequently accessed URLs (80/20 rule) in RAM to serve 95%+ of redirects in <2ms.
4Distributed NoSQL / SQL Store
DynamoDB / PostgreSQL partitioned by ShortKey for permanent URL mapping persistence.
Architectural Trade-Off Analysis & CAP Constraints
Trade-Off Decision MatrixEngineering a resilient architecture for Design Distributed High-Throughput URL Shortener (Bitly / TinyURL) at a scale of 500M Links Created/Month • 100 Billion Redirects/Month • 100k QPS requires deliberate trade-offs across data consistency, replication latency, network partition tolerance, and storage economics:
| Dimension | Selected Strategy | Alternative Evaluated | Trade-Off Rationale & Latency Impact |
|---|---|---|---|
| CAP Theorem Posture | AP (High Availability with Eventual Consistency) | CP (Strict Consistency) | Link redirection represents 99% of system traffic and must complete in sub-5ms globally; a 500ms cross-region write sync delay is imperceptible. |
| ID Generation Mechanism | Snowflake 64-Bit Distributed Generator | Auto-Incrementing Database Sequence | Eliminates database write bottlenecks and prevents competitors from calculating link creation velocity through predictable sequential IDs. |
| Encoding Scheme | Bijective Base62 Encoding (a-z, A-Z, 0-9) | MD5 / SHA-256 Hash Truncation | Guarantees 100% collision-free short codes without requiring expensive database check-and-retry loops for collision resolution. |
| HTTP Redirect Status Code | HTTP 302 Found (or 301 with Short TTL) | Permanent HTTP 301 without Headers | Allows server to track click analytics and geolocation metrics while preventing aggressive client browsers from caching redirected URLs permanently. |
Fault Tolerance, High Availability & Failure Mode Analysis
Operating at 500M Links Created/Month • 100 Billion Redirects/Month • 100k QPS demands proactive defenses against cascading outages. The blueprint specifies four critical failure modes and remediation protocols tailored to Design Distributed High-Throughput URL Shortener (Bitly / TinyURL):
1. Snowflake Generator Clock Drift / Skew
Blast Radius: Server system time rolls backwards, causing ID collisions across worker nodes.
Remediation Protocol: Node rejects ID generation and waits for clock synchronization if delta exceeds 10 milliseconds.
2. Viral Link Cache Stampede (Thundering Herd)
Blast Radius: A viral link with 100,000 req/sec expires from Redis, swamping primary PostgreSQL.
Remediation Protocol: Probabilistic early expiration (XFetch algorithm) refreshes the cache entry 10 seconds before TTL expiration.
3. Malicious Phishing / Malware URL Insertion
Blast Radius: Bad actors utilize the shortener to cloak dangerous phishing links.
Remediation Protocol: Asynchronous safety workers scan target destinations against Google Safe Browsing API, blocking malicious short links.
4. Database Hot Shard Key Skew
Blast Radius: A single database partition receives 80% of redirect reads for top global brand links.
Remediation Protocol: Virtual read replicas and localized edge CDN caching absorb all read traffic, shielding primary database shards.
Production Algorithm Implementation: Bijective Base62 Integer to Short Code Converter
TypeScriptHigh-scale distributed systems rely on atomic synchronization primitives to enforce SLA boundaries. Below is the production implementation for Design Distributed High-Throughput URL Shortener (Bitly / TinyURL):
// Bijective Base62 Encoder & Decoder
const ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
const BASE = BigInt(ALPHABET.length);
export function encodeIdToBase62(num: bigint): string {
let str = '';
let n = num;
while (n > 0n) {
str = ALPHABET[Number(n % BASE)] + str;
n = n / BASE;
}
return str.padStart(7, '0');
}
export function decodeBase62ToId(str: string): bigint {
let num = 0n;
for (let i = 0; i < str.length; i++) {
const idx = BigInt(ALPHABET.indexOf(str[i]));
num = num * BASE + idx;
}
return num;
}Design Distributed High-Throughput URL Shortener (Bitly / TinyURL): Design Scope & Constraints Summary
This senior / staff blueprint balances 3 core functional workflows against 3 availability and latency constraints tailored for 500M Links Created/Month • 100 Billion Redirects/Month • 100k QPS. Review the FAQ trade-offs below to compare partitioning keys, replication topology, and failure isolation specific to Distributed Systems.
Architectural FAQs & Interview Deep Dives
1Why combine a Snowflake 64-bit ID generator with Base62 encoding instead of truncating MD5 or SHA-256 hashes?
Truncating a cryptographic hash to 7 Base62 characters introduces birthday-paradox collisions as stored links scale into the billions, forcing every write to query the database, verify whether the long URL differs, and re-salt on conflict. A distributed Snowflake generator produces strictly unique 64-bit integers locally across workers with zero coordination, mapping deterministically into 7-character Base62 codes (62^7 = 3.52 trillion keys).
2How do you prevent competitors or scrapers from enumerating sequential Snowflake-derived short URLs?
Raw monotonic IDs produce contiguous Base62 strings that leak creation volume and allow brute-force crawling. Passing the generated 64-bit integer through a reversible 42-bit Feistel network permutation (or XORing with a secret bitmask before Base62 conversion) scrambles consecutive outputs into pseudo-random tokens while preserving a 1-to-1 bijection with zero collision risk.
3What protects the database at 100k peak QPS against cache stampedes on viral links and random 404 probes?
Viral redirects use singleflight request coalescing at the application tier so thousands of simultaneous cache misses collapse into a single DynamoDB or PostgreSQL lookup before repopulating Redis. To stop cache-penetration attacks probing non-existent codes, each edge node maintains a compact in-memory Bloom filter (plus short-TTL negative caching for misses) to reject invalid keys in microseconds.
4What is the operational trade-off between serving HTTP 301 versus HTTP 302 redirects?
Returning `301 Moved Permanently` instructs browsers and CDN edge nodes to cache the target URL locally, slashing origin read QPS and improving repeat redirect latency, but blinds server-side click analytics and makes link revocation impossible until client caches expire. Returning `302 Found` ensures every click hits the redirect tier for real-time telemetry, geo-routing, and expiration enforcement at the cost of higher origin bandwidth.