Requirements


Functional Requirements:


  • Shorten URL → short link
  • Redirect short link → original URL
  • (Optional) expiration, custom alias, analytics



Non-Functional Requirements:


  • Low latency (10–50ms, read-heavy)
  • High availability (≥ 99.99%)
  • Scalable (billions URLs, high QPS)
  • Durable storage


API Design

POST /shorten { long_url, custom_alias?, expires_at? } → { short_url } GET /{short_code} → 302 redirect



High-Level Design

Client

|

CDN

|

API Gateway (LB, rate limit)

|

+----------------------+

| |

Shorten Service Redirect Service

| |

ID Generator Cache (Redis)

| |

+---------> Database (sharded)

Analytics: Kafka → OLAP DB


Detailed Component Design

4.1 ID Generation

  • Use Snowflake ID (distributed, no bottleneck)
  • Encode → Base62short_code
  • No collision

4.2 Database

urls( id BIGINT PK, short_code VARCHAR UNIQUE, long_url TEXT, created_at, expires_at )
  • Index: short_code
  • Scaling:
    • Read replicas
    • Sharding: hash(short_code) % N
    • Consistent hashing for rebalancing

4.3 Cache (Redis)

  • Key: short_code
  • Value: long_url

Strategy: Write-around (recommended)

Write: → DB only Read: → Cache miss → DB → populate cache
  • TTL (e.g., 24h)
  • Cache invalidation on update/delete

4.4 Read Flow (Optimized)

CDN (edge cache) L1: in-memory cache L2: Redis DB fallback Return 302
  • Handles high QPS efficiently

4.5 Write Flow

Validate URL Generate ID Encode Base62 Store DB Return short URL