Skip to content

Design My Projects (Scale-Up Answers)

This is the most likely system design question you’ll get: “You built X. How would you scale it to a million users? What breaks first?”

It’s also where you have an unfair advantage — you built these. The interviewer wants to see that you understand your own architecture’s weak points. Being honest (“this part wouldn’t scale, here’s why and here’s the fix”) scores far higher than claiming it’s perfect.


1. Calcimate — math learning platform (current job)

Section titled “1. Calcimate — math learning platform (current job)”
┌──────────────────────── Cloudflare edge (300+ cities) ──────────────────────┐
Browser ─────▶ │ Next.js (OpenNext on Workers) ──▶ Hono API (Workers) │
(GSAP, DnD, │ static assets from edge cache Better-auth sessions, Drizzle ORM │
Howler audio) └───────────────────────────────────────────────┬─────────────────────────────┘
│ TCP/TLS over the internet
▼
┌──────────────────────────┐
│ Azure PostgreSQL │
│ (single region) │
│ users, sessions, quests, │
│ progress, attempts │
└──────────────────────────┘

Read/write pattern: lots of reads (lesson content, quest definitions, the user’s progress) and frequent small writes (attempt submitted, XP updated, quest step completed).

1. Distance + connections between Workers and a single-region Postgres. Workers run at the edge closest to the user, but the database is in one Azure region. Every query is a round trip from the edge city to that region. A page that does 4 sequential queries from a far edge pays 4 × RTT. Also, each Worker invocation opening a fresh TCP + TLS + Postgres auth handshake is expensive (several round trips before the first query), and many concurrent isolates can exhaust Postgres connection limits.

2. Auth on every request. Better-auth session lookups hit the DB on each request unless cached — that’s a DB read multiplied by every API call.

3. Write hot spots. Progress/XP updates on every answer → many small writes; leaderboards computed with ORDER BY xp over all users get slow.

Fix What it does Tradeoff
Cloudflare Hyperdrive Keeps a warm connection pool near the DB, so Workers skip the handshake; can cache read query results Cached reads can be slightly stale; another piece of config
Smart Placement for the API Worker Runs the Worker near the DB instead of near the user, so N queries = N short hops and only one long hop to the user User → Worker hop gets longer; good when a request makes multiple DB calls
Batch / parallelise queries One query with joins, or Promise.all, instead of sequential awaits Slightly more complex code
Cache static content (quest definitions, lesson content) in KV or Cache API Lessons change rarely → edge reads at ~ms Must purge/version on content publish
Cookie-cached sessions Better-auth supports caching session data in a signed cookie for a short window → skip DB on most requests Revocation is delayed until the cache expires
Indexes progress(user_id, quest_id), attempts(user_id, created_at) Slower writes (negligible here)
Read replica Offload heavy reads (dashboards, analytics) Replication lag → read-your-own-writes issue for progress
Queue for non-critical writes (Cloudflare Queues) Analytics events, streak recomputation, badges done async Eventual; need idempotency
Leaderboard in Redis sorted set (or a periodically materialised table) O(log n) rank updates Another store to keep in sync
Browser
│
▼
┌──────────── Cloudflare ─────────────────────────────────────────────┐
│ Next.js (OpenNext) ── static/ISR from edge cache │
│ │ │
│ ▼ │
│ Hono API Worker ──▶ KV / Cache API (lesson + quest content) │
│ │ └───▶ Cloudflare Queue ──▶ Consumer Worker │
│ │ (xp events, (badges, streaks, │
│ │ analytics) analytics rollups) │
│ ▼ │
│ Hyperdrive (pooled conns + query cache) │
└──────┼──────────────────────────────────────────────────────────────┘
▼
Azure Postgres primary ──replication──▶ read replica (dashboards / reports)

If your resume or you say “sub-100ms”, be ready for: “sub-100ms for what, measured where?”

Be precise:

  • Static assets and cached pages served from Cloudflare’s edge — yes, easily sub-100ms TTFB for most users.
  • API calls that hit the database — latency is dominated by edge → Azure region distance + number of queries. For a user near the DB region it can be fast; for a user far away, a few sequential queries can each add tens of ms.
  • Workers cold starts are very small (isolates, not containers), which helps — but the DB round trip is the real cost.

