Skip to content

Classic Designs (SDE-1 Level)

These are the “textbook” HLD questions. At SDE-1, nobody expects a perfect design — they expect you to run the framework and hit the main talking points. Each design below fits a 30–40 minute round.


Requirements

  • Functional: create short URL for long URL; redirect short → long; optional custom alias, expiry; basic click count.
  • Non-functional: very read-heavy (100:1), redirects must be fast (<50 ms), highly available, short codes unique.

Estimate: 1M new URLs/day ≈ 12 writes/s; 100M redirects/day ≈ 1,200 reads/s. 5 years × 365M ≈ 2B URLs × ~500 B ≈ 1 TB. A 7-char base62 code gives 62^7 ≈ 3.5 trillion — plenty.

API

POST /api/urls { longUrl, customAlias?, expiresAt? } -> { shortUrl }
GET /:code -> 301/302 redirect to longUrl

Schema

urls(code PK, long_url, user_id, created_at, expires_at)
clicks(code, ts, country, referrer) -- or aggregated counters

Diagram

Client ──▶ CDN/LB ──▶ API servers ──▶ Redis cache (code → longUrl)
│ │ miss
│ ▼
│ Postgres / KV store
└──▶ queue ──▶ analytics worker (click counts)

Talking points

  • Code generation: (a) base62-encode an auto-increment ID / ID range per server — no collisions, but guessable; (b) random 7 chars + check uniqueness (retry on collision); (c) hash of URL — same URL gives same code, but must handle collisions. Option (a) with pre-allocated ranges is the clean answer.
  • 301 vs 302: 301 is cached by browsers (less load, but you lose click analytics); 302 hits you every time.
  • Cache hot codes in Redis (LRU); most traffic goes to a small set of URLs.
  • Analytics async — don’t slow the redirect; push click events to a queue.

Requirements

  • Functional: limit requests per user/IP/API key (e.g. 100/min); return 429 when exceeded; different limits per plan/endpoint.
  • Non-functional: very low added latency (<5 ms), works across many servers, fails open (if the limiter is down, don’t block all traffic) — state that choice explicitly.

Where it lives: API gateway / middleware before the handler (Express middleware, Hono middleware, Cloudflare rate limiting rules).

Diagram

Client ──▶ LB ──▶ API server ──[rate-limit middleware]──▶ handler
│
▼
Redis (shared counters)

Algorithm — token bucket (say this one)

key = "rl:{userId}"
tokens, last = redis.get(key)
tokens = min(capacity, tokens + (now - last) * refillRate)
if tokens < 1: return 429 (Retry-After)
tokens -= 1; redis.set(key, tokens, now)

Run it as a Redis Lua script so read-modify-write is atomic across servers.

Simpler alternative — fixed window: INCR rl:{user}:{minute} + EXPIRE 60; if > limit → 429.

Talking points

  • Compare algorithms: fixed window (edge burst), sliding window (accurate), token bucket (allows bursts, smooth average).
  • Response headers: X-RateLimit-Limit, X-RateLimit-Remaining, Retry-After.
  • Key choice: user ID for logged-in users, IP for anonymous (beware shared NAT IPs — common on Indian mobile networks).
  • Local in-memory pre-check + Redis for global accuracy if latency matters.

Requirements

  • Functional: 1:1 and small group chat, online status, message history, delivered/read receipts.
  • Non-functional: low latency delivery, messages never lost, ordered within a conversation.

API / protocol

WebSocket /ws (auth with token on connect)
→ { type: "send", conversationId, clientMsgId, text }
← { type: "message", ... } / { type: "ack", clientMsgId, serverMsgId }
GET /api/conversations/:id/messages?before=cursor (history)

Schema

conversations(id, type, created_at)
participants(conversation_id, user_id, last_read_msg_id)
messages(id, conversation_id, sender_id, body, created_at)
INDEX (conversation_id, id DESC)

Diagram

User A ══WS══▶ Chat server 1 ──┐ ┌── Chat server 2 ◀══WS══ User B
▼ ▼
┌───────────────────────────┐
│ Redis pub/sub │ + presence: user → server
└───────────────────────────┘
▼
Messages DB (Postgres / Cassandra at huge scale)
│
offline? ──▶ push notification service (FCM/APNs)

Talking points

  • Flow: A sends → server persists first, then acks A, then publishes to B’s server via pub/sub → pushed to B. If B offline → push notification; B fetches history on reconnect.
  • clientMsgId for idempotency: resending after a flaky network doesn’t duplicate.
  • Ordering: per-conversation increasing IDs (or timestamps + ID); ordering across conversations doesn’t matter.
  • Scaling WebSockets: stateful connections → pub/sub between servers (same as Vigil’s Socket.io Redis adapter), heartbeats for presence.

Requirements

  • Functional: send notifications via in-app, email, SMS, push; triggered by events (new application, quest completed); user preferences / opt-out; templates.
  • Non-functional: reliable (retries), no duplicates, handle spikes (bulk campaigns), respect provider rate limits.

