StackMonkey
Home / Templates / URL Shortener

URL Shortener System Design: Capacity Planning, Bottlenecks & Simulation

A complete architectural breakdown of a TinyURL / Bitly tier service handling 50,000 read QPS: Base62 key generation, 100:1 read/write traffic ratios, 80/20 cache sizing, database connection pool exhaustion, and discrete event simulation.

Peak Read Ingress
50,000 /s
100:1 Read-to-Write
Write Throughput
500 /s
500M URLs / Month
5-Year Storage
15 TB
500 Bytes / Record
Target P99 Latency
< 15 ms
80% Redis Hit Ratio
Step 1 of 4

Requirements & Capacity Planning

Production sizing starts from hard capacity constraints and storage budgets, not hand-waving. Here is the operational capacity math for 500M writes/month under skewed read traffic.

System Requirements Matrix

Functional Requirements:
  • Given a long URL, return a unique 7-character short URL (e.g., https://short.io/abc12xy).
  • When accessing a short URL, redirect users to original destination via HTTP 301 or 302.
  • Users can optionally provide custom aliases and expiration timestamps (TTL).
  • Analytics recording (clicks, referrer, geolocations) without blocking redirect latency.
301 Permanent vs 302 Temporary Redirect:

301 (Permanent): Browsers cache the redirect locally; subsequent clicks bypass your servers completely. Decreases server load by 35% but blinds click analytics.
302 (Found / Temporary): Every request hits the backend first. Mandatory if accurate billing, rate limiting, and real-time click telemetry are required.

Back-of-the-Envelope Capacity Math

Throughput Calculation
Writes: 500M / (30 days × 86,400s) ≈ 193 writes/s (Peak: 500/s)
Reads (100:1): 193 × 100 ≈ 19,300 reads/s (Peak: 50,000/s)
Storage Calculation (5 Years)
Record Size: ID (8B) + Hash (7B) + URL (450B) + TTL (16B) = 500 Bytes
5-Year Footprint: 500M × 12 × 5 × 500B = 15 Terabytes
Memory Cache (80/20 Pareto Working Set)
Daily Reads: 19,300 × 86,400s ≈ 1.67 Billion reads/day
20% Hot Working Set: 0.20 × (1.67B × 500B) ≈ 167 GB RAM (Redis Cluster)
Step 2 of 4

Key Generation Strategy: Base62 vs Distributed Range

How do you encode 64-bit integer IDs into compact URLs without hash collisions, database locks, or coordination bottlenecks?

Approach A

MD5 / SHA-256 Truncation

Compute MD5(original_url), convert to Base62, and take the first 7 characters.

Failure Mode: High collision rate as URL count scales (Birthday Paradox). Requires querying the DB to verify collision, retrying with salt, causing massive write queue stall.
Approach B

Centralized Auto-Increment ID

Store URLs in PostgreSQL with an auto-incrementing BIGSERIAL primary key. Convert integer ID to Base62.

Failure Mode: Single point of failure. Write throughput is strictly bounded by single-node database write lock contention (~3,000 writes/sec max).
Approach C · Industry Standard

Distributed Range Key Generator

ZooKeeper or Raft coordinator assigns unique blocks of 100,000 IDs to compute instances. Each worker generates IDs locally in memory without coordination.

Zero Collisions: In-memory atomic integer increment. 0 database round-trips for ID creation. Scales to 1,000,000+ writes/sec horizontally.
Base62 Capacity Proof:
Characters: [0-9, a-z, A-Z] = 10 + 26 + 26 = 62 characters.
Length 6: 62^6 = 56,800,235,584 (56.8 Billion unique URLs)
Length 7: 62^7 = 3,521,614,606,208 (3.52 Trillion unique URLs). At 500M URLs/month, length 7 lasts for over 580 years.
Step 3 of 4

Where the Naive Design Crashes Under Load

Why naive architectures fail in production: Little's Law, thread starvation, and database connection pool exhaustion.

The 50,000 QPS Direct Database Crash

Junior engineers often assume a relational database with an indexed hash column can handle 50,000 reads/sec. Queueing theory proves mathematical impossibility on single-node storage:

Little's Law: L = λ × W
Arrival Rate (λ): 50,000 requests / sec
Avg Disk Query Latency (W): 25 ms (0.025 sec)
Concurrent In-Flight Queries (L): 50,000 × 0.025 = 1,250 concurrent queries

The Cascade Sequence

  1. Connection Pool Exhaustion: Postgres default max_connections = 100 saturates in under 2ms. Subsequent queries queue in memory.
  2. Upstream Worker Lockup: Node.js event loops and Go worker routines block waiting on the DB pool, exhausting thread limits.
  3. Client Retry Storm: Edge clients time out after 150ms and trigger 3 retries, multiplying ingress load from 50k to 150k QPS.
  4. Total 504 Outage: API Gateway returns HTTP 504 Gateway Timeout across 100% of incoming traffic.
Step 4 of 4

The Resilient Production Architecture

How StackMonkey models the complete, fault-tolerant topology with edge caching, token bucket throttling, read-through Redis clusters, and async Kafka logging.

01 · Edge Anycast CDN
Cloudflare / Fastly POPs
Caches HTTP 301 redirects for top viral URLs directly in edge points of presence, shedding 20-30% of global traffic before hitting your origin.
02 · API Gateway Throttling
Token Bucket Rate Limiter
Enforces per-IP and per-token quotas (100 req/min). Drops aggressive scrapers and DDoS bursts with immediate HTTP 429 before compute exhaustion.
03 · Stateless Compute Tier
Go / Rust Microservice Pods
Stateless workers scale horizontally behind a Least Connections load balancer. Generates short Base62 hashes using local pre-allocated ID ranges.
04 · In-Memory Cache Cluster
Redis Cluster (LRU Eviction)
Serves 80% of read traffic with sub-millisecond p99 latency (0.8ms). Configured with allkeys-lru to automatically cycle out cold links.
05 · Primary-Replica Database
PostgreSQL + PgBouncer Pool
Primary handles writes (500 QPS) with WAL persistence. Read misses query 3 Read Replicas via PgBouncer connection pooling.
06 · Asynchronous Telemetry
Apache Kafka Event Stream
Click events (IP, timestamp, referrer, country) publish to Kafka asynchronously. Decouples analytics logging completely from user redirect latency.
Interactive Discrete Event Simulation

Simulate the URL Shortener Topology Live

Watch Redis absorb 80% read traffic, observe database pool saturation under cache eviction, and adjust queue depth thresholds in real-time.