Good answer: “The edge layer is fast — static and cached responses are well under 100ms. Database-backed calls depend on distance to the Azure region; that’s exactly why I’d add Hyperdrive and cache read-mostly content in KV, and measure p95 per route rather than quoting a single number.”

p95 latency per route, DB connection count, slow query log, Hyperdrive cache hit rate, Worker CPU time, error rate on submits.

Q: Why not just move the database to the edge (D1 or a global DB)?

Possible for some data, but progress/auth data needs strong consistency and relational queries, and the team already has Postgres + Drizzle migrations. A global DB adds write latency for consistency or gives up consistency. Pragmatic path: keep Postgres as source of truth, pool with Hyperdrive, cache read-mostly content at the edge.

Q: What happens if two tabs submit the same quest step at once?

Risk of double XP. Fix: unique constraint UNIQUE(user_id, quest_step_id) on completions and INSERT ... ON CONFLICT DO NOTHING, then award XP only if a row was inserted (in the same transaction).

Q: Why is the frontend heavy (GSAP, DnD, Howler) a scaling concern?

It’s a client performance concern, not server: bundle size and load time on low-end Android devices. Code-split per module (dynamic import GSAP/Howler only on lesson pages), lazy-load audio sprites, serve audio from CDN, and respect prefers-reduced-motion.


Candidate / Recruiter
│
▼
Web app ──▶ API server ──▶ Postgres/DB (jobs, applications, statuses, CMS content)
│
├──▶ pdf-lib: generate certificate / offer letter (in the request!)
└──▶ email provider: send PDF as attachment (in the request!)

Synchronous PDF generation + email inside the HTTP request.

  • PDF generation is CPU-bound; in Node it blocks the event loop, so one recruiter bulk-issuing 500 certificates slows the API for everyone.
  • The request can time out midway → some PDFs generated, some emails sent, unclear state.
  • The email provider can fail or rate-limit → no retry → candidate never gets the letter.
  • Client retries after timeout → duplicate emails (“you got two offer letters”).
Recruiter clicks "Issue offer letters"
│
▼
API: validate, INSERT documents(status='pending') rows, enqueue jobs ──▶ 202 Accepted
│
▼
┌──────────────┐ ┌──────────────────────────┐ ┌───────────────┐
│ Queue │───▶ │ Worker(s) │───▶ │ Object storage│ (PDF saved: S3/R2)
│ (BullMQ/SQS) │ │ 1. generate PDF (pdf-lib)│ └───────────────┘
└──────┬───────┘ │ 2. upload PDF │
│ │ 3. status='generated' │──▶ enqueue "send email" job
▼ └──────────────────────────┘
Dead-letter queue │
(after N retries) ▼
Email worker ──▶ Email provider (SES/Resend/SendGrid)
│ │
│ └── webhook: delivered / bounced
▼
status='sent', sent_at, provider_message_id

Key points to say:

  • Split into two jobs: generate and send. If email fails, we retry only the email — not regenerate the PDF.
  • Retries with exponential backoff (e.g. 1s, 5s, 30s, 2min), then a dead-letter queue + admin alert.
  • Store the PDF in object storage and email a link (or attach from storage) — re-sendable, auditable, and you can show “Download certificate” in the dashboard.
  • Bulk operations become N small jobs, processed with limited concurrency so the email provider’s rate limit isn’t exceeded.
  • Recruiter UI shows progress (120/500 sent) by polling a status endpoint or via SSE.

Idempotency: never send a certificate twice

Section titled “Idempotency: never send a certificate twice”
documents(
id PK,
candidate_id, job_id, type, -- 'offer_letter' | 'certificate'
status, -- pending | generated | sent | failed
storage_key, provider_message_id, sent_at,
UNIQUE (candidate_id, job_id, type) -- can't create two offer letters for same job
)
  • Job ID = document ID, so enqueuing twice is deduplicated (BullMQ jobId, SQS FIFO dedup ID).
  • Email worker: atomically claim the send — UPDATE documents SET status='sending' WHERE id=? AND status='generated' — if 0 rows updated, someone else already handled it → skip.
  • Pass an idempotency key to the email provider where supported.
  • Edge case to admit: if the worker crashes after the provider accepted the email but before we mark sent, a retry could duplicate. Mitigation: provider idempotency keys, or check provider message log before resending. Saying this unprompted is a strong signal.
