Skip to content
Chethan Yadav_
System Design

SD/Lesson 8 of 8/6 min read

Design Case Studies

Worked designs for a URL shortener, a rate limiter, a chat system, a news feed, and a notification service, with estimates, data models and the key trade-offs.


On this page

Each design follows the framework: requirements, estimates, API, high-level design, deep dive.

URL Shortener

Requirements

  • Shorten a long URL to a short code; redirect the code to the original URL.
  • Optional custom aliases and expiry. Very read-heavy.
  • Scale: 100 M new URLs per month, 100:1 read to write.

Estimates

Writes: 100M / (30 × 10^5 s) ≈ 40 per second
Reads:  ≈ 4,000 per second (peak ~10,000)
Storage: 100M × 12 months × 5 years × 500 B ≈ 3 TB

API

POST /api/urls        { "url": "https://...", "alias": "optional" }  → { "code": "aZ3k9Q" }
GET  /{code}          → 301 or 302 redirect

301 (permanent) lets browsers cache the redirect, reducing load but hiding clicks from analytics. 302 (temporary) sends every click through you. Pick by whether analytics matter.

Base62 code generation

Encode a number using [0-9a-zA-Z]. Base62 with 7 characters gives 62⁷ ≈ 3.5 trillion codes, plenty.

ApproachHowTrade-off
Hash and truncateFirst 7 chars of base62(md5(url))Collisions: check and retry with a salt
Counter + Base62Unique ID from a distributed ID generator, then encodeNo collisions; codes are guessable unless shuffled
Pre-generated keysA key service hands out batches of unused random codesFast, no collisions; extra service

High-level design

client ──▶ LB ──▶ API servers ──▶ cache (Redis: code → url)
                       │                  │ miss
                       ▼                  ▼
                 ID generator        key-value DB (code → url, created, expiry)
  • Data model is a simple key-value lookup, so a key-value or wide-column store (DynamoDB, Cassandra) fits; Postgres works fine at this size too.
  • Cache popular codes with LRU; the 80/20 rule means a small cache absorbs most reads.
  • Click analytics: publish an event to a queue on each redirect and aggregate asynchronously, keeping redirects fast.

Rate limiter

Requirements: limit each API key to N requests per window across many API servers, with low added latency.

  • Put the limiter in the API gateway or as middleware.
  • Use a token bucket or sliding window counter per key, stored in Redis. Do read-modify-write atomically with a Lua script to avoid races between servers.
  • Return 429 with X-RateLimit-Remaining and Retry-After headers.
  • If Redis is down, fail open (allow traffic) for most APIs, or fail closed for security-critical ones like login.
  • For very high traffic, keep local approximate counters and sync to Redis periodically.

Chat System

Requirements

  • One-to-one and group chat, online presence, delivery and read receipts, message history across devices.
  • Scale: 50 M daily active users, low latency delivery.

Connections

HTTP request-response does not suit server-initiated pushes. Options: long polling, Server-Sent Events, or WebSockets (full duplex, the usual choice).

client ◀═ WebSocket ═▶ chat server A ──┐
                                       ├──▶ message service ──▶ message store
client ◀═ WebSocket ═▶ chat server B ──┘          │
                                          presence / session store (Redis:
                                          user → which chat server)

Message flow

  1. Alice's client sends a message over its WebSocket to chat server A.
  2. Server A assigns a message ID (time-sortable, such as Snowflake), persists it, and acks to Alice ("sent").
  3. It looks up Bob's connection in the session store. If Bob is online on server B, the message is routed to B (via pub/sub or direct RPC) and pushed to Bob.
  4. If Bob is offline, a push notification is sent; Bob's client fetches missed messages on reconnect using its last seen message ID.

Storage

  • Huge write volume, append-only, read by conversation in time order: a wide-column store like Cassandra or HBase, partitioned by conversation_id, clustered by message_id.
  • Ordering: per-conversation sequence numbers or time-sortable IDs.
  • Presence: heartbeats update a TTL key in Redis; status changes are fanned out to friends, throttled for big friend lists.
  • Group chats: fan out to each member's connection; cap group size or switch large groups to a pull model.

News Feed

Requirements

  • Users post; each user sees a feed of posts from people they follow, newest or ranked first.
  • Scale: 300 M daily active users; feed reads vastly outnumber posts.

Fan-Out on Write

When a user posts, push the post ID into every follower's precomputed feed (a Redis list or sorted set per user).

  • Feed reads are a single fast lookup.
  • Expensive for users with millions of followers (a celebrity post means millions of writes), and wasted on inactive followers.

Fan-Out on Read

Store posts only with the author. When a user opens the feed, fetch recent posts from everyone they follow and merge them.

  • Cheap writes, always fresh.
  • Slow reads for users following many accounts.

Hybrid

Use fan-out on write for ordinary users and fan-out on read for celebrities. At read time, merge the precomputed feed with fresh posts from the few celebrities the user follows. This is how large social networks handle the celebrity problem.

post ──▶ post service ──▶ posts DB
              │
              ▼
        fan-out workers (queue) ──▶ feed cache per follower
                                          │
feed request ──▶ feed service ── merge ◀──┘ + celebrity posts + ranking

Other details: store only post IDs in feeds and hydrate content from a post cache; paginate with cursors; rank with a model asynchronously; keep media in object storage behind a CDN.

Notification Service

Requirements

  • Send push, SMS and email notifications triggered by many internal services.
  • Respect user preferences and quiet hours, avoid duplicates, handle provider outages.

Design

services ──▶ notification API ──▶ validate + preferences + templates
                                         │
                              queues per channel (push / sms / email)
                                         │
                                   channel workers ──▶ APNs / FCM / Twilio / SES
                                         │
                                  retries, DLQ, delivery log
  • Separate queues per channel so a slow SMS provider cannot block push notifications.
  • Deduplicate with an idempotency key per event and user.
  • Retry with exponential backoff; fail over between providers; route permanent failures to a DLQ.
  • Rate limit per user to avoid spamming, and batch low-priority notifications into digests.
  • Track delivery, opens and clicks in an analytics pipeline.

Common interview checklist

  • Did I state assumptions and do the numbers?
  • Where are the single points of failure, and how do I remove them?
  • What is the read/write ratio, and where do caches go?
  • What is the shard key, and where could hotspots appear?
  • What consistency does each piece of data need?
  • What happens when each dependency is slow or down?
  • How will I monitor it and know it is healthy?

Quick revision

  • URL shortener: Base62 codes from a counter or key service, key-value store, heavy caching, async analytics.
  • Rate limiter: token bucket in Redis with atomic scripts at the gateway; decide fail-open vs fail-closed.
  • Chat: WebSockets, a session store mapping users to servers, Cassandra-style storage partitioned by conversation.
  • News feed: fan-out on write for normal users, fan-out on read for celebrities, merged at read time.
  • Notifications: per-channel queues, preferences, idempotency, retries, provider failover.