System Design Fundamentals

Lesson 12 of 12 · 24 min

x
100%

Case Study: Design a URL Shortener

URL shorteners receive a long URL, generate a short code, and redirect users. It sounds trivial but the production version touches almost every system design concept: write throughput, read throughput 100× higher, caching, database choice, collision handling, and analytics at scale. Scale estimate: 100M URLs shortened per day = ~1,200 writes/sec. Redirects at 10:1 read ratio = 12,000 reads/sec, each must complete under 10ms. Design: Postgres handles writes. A Redis cache serves the top 20% of codes that account for 80% of traffic (Pareto distribution). The short code is base62 of a database counter — no hash collisions. Analytics events go to Kafka and are processed asynchronously, never in the redirect critical path.

Before
Naive — everything synchronous in the redirect
async function redirect(shortCode: string) {
  const url = await db.query(           // 20ms
    'SELECT long_url FROM urls WHERE code = $1',
    [shortCode]
  );
  await analytics.record(shortCode);    // 50ms — blocks!
  await db.query(                       // 10ms
    'UPDATE urls SET clicks = clicks + 1 ...',
    [shortCode]
  );
  return redirect(url.long_url);        // total: ~80ms
}
After
Production — fast path + async analytics
async function redirect(shortCode: string) {
  // 1. Redis first — ~0.5ms on hit (80% of traffic)
  const cached = await redis.get(`url:${shortCode}`);
  if (cached) {
    kafka.publish('redirect', { shortCode }); // fire & forget
    return redirect(cached);  // total: ~1ms
  }

  // 2. Cache miss — read DB, then cache it
  const { long_url } = await db.query(...); // 20ms
  await redis.setex(`url:${shortCode}`, 86400, long_url);
  kafka.publish('redirect', { shortCode });  // fire & forget
  return redirect(long_url); // total: ~25ms on miss
}
// Kafka consumer batch-updates click counts — off critical path

Key Takeaway

Every case study is the same lesson: separate the hot read path, cache aggressively, and push analytics off the critical path.