Area Change
Job search Postgres full-text search (tsvector + GIN index) first; Elasticsearch/Meilisearch/Typesense only when needed
Application tracking Index applications(job_id, status) and applications(candidate_id, created_at); status history table for audit
Custom CMS pages Mostly static → cache on CDN / ISR, purge on publish
Resume uploads Presigned URL direct to storage; virus scan async
Recruiter dashboards Cursor pagination; counts via cached/materialised aggregates
Q: Why not just use async/await or setTimeout to do the PDF in the background in the same server?

It’s not durable — if the server restarts or crashes, in-flight work is lost with no record. No retries, no visibility, no concurrency control, and CPU-heavy work still competes with API requests on the same event loop. A queue persists jobs and lets workers scale separately.

Q: PDF generation is CPU-heavy — how do you scale it?

Run workers as separate processes/containers; scale on queue depth. Within Node, use worker_threads or multiple processes. Cache templates (fonts, background images loaded once). For certificates with the same layout, only text fields change, so the template can be loaded once per worker.


3. Vigil — video platform with AI moderation

Section titled “3. Vigil — video platform with AI moderation”
Uploader ──(multipart, whole file)──▶ Express API ──▶ extract frames ──▶ NSFWJS (in-process)
│ └──▶ Clarifai API (per frame)
│
├──▶ Cloudinary upload ──▶ HLS adaptive streaming
├──▶ Database: video metadata, status
└──▶ Socket.io: "processing… approved/rejected"
JWT auth with RBAC: Admin / Editor / Viewer
  1. Video bytes flow through the Express server. A 500 MB upload ties up memory, disk, bandwidth, and a connection for minutes. A few concurrent uploads and the server falls over.
  2. Moderation runs inside the API process. NSFWJS (TensorFlow.js) is CPU/memory heavy and blocks the event loop; frame extraction (ffmpeg) is heavy too. API latency spikes for everyone.
  3. Clarifai cost and rate limits. Calling an external API for every frame is expensive and slow. A 10-minute video at 30 fps = 18,000 frames. Even at 1 frame/sec it’s 600 calls per video. Multiply by uploads per day — that’s the bill.
  4. Socket.io on multiple servers. Once you have 2+ API instances, the worker that finishes moderation might emit to a server where the user isn’t connected.

a) Presigned / direct uploads — client gets a signed upload URL (Cloudinary signed upload or S3/R2 presigned URL) and uploads directly. The API only handles a small JSON request. Use chunked/resumable uploads for big files.

b) Webhooks instead of waiting — Cloudinary calls our /webhooks/cloudinary endpoint when upload/transcoding finishes. Verify the webhook signature, and make the handler idempotent (webhooks can be delivered more than once).

c) Queue + moderation workers — the webhook enqueues a moderate(videoId) job. Separate worker processes (scaled on queue depth) do the heavy lifting.

d) Smart frame sampling — don’t check every frame:

  • Sample 1 frame every N seconds, plus scene-change / keyframes (ffmpeg can extract keyframes or detect scene changes).
  • Cascade: run cheap local NSFWJS on all sampled frames; only send uncertain frames (e.g. score between 0.3 and 0.8) to Clarifai. Clear-safe and clear-unsafe never hit the paid API.
  • Early exit: once enough frames are confidently unsafe, reject without checking the rest.
  • Cloudinary can also generate thumbnails/frames at offsets, so workers may not even need to download the full video.

e) Socket.io scaling — use the Redis adapter (@socket.io/redis-adapter) so an emit on any server reaches clients connected to any other server via Redis pub/sub. Enable sticky sessions at the load balancer because Socket.io’s HTTP long-polling fallback needs all requests of a session to hit the same server (or force WebSocket-only transport). Workers can publish with the Redis emitter without being Socket.io servers themselves.

