system design

System Design: URL Shortener

Design a URL shortener like bit.ly — storage, encoding, caching, analytics.

System Design: URL Shortener

The Problem

Design a URL shortening service like bit.ly. It should generate short URLs, redirect to the original, and track click analytics. Scale: 100M URLs created/month, 10B redirects/month.

API

POST /api/shorten  { "url": "https://..." }  → { "short": "https://short.ly/abc123" }
GET  /abc123       → 301 redirect to original URL
GET  /api/analytics/abc123  → { "clicks": 12345, "by_country": {...} }

Key Design Decisions

Short Code Generation

  • Base62 encoding of an auto-incrementing counter: 0-9, a-z, A-Z → 62^7 = 3.5 trillion unique codes
  • Pre-generate codes in batches to avoid DB bottleneck
  • Check uniqueness via database unique constraint
  • Storage

  • Postgres for URL mappings (short_code → original_url, created_at, user_id)
  • Redis for caching hot URLs (90% of redirects hit 10% of URLs)
  • Redirect Flow

    Request → Load Balancer → App Server → Redis cache check
                                              ↓ miss
                                           Postgres lookup → cache result → 301 redirect

    Analytics

  • Log clicks to Kafka → aggregate hourly in a batch job → store in analytics table
  • Don't query the click log directly (too large)
  • Scale Numbers

  • 100M URLs/month = ~40 URL creates/second
  • 10B redirects/month = ~4000 redirects/second → Redis easily handles this
  • Your design notes

    Work through this problem yourself before reading the walkthrough above. Your notes are stored locally and not submitted anywhere — only sent to the AI when you click Review.