Skip to content

Building Blocks

Every design answer is built from the same ~15 Lego pieces. If you can explain what each one is, when to use it, and what it costs, you can handle any SDE-1 design round.

Block Use it when Cost / downside
Load balancer >1 app server Extra hop; needs health checks
Horizontal scaling Stateless servers, traffic grows Must externalise state
Cache (Redis) Read-heavy, repeated reads Staleness, invalidation bugs
CDN Static assets, media, global users Cache purge complexity, cost
Read replica Reads >> writes Replication lag (stale reads)
Sharding One DB can’t hold data / writes Cross-shard queries are painful
Index Slow queries on a column Slower writes, more storage
Message queue Slow / unreliable / bursty work Eventual completion, retries, idempotency
Object storage Files, images, videos, PDFs Not a database; no queries
Rate limiter Abuse, cost control, fairness Shared counter store needed

Q: Vertical vs horizontal scaling?

Vertical = bigger machine (more CPU/RAM). Simple, no code changes, but has a ceiling and is a single point of failure.

Horizontal = more machines behind a load balancer. Near-unlimited and fault tolerant, but servers must be stateless and you need a load balancer.

Typical path: scale vertically first (cheap and simple), go horizontal when you hit limits or need availability. Databases are usually scaled vertically much longer than app servers.

Q: What is a load balancer and what algorithms does it use?

Distributes incoming requests across multiple servers and stops sending traffic to unhealthy ones (health checks).

Algorithms: round robin, least connections, IP hash / sticky sessions (same client → same server; needed for some WebSocket setups), weighted.

L4 (TCP-level, fast, dumb) vs L7 (HTTP-level, can route by path/header, terminate TLS).

Examples: Nginx, AWS ALB, Cloudflare. From my projects: on Cloudflare Workers (Calcimate) there’s no LB to manage — Cloudflare runs the code in every edge location automatically.

Q: What does "stateless server" mean and why does it matter?

The server keeps no per-user data in memory between requests — sessions, uploads in progress, etc. live in a DB/Redis/cookie/JWT. Any server can handle any request, so you can add/remove servers freely and a crash loses nothing.

From my projects: Vigil uses JWTs, so the Express API is stateless for auth. But Socket.io connections are state — that’s why scaling it needs a Redis adapter.

Q: Where can you cache? (layers)

From closest to the user to furthest:

  1. Browser — HTTP Cache-Control, service workers, in-memory (React Query/SWR).
  2. CDN / edge — static assets, images, video segments, even cacheable API responses.
  3. App server memory — fast but per-instance and lost on restart; inconsistent across instances.
  4. Distributed cache (Redis / Memcached / Cloudflare KV) — shared by all servers.
  5. Database — its own buffer cache; materialized views.

The closer to the user, the faster and cheaper — but the harder to invalidate.

Q: Caching strategies: cache-aside, write-through, write-back?
  • Cache-aside (lazy loading) — app checks cache; on miss reads DB and fills cache. Most common. Risk: stale data until TTL/invalidation.
  • Write-through — write to cache and DB together. Cache always fresh; writes slower.
  • Write-back (write-behind) — write to cache, flush to DB later. Fast writes; risk of data loss.
  • Read-through — cache library itself loads from DB on miss.

Default answer: cache-aside with a TTL, plus delete-on-write for important keys.

Q: How do you invalidate a cache?
  • TTL — simplest; accept staleness up to N seconds.
  • Delete on write — when data changes, delete the cache key (next read refills). Prefer delete over update to avoid races.
  • Versioned keys — user:42:v7; bump version to invalidate.
  • Event-based — publish “user updated” event, subscribers evict.

Mention the thundering herd / cache stampede: a hot key expires and 1,000 requests hit the DB at once. Fixes: request coalescing (single flight), lock while refilling, jittered TTLs, stale-while-revalidate.

Q: What's an eviction policy?

What the cache drops when full: LRU (least recently used — most common), LFU (least frequently used), FIFO, TTL-based. Redis supports allkeys-lru etc. (LRU is also a classic LLD question — see the LLD page.)

Q: What is a CDN and what do you put on it?

A network of edge servers worldwide that cache content near users. Put static assets (JS, CSS, fonts), images, video segments (HLS .ts/.m4s chunks), downloadable files. Can also cache public API responses with short TTLs.

Benefits: lower latency, offloads origin, absorbs traffic spikes and DDoS.

From my projects: Vigil streams via Cloudinary’s CDN (HLS). Calcimate’s Next.js static assets are served from Cloudflare’s edge.

Q: What is database replication?

Copying data from a primary (handles writes) to one or more replicas (handle reads).

  • Scales reads, improves availability (promote replica if primary dies).
  • Async replication → replicas may lag (stale reads). Sync → no lag but slower writes.

Gotcha: read-your-own-writes. User updates profile, next read hits a lagging replica and shows old data. Fix: read from primary for a few seconds after a write, or for that user’s own data.

Q: What is sharding (partitioning)?

Splitting data across multiple databases by a shard key (e.g. user_id). Each shard holds a subset of rows.

  • Scales writes and storage beyond one machine.
  • Strategies: hash-based (even spread), range-based (easy range queries, risk of hot shards), directory/lookup.
  • Pain: cross-shard joins/transactions, resharding, hot keys (a celebrity user).

At SDE-1, say: “I’d avoid sharding until we truly need it — vertical scaling, read replicas and caching get a Postgres very far.”

Q: What is an index and what does it cost?

A data structure (usually a B-tree) that lets the DB find rows without scanning the whole table — O(log n) instead of O(n).

