πŸ’¬
βœ‰οΈ
πŸ“Έ
▢️

Loading…

Design a URL Shortener (TinyURL): Interactive System Design

URL ShortenerGuided Mode

Step 4 β€” Cache for Fast Redirects

URL lookups (GET /:code) are read-heavy. The same popular links get clicked thousands of times. That's identical DB queries, each round-trip.

We introduce Redis Cache between the API and the Database.

Request Flow

1

Request: GET /abc123

The Load Balancer routes the redirect request to an API Server.

2

API checks Cache first

Before touching the Database, the API checks Redis Cache: "Do you have the long URL for code abc123?"

3a

Cache HIT β€” 95% of traffic

Code found in cache β†’ return the long URL instantly. Redis Cache responds in <1ms. Database is never touched.

// Cache hit path (95% of requests)
redis.get('url:abc123')  // β†’ 'https://longurl.com'
// Total latency: ~5ms
3b

Cache MISS β€” first visit

Code not in cache β†’ query Database β†’ store result in Redis Cache β†’ redirect. Cache is populated; next visit is a hit.

// Cache miss path (5% of requests)
redis.get('url:abc123')  // β†’ null
db.query('SELECT...')    // β†’ 'https://longurl.com'
redis.set('url:abc123', 'https://...', 'EX', 86400)  // TTL: 24h

Why We Need This

URL mappings almost never change. Once created, they're read thousands of times with the same result each time β€” the perfect cache target.

With 95% cache hit rate: the Database only sees 5% of real read traffic. You effectively get 20Γ— DB capacity for free.

Key Insight

With a 95% cache hit rate, your Database only handles 5% of redirect queries. The same hardware now serves 20Γ— more traffic β€” no new servers needed.

Step 4 of 6