Uploader Viewer
│ 1. POST /videos (JWT, role=Editor) │
▼ │ HLS (.m3u8 + segments)
┌────────┐ 2. signed upload params ▼
│ API │◀─────────────────────────┐ ┌─────────────┐
│(Express│ │ │ Cloudinary │
│ xN) │ 3. client uploads ──────┼────────────────────▶│ storage + │
└───┬────┘ directly │ │ transcode + │
│ │ │ CDN (HLS) │
│ 4. webhook: upload done ◀─────┼─────────────────────└─────────────┘
│ (verify signature, │
│ idempotent) │
▼ │
┌────────┐ 5. job ┌──────────────────────────────┐
│ DB │◀──status───│ Moderation workers (xM) │
│ videos │ │ sample frames → NSFWJS │
└────────┘ │ uncertain only → Clarifai │
▲ └───────────────┬──────────────┘
│ │ 6. publish "video:123 approved"
│ ┌───────▼───────┐
└──────────────────────── │ Redis │ ← queue (BullMQ) + Socket.io adapter
└───────┬───────┘
▼
Socket.io servers ──▶ uploader's browser: "Approved ✓"
uploading ──▶ uploaded ──▶ processing ──▶ approved ──▶ published
│
├──▶ rejected
└──▶ needs_review ──▶ (Admin decides) ──▶ approved / rejected

Adding needs_review (human-in-the-loop for borderline scores) is a great point: AI moderation has false positives, and admins (your RBAC Admin role) should be able to override.

  • RBAC: keep permission checks in middleware (requireRole('Editor')), but also check ownership (an Editor can edit their videos). JWT roles are stale until token expires — use short-lived access tokens + refresh tokens, or check role from DB for sensitive actions.
  • Viewers never get unapproved videos: stream URLs are only returned when status='approved'; use signed/private delivery URLs for anything not public.
  • Cost: biggest costs are transcoding/storage/bandwidth (Cloudinary) and Clarifai calls. Sampling + cascade cuts Clarifai calls drastically; consider storing fewer renditions for rarely watched videos.
Q: Why is a queue better than doing moderation in the webhook handler?

The webhook sender expects a fast 2xx; slow handlers cause timeouts and retries (duplicate processing). The queue gives durability, retries with backoff, concurrency control (respect Clarifai rate limits), and lets you scale workers independently of the API.

Q: Why do you need sticky sessions with Socket.io if you have the Redis adapter?

They solve different problems. The Redis adapter lets server A broadcast to clients on server B. Sticky sessions ensure that a single client’s polling requests (before upgrading to WebSocket) all go to the same server, since the handshake state lives on that server. If you force transports: ['websocket'], you can drop sticky sessions.

Q: How would you estimate Clarifai cost?

calls/day = videos/day × avg duration (s) ÷ sample interval × fraction sent to Clarifai. E.g. 1,000 videos × 300 s ÷ 2 s × 20% uncertain = 30,000 calls/day. Multiply by the per-call price from their pricing page. Then compare with checking every frame to show the saving. (Don’t quote a price you don’t know — show the formula.)

Q: What is HLS adaptive streaming, briefly?

The video is transcoded into several bitrates/resolutions, each split into small segments (2–6 s). A master .m3u8 playlist lists the variants. The player measures bandwidth and switches quality per segment. Segments are plain HTTP files → perfectly CDN-cacheable.


4. AniSnap — social app (React + Vite + Supabase + Zustand)

Section titled “4. AniSnap — social app (React + Vite + Supabase + Zustand)”
React + Vite SPA (Zustand state)
│
├──▶ Supabase Auth (JWT)
├──▶ Supabase Postgres via PostgREST (RLS policies enforce access)
├──▶ Supabase Storage (images) ──▶ CDN
└──▶ Supabase Realtime (websocket: new posts, likes, comments)

No custom backend: the client talks to Postgres through Supabase’s auto-generated API, and Row Level Security (RLS) is the security layer.

Two classic approaches:

Fan-out on read (pull) Fan-out on write (push)
How On load, query posts from people I follow, sorted by time On post, insert a row into every follower’s feed table
Read cost High (join over follows) Very low (read my feed rows)
Write cost Low High for users with many followers
Fits Small/medium apps — AniSnap today Large apps with heavy reads

Hybrid (what big apps do): push for normal users, pull for celebrities at read time.

For AniSnap at 1M users I’d start with pull + good indexes + caching, and move to a precomputed feed_items table (populated by a Postgres trigger or a background job/Edge Function) once feed queries get slow.