Index columns used in WHERE, JOIN, ORDER BY. Composite index order matters: (user_id, created_at) serves WHERE user_id = ? ORDER BY created_at but not WHERE created_at > ? alone.

Cost: slower inserts/updates (index must be updated), extra storage. Check with EXPLAIN ANALYZE.

Q: SQL vs NoSQL — how do you choose?

SQL (Postgres): structured, relational data; joins; transactions; constraints. The default choice.

NoSQL: document (MongoDB), key-value (Redis, DynamoDB), wide-column (Cassandra), graph. Choose for massive write scale with simple access patterns, flexible schemas, or specific models.

Say: “I’d default to Postgres — our data has clear relations (users, quests, progress) and we need transactions.”

Q: What is connection pooling and why does it matter?

Opening a DB connection is expensive (TCP + TLS + auth), and Postgres can only handle a few hundred connections. A pool keeps connections open and reuses them.

Serverless/edge (Workers, Lambda) spins up many instances, each wanting connections → exhausts Postgres. Fix: an external pooler (PgBouncer, Supabase’s Supavisor, Cloudflare Hyperdrive).

From my projects: this is exactly the Calcimate risk — Workers → Azure Postgres.

Q: Why use a message queue?

Decouple “accept the request” from “do the work”:

  • Fast responses — return 202 immediately; do slow work (PDFs, video moderation, emails) in the background.
  • Absorb spikes — queue buffers bursts; workers process at a steady rate.
  • Reliability — retries with backoff; dead-letter queue for poison messages.
  • Independent scaling — scale workers separately from the API.

Cost: eventual completion, more infrastructure, must handle duplicates (idempotency) and observe queue depth.

Q: BullMQ vs SQS vs Cloudflare Queues vs Kafka?
  • BullMQ — Node library on top of Redis. Delayed jobs, retries, priorities, rate limiting, nice for an Express app. You run Redis.
  • AWS SQS — fully managed, at-least-once, scales infinitely, simple. Pair with Lambda or worker containers.
  • Cloudflare Queues — managed queue for Workers; producer and consumer are Workers. Natural fit for Calcimate.
  • Kafka — distributed log; high throughput, replayable, many consumers. Overkill for most SDE-1 designs — mention only if event streaming/analytics at scale.
Q: What is idempotency and how do you implement it?

An operation is idempotent if doing it twice has the same effect as doing it once. Needed because queues are at-least-once and clients retry on timeouts.

Implementation:

  • Client sends an Idempotency-Key header; server stores key → result; repeated key returns stored result.
  • Unique constraints in DB, e.g. UNIQUE(candidate_id, certificate_type).
  • Check-then-mark state: status = 'sent' updated in the same transaction.

From my projects: Seqtto — a retried job must not email the same offer letter twice.

Q: Delivery guarantees: at-most-once, at-least-once, exactly-once?
  • At-most-once — may lose messages, never duplicates.
  • At-least-once — never loses, may duplicate. Most queues (SQS, BullMQ).
  • Exactly-once — very hard end-to-end; in practice = at-least-once + idempotent consumers.
Q: What is object storage and how do uploads work at scale?

S3 / R2 / GCS / Azure Blob / Cloudinary: store files as objects by key. Cheap, durable, infinitely scalable, CDN-friendly. Not for querying — store metadata (owner, size, status) in your DB.

Presigned URLs: server generates a short-lived signed URL; client uploads directly to storage. Your server never handles the bytes → no memory/bandwidth bottleneck. Storage then fires an event/webhook to start processing.

Q: Rate limiting algorithms?
  • Fixed window — count per minute bucket. Simple; burst at window edges (2x allowed).
  • Sliding window log — store timestamps; accurate but memory-heavy.
  • Sliding window counter — weighted mix of current + previous window. Good balance.
  • Token bucket — bucket refills at rate r, holds up to b tokens; each request takes one. Allows bursts, smooth average. Most popular.
  • Leaky bucket — requests queue and drain at a fixed rate; smooths output.

Store counters in Redis (INCR + EXPIRE, or Lua for atomicity) so all servers share them. Return 429 Too Many Requests with Retry-After.

Q: Explain the CAP theorem simply.

In a distributed system, when a network partition happens (nodes can’t talk), you must choose:

  • Consistency (C) — every read sees the latest write (or errors), or
  • Availability (A) — every request gets a response (possibly stale).

Partitions are unavoidable, so really it’s CP vs AP during failures.

  • Bank balance, seat booking → CP (better to error than double-book).
  • Like counts, feeds, view counts → AP (stale is fine).
Q: Strong vs eventual consistency?

Strong: after a write, every read returns it. Eventual: reads may be stale briefly but converge.

Most systems mix: payments/inventory strong; feeds, counters, search indexes, caches eventual. Saying which parts need which is a great SDE-1 signal.

Q: What is a single point of failure and how do you remove it?

Any component whose failure takes the whole system down (one server, one DB, one Redis). Fix with redundancy: multiple app instances behind an LB, DB replica with failover, managed services with multi-AZ, health checks.

Q: Push vs pull for real-time updates?
  • Polling — client asks every N seconds. Simple, wasteful.
  • Long polling — server holds request until data. Better.
  • SSE — one-way server → client stream over HTTP. Great for status updates/notifications.
  • WebSockets — full duplex. Chat, collaboration, games.
  • Webhooks — server-to-server push (Cloudinary → your API).

From my projects: Vigil uses Socket.io for moderation status; SSE would also work since it’s one-way.

Q: What should you monitor?

The “golden signals”: latency (p50/p95/p99), traffic (req/s), errors (5xx rate), saturation (CPU, memory, DB connections, queue depth). Plus logs with request IDs, and alerts on SLO breaches.