API

POST /internal/notify { userId, type, data, idempotencyKey }
GET /api/notifications?cursor=... (in-app inbox)
PATCH /api/notifications/:id/read
PUT /api/notification-preferences

Schema

notifications(id, user_id, type, payload, channel, status, created_at, read_at)
UNIQUE (idempotency_key)
preferences(user_id, type, channel, enabled)
templates(type, channel, subject, body)

Diagram

Services (jobs, quests, payments)
│ event
▼
Notification API ──▶ check preferences + render template ──▶ one queue per channel
│ │ │
email q sms q push q
▼ ▼ ▼
workers (retry, backoff, DLQ)
▼ ▼ ▼
SES/ SMS FCM/
Resend gateway APNs
│
delivery webhooks → update status

Talking points

  • Separate queue per channel so a slow SMS provider doesn’t block emails.
  • Idempotency key per (event, user, channel) — same as Seqtto’s offer-letter dedup.
  • Priority: OTPs/transactional > marketing (separate high-priority queue).
  • In-app notifications: store in DB + push live via WebSocket/SSE; unread count cached.

5. File Upload Service (Google Drive-lite)

Section titled “5. File Upload Service (Google Drive-lite)”

Requirements

  • Functional: upload files (up to a few GB), download, share via link, list my files.
  • Non-functional: uploads resumable, durable storage, downloads fast, access controlled.

API

POST /api/files { name, size, mimeType } -> { fileId, uploadUrl(s) }
POST /api/files/:id/complete -> { status }
GET /api/files/:id/download -> 302 to signed URL
GET /api/files?cursor=

Schema

files(id, owner_id, name, size, mime, storage_key, status, checksum, created_at)
shares(file_id, shared_with_user_id | link_token, permission, expires_at)

Diagram

Client ──1. init──▶ API ──▶ DB (status=pending)
│ │
│ 2. presigned (multipart) URLs
▼
Object storage (S3 / R2) ──3. event──▶ queue ──▶ worker: virus scan, thumbnail, status=ready
▲
└── 4. downloads via CDN with short-lived signed URLs

Talking points

  • Presigned URLs — bytes never touch the API (Vigil lesson).
  • Multipart / chunked upload — 5–100 MB parts, retry only failed parts, resume after disconnect.
  • Validate size/type server-side when issuing URLs; scan files async before marking ready.
  • Clean up abandoned pending uploads with a scheduled job (and storage lifecycle rules).
  • Dedup by checksum (optional): same file content stored once.

Requirements

  • Functional: post (text + image), follow users, home feed of followed users’ posts (newest first), like/comment.
  • Non-functional: feed load < 300 ms, read-heavy, eventual consistency OK (a post appearing a few seconds late is fine).

API

POST /api/posts { text, mediaKey }
GET /api/feed?cursor=...&limit=20 -> { items, nextCursor }
POST /api/users/:id/follow
POST /api/posts/:id/like

Schema

posts(id, author_id, text, media_url, created_at) INDEX (author_id, created_at DESC)
follows(follower_id, followee_id) PK (follower_id, followee_id)
feed_items(user_id, post_id, created_at) PK (user_id, created_at, post_id) -- if fan-out on write

Diagram

Client ──▶ LB ──▶ Post service ──▶ posts DB
│
└──▶ queue ──▶ fan-out workers ──▶ feed cache per user (Redis list / feed_items)
Client ──▶ LB ──▶ Feed service ──▶ feed cache ──miss──▶ build from follows + posts
│
└──▶ hydrate post details (cache) ──▶ CDN for media

Talking points

  • Fan-out on write vs read and the hybrid for celebrities (see AniSnap section on the projects page).
  • Cursor pagination, not offset.
  • Store only post IDs in feed lists; hydrate details from a post cache.
  • Ranking: start chronological; mention ranked feeds (engagement signals) as a later upgrade.
  • Media via object storage + CDN; resize on upload.

Q: URL shortener: 301 or 302?

301 (permanent) gets cached by browsers — less server load, but you can’t count repeat clicks or change the destination. 302 (temporary) hits your server every time — enables analytics. Most shorteners use 302 or 301 with short cache.

Q: Why should a rate limiter "fail open"?

If Redis is down and the limiter fails closed, every request gets 429 — you’ve taken down your own product. Failing open temporarily allows unlimited traffic, which is usually the lesser evil (except for sensitive endpoints like login/OTP, where you may fail closed).

Q: In a chat app, why persist the message before delivering it?

So a message is never lost if the server crashes after delivery attempt. The ack to the sender means “stored durably”; delivery to the recipient can then be retried.

Q: Why one queue per notification channel?

Isolation: a slow or failing provider (SMS) doesn’t back up others (email, push). Each channel can have its own concurrency and rate limit matched to the provider.

Q: How does a celebrity break fan-out on write?

A user with 10M followers posting means 10M feed writes for one post — huge write spike and delay. Hybrid: don’t fan out celebrity posts; merge them into followers’ feeds at read time.