posts(id, author_id, image_path, caption, created_at)
INDEX (author_id, created_at DESC, id DESC)
follows(follower_id, followee_id, PRIMARY KEY (follower_id, followee_id))
INDEX (followee_id) -- "who follows me" for fan-out
likes(user_id, post_id, PRIMARY KEY (user_id, post_id)) -- no double likes
posts.like_count -- denormalised counter, updated by trigger
OFFSET: SELECT ... ORDER BY created_at DESC LIMIT 20 OFFSET 10000;
→ DB still walks 10,020 rows. Slow on deep pages.
→ New posts arriving shift everything → duplicates/skips while scrolling.
CURSOR: SELECT ... WHERE (created_at, id) < ($lastCreatedAt, $lastId)
ORDER BY created_at DESC, id DESC LIMIT 20;
→ Index seek straight to the position. Same speed on page 1 or page 500.
→ Stable while new posts arrive.

Use the (created_at, id) tuple because timestamps can tie. Offset is fine for admin tables with page numbers; cursor for infinite feeds.

  • Good: security is enforced in the database, so even a hacked client can’t read others’ private data. Example: using (auth.uid() = user_id) for private rows; for posts, visible if public or if the viewer follows the author.
  • Cost: RLS policies run per row. A policy with a subquery (exists (select 1 from follows ...)) on a big feed query can get slow. Fix: index the columns used in policies (follows(follower_id, followee_id)), wrap auth.uid() in (select auth.uid()) so it’s evaluated once, keep policies simple, and move complex feed logic into a security definer SQL function / RPC that’s carefully written.
  • Always remember: the anon key is public. RLS must be enabled on every table, or the table is open.
  • Supabase Realtime Postgres Changes checks each change against RLS for every subscribed client — with many subscribers on a busy table, that becomes a throughput bottleneck (one insert × 10,000 listeners = 10,000 authorisation checks).
  • Fixes:
    • Don’t subscribe everyone to the whole posts table. Subscribe to narrow channels: post:{id}:comments only while viewing that post, user:{id}:notifications for your own notifications.
    • Use Broadcast channels (server/DB publishes a message to a topic) for high-fanout events instead of raw Postgres Changes.
    • For the feed, don’t push every new post live. Show a “5 new posts ↑” pill (poll a count every 30–60 s or a light broadcast) and fetch on click — that’s what Twitter/Instagram do.
    • Debounce like-count updates; update counts optimistically on the client.
  • Connection limits: each open tab = one WebSocket connection; plan tiers accordingly and unsubscribe channels on unmount.
React SPA (Zustand: UI state; React Query/SWR: server cache + pagination)
│
├──▶ CDN ──▶ Supabase Storage (images, resized via image transformations, WebP)
│
├──▶ PostgREST / RPC: get_feed(cursor) ──▶ Postgres primary
│ │ RLS + indexes
│ ├──▶ read replica (feed/profile reads)
│ └──▶ trigger/job ──▶ feed_items (fan-out on write)
│
├──▶ Edge Functions: rate-limited writes (post, comment), moderation, notifications
│
└──▶ Realtime: narrow channels (notifications, open post's comments) + Broadcast
  • Images: resize/compress on upload (client-side + storage transforms), serve thumbnails in the feed, full size on open, lazy-load below the fold.
  • Zustand vs server state: keep server data (feed pages) in a cache library like React Query/SWR with useInfiniteQuery; keep Zustand for UI/client state. Avoids stale duplicated state.
  • Abuse: rate-limit post/comment creation (Edge Function or DB-level checks); without a backend, anyone with the anon key can call your API directly.
Q: Why is offset pagination bad for an infinite feed?

Deep offsets are slow (DB scans and discards rows) and results shift when new posts are inserted, causing duplicates or skipped posts. Cursor (keyset) pagination uses an index seek and is stable.

Q: Is having no backend (direct Supabase from client) safe?

Yes, if RLS is enabled on every table with correct policies, and the service-role key never reaches the client. Business logic that needs secrets, validation, or rate limiting goes in Edge Functions or database functions.

Q: How would you show like counts at scale?

Denormalised like_count on posts updated by a trigger (or batched by a job), not COUNT(*) per render. Client updates optimistically. Uniqueness enforced by the (user_id, post_id) primary key so double-clicks can’t double-like.


Project First bottleneck First fix
Calcimate Edge Workers ↔ single-region Postgres (latency, connections) Hyperdrive + edge caching of content + fewer sequential queries
Seqtto Sync PDF + email in the request Queue + workers + idempotent sends
Vigil Video bytes + moderation in the API process Direct uploads + webhook + queue workers + frame sampling
AniSnap Feed queries + RLS cost + realtime fan-out Cursor pagination, indexes, narrow channels, fan-out table later