System Design Senior cheat sheet: interview answers
Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.
1. What does the CAP theorem state?
Correct answer: During a network partition you have to choose between consistency and availability
Consistency, Availability, Partition tolerance: network partitions are inevitable in a distributed system, and at that moment the system either rejects some requests (CP) or responds with possibly stale data (AP). In normal operation the trade-off is between consistency and latency (PACELC).
2. A user updated their profile, refreshed the page and saw the old data. Which guarantee was violated?
Correct answer: Read-your-writes: the user must see their own changes
A typical cause is reading from a replica the change hasn't reached yet, or a stale cache. Solutions: read "own" data from the primary for a while after a write, update the client cache with the mutation response, use
updateTaginstead of SWR invalidation.3. Why is choosing "creation date" as a sharding key dangerous?
Correct answer: All new records land in one shard - a hot partition
Sharding distributes data across nodes; the key must spread the load evenly and match the queries. A monotonic key concentrates writes in the last shard. A hash of the user id or a composite key is often used.
4. Why use consistent hashing when adding cache nodes?
Correct answer: When the number of nodes changes, only a small share of keys move
With
hash(key) % N, changing N redistributes almost all keys and the cache misses en masse. A hash ring (with virtual nodes) moves only ~1/N of the keys. Used in distributed caches, CDNs and databases.5. Why put a message queue between the API and a heavy-task worker?
Correct answer: To decouple intake from processing and smooth out load spikes
The API quickly accepts the request and enqueues a task (report generation, video processing), and workers process it at their own pace. Load spikes are smoothed out, and a worker failure doesn't lose the task. The client learns the result via status polling, SSE or a notification.
6. Why must consumers of an "at-least-once" queue be idempotent?
Correct answer: A message may arrive again, and that must cause no harm
Exactly-once is expensive or unattainable in practice, so systems guarantee "at least once". The handler stores ids of processed messages or makes operations idempotent (upsert instead of insert).
7. What is backpressure?
Correct answer: A signal from a slow consumer to the source: "slow down"
Without backpressure, a fast source overflows the consumer's buffers and memory. Examples: the Streams API in the browser (
ReadableStreamwith a queue), limiting queue size, rejecting requests with 429/503.8. How does fan-out on write differ from fan-out on read in a social feed?
Correct answer: On write it's copied to feeds; on read it's assembled
Precomputed feeds make reads fast, but a celebrity's post with millions of followers generates millions of writes. Assembling on read is cheap to write but slow to read. Usually it's a hybrid: fan-out on write for regular authors, merge-in at read time for celebrities.
9. How do you guarantee correct message order in a chat?
Correct answer: Server-assigned sequence numbers per conversation, not client time
Device clocks drift, and messages are delivered along different paths. The server assigns a monotonic number within a conversation; the client shows a sent message with a temporary id and replaces it with the confirmed one. Gaps in numbers signal the need to fetch missing messages.
10. Which components are usually needed in a messenger architecture?
Correct answer: WS gateways, message storage, presence and push
Gateways hold connections and scale horizontally; pub/sub (Redis, Kafka) sits between them so a message reaches the right node. Message storage, delivery and read receipts, presence with heartbeats, push notifications, cross-device sync.
11. How do you scale WebSocket servers horizontally?
Correct answer: Connect nodes via pub/sub for delivery between them
Users of the same chat are connected to different nodes. The node that receives a message publishes it to a bus, and nodes with subscribers deliver it to their connections. The load balancer must support long-lived connections; during deploys clients reconnect gradually.
12. How do you implement an "online" status for millions of users?
Correct answer: Heartbeat with TTL: the status expires without client signals
The client sends a signal every N seconds, and the server stores a key with a TTL in fast storage (Redis). A disconnect without an explicit logout is detected by expiration. Status changes are broadcast only to those who can see them.
13. How does OT differ from CRDT in collaborative editing?
Correct answer: OT transforms operations; CRDTs converge on their own
Operational Transformation (Google Docs) adjusts concurrent operations relative to each other, which is easier with an arbiter server. CRDTs (Yjs, Automerge) are structures whose states mathematically merge into one in any order; they're convenient for offline and P2P but carry metadata.
14. How does adaptive video streaming (HLS/DASH) work?
Correct answer: Segments at different bitrates; the player picks based on the network
A playlist lists quality variants, and the player (via MSE) picks segments based on bandwidth and buffer. Segments are ordinary HTTP files, so a CDN caches them well.
15. How would you design serving user images in different sizes?
Correct answer: Store the original, generate sizes and formats on demand and cache on a CDN
A transformation service (in-house or cloud) creates a variant from width and format URL parameters and puts it into the CDN cache. The set of allowed sizes is limited to avoid endless variants and to prevent attacks on the service.
16. How do you implement rate limiting when the API runs on 20 servers?
Correct answer: Keep counters in shared fast storage (Redis) or at the gateway
Local counters give a limit ×20 and depend on load balancing. Shared storage with atomic operations (or a limiter at the API gateway/CDN) gives a global limit. Client-side limits are easily bypassed.
17. What is a Bloom filter useful for?
Correct answer: Quickly checking "definitely not / maybe" in a set
A Bloom filter never gives false negatives but allows false positives. Example: quickly rule out usernames that are definitely free, or URLs that are definitely not cached, before going to the DB.
18. How do you generate short links in a URL shortener?
Correct answer: A unique id from a counter, encoded in base62
Base62 of a 64-bit id gives a short string without collisions; the counter is handed out in ranges so nodes don't sync on every request. Random short strings require collision checks; a full hash is too long. Reads are cached, and the redirect is 301 or 302 depending on whether analytics is needed.
19. How do you scale search suggestions (typeahead) to millions of requests per second?
Correct answer: Precomputed top-K per prefix, edge caching, debounce
Popular prefixes and their suggestions (a trie or key-value) are updated offline from query logs, and responses are cached on the CDN and in the browser. The client reduces requests with debounce, cancellation and a local prefix cache.
20. What problems arise when running a service in multiple regions (active-active)?
Correct answer: Write conflicts, replication lag, data laws
Writing in two regions simultaneously requires a conflict resolution strategy (last-write-wins, CRDT, a user's "home region"). In addition, data localization laws (e.g. GDPR) restrict where personal data may be stored.
21. Why is a
Vary: User-AgentorVary: Cookieheader dangerous for a CDN?Correct answer: The cache key fragments and almost no hits remain
Varyadds request headers to the cache key. User-Agent and Cookie are nearly unique per visitor, so the cache becomes useless. Normalize the key (device class instead of the full UA) and move personalization out of the cached response.22. What is a cache stampede and how do you prevent it?
Correct answer: Many recomputations of one expired cache entry
When a popular key expires, thousands of requests hit the DB at once. Solutions: request coalescing (one recomputes, the others wait), stale-while-revalidate, random TTL jitter, warming.
23. How do cache-aside, write-through and write-back strategies differ?
Correct answer: Cache on read; write to cache and DB; deferred write to DB
Cache-aside (lazy loading) is the most common: on a miss, read the DB and put the result in the cache. Write-through keeps the cache up to date at the cost of slower writes. Write-back is faster but risks losing data if the cache fails.
24. When should you render at the edge, and when in a region near the database?
Correct answer: Edge for light logic, region for frequent DB queries
The edge is close to the user, but if a page makes five sequential DB queries across an ocean, each adds hundreds of milliseconds. Rendering near the data plus CDN caching often wins. The edge is good for redirects, A/B tests, cookie-based personalization and auth.
25. What ways of composing micro-frontends exist?
Correct answer: At build time, on the server and at runtime in the browser
Build-time composition is simple but rules out independent deploys. Server-side composition assembles HTML from fragments. Runtime composition gives independent releases at the cost of complexity and dependency coordination. iframes give isolation but are poor for UX and SEO.
26. How do you deploy an API change without breaking clients on the old version?
Correct answer: Expand-and-contract: add, migrate, remove the old
Open tabs, mobile apps and caches live with old code. First the API supports both the old and new format, then clients migrate, and only then is the old one removed. The same approach applies to DB schema migrations.
27. Why do users get a
ChunkLoadErrorafter an SPA deploy?Correct answer: An old tab requests a chunk that has already been removed
Hashed names change, and a lazily loaded chunk of the old version disappears. Solutions: keep assets from the last few releases, catch the error and reload the page, version skew protection (
deploymentIdin Next.js).28. How do metrics, logs and traces complement each other?
Correct answer: Metrics show something is wrong, traces show where, logs show why
Metrics (error rate, p95 latency) are cheap and suitable for alerts. A distributed trace shows a request's path through services. Logs give details of a specific event. OpenTelemetry standardizes collecting all three signals.
29. What is an error budget?
Correct answer: The allowed share of failures under the SLO that can be "spent"
With a 99.9% SLO, the budget is 0.1% failed requests. While budget remains, the team ships features; when it's exhausted, the focus shifts to reliability. This makes reliability a measurable trade-off rather than an argument.
30. What is the Bulkhead pattern?
Correct answer: Isolating resources so one failure stays contained
Separate connection and thread pools for different dependencies: a slow recommendations service won't take all the connections needed for payments. Together with circuit breakers and timeouts it prevents cascading failures.
31. Why is it important to look at p99 latency and not just the average?
Correct answer: The average hides the slow "tail" of requests
If a page makes 20 requests, the probability of hitting at least one slow one is high, and the user waits for the slowest. That's why SLOs are stated in percentiles (p95, p99), and Web Vitals are assessed at the 75th percentile.
32. How do you combine CDN caching of HTML with personalization (username, cart)?
Correct answer: Cache the shell and stream personal parts separately
Partial Prerendering, Edge Side Includes or client-side loading: the static part is served instantly from the CDN, and personal fragments are filled in on request. A per-user cache kills CDN efficiency and risks leaks.
33. Why can't a successful redirect from the payment page be treated as payment confirmation?
Correct answer: A redirect can be faked; the provider's webhook confirms it
The user may close the tab or open the success URL manually. The source of truth is a server-side webhook from the provider with signature verification, plus a status check via the API. Webhook handling must be idempotent.
34. How do you verify the authenticity of an incoming webhook?
Correct answer: Verify the HMAC signature and timestamp
The webhook endpoint is public; anyone can call it. The provider signs the body with a secret, and you verify the signature (on the raw body) and the time to reject replays. Everything else is easy to forge.
35. Why is the search index often updated asynchronously rather than in the same transaction?
Correct answer: So DB writes don't depend on search; the cost is a delay
Changes are fed into the index via a queue or CDC (change data capture). The main operation is fast and reliable, and search catches up within seconds - eventual consistency. The UI must be ready for this (e.g. show just-created items from local state).
36. How do you atomically update the database and publish an event to a queue?
Correct answer: Outbox: the event is written to the DB in the same transaction
Without a transaction spanning the DB and the broker, inconsistencies are possible: the write succeeded but the event was lost (or vice versa). An outbox table records the event atomically with the change, and a relay publishes it with retries (at-least-once).
37. A service must handle 10 million daily active users making 20 requests each. What is the average load?
Correct answer: ≈ 2,300 requests per second
200 million requests per day / 86,400 seconds ≈ 2,315 RPS on average. Peak load is usually 2–5× the average, and capacity is planned for it. Such back-of-the-envelope estimates are expected in interviews.
38. How does designing a read-heavy system differ from a write-heavy one?
Correct answer: Reads - caches and replicas; writes - queues and sharding
A product catalog is read thousands of times more often than it changes - it pays to cache and scale reads. Collecting metrics or logs is a stream of writes: ingestion via a queue, batch writes and partitioning matter.
39. How do you build an analytics dashboard over millions of events so it opens quickly?
Correct answer: Pre-aggregate data on the server and send the client only the needed points
Separate read models (CQRS, OLAP stores) keep aggregates by interval; a chart receives a downsampled series. Heavy analytics queries must not load the main database.
40. How would you design a notification system (email, push, in-app)?
Correct answer: Queue, user preferences, deduplication, retries
An event goes into a queue; the notification service checks preferences and quiet hours, picks channels, groups and deduplicates, and sends via providers with retries and rate limits. In-app notifications are stored on the server and delivered via SSE/WebSocket.
41. How do you deliver the result of a heavy operation (a 5-minute report export)?
Correct answer: Accept the job (202 Accepted), process it in the background and notify when ready
The server returns a job id, and the client tracks status (polling, SSE) or gets a notification with a link to the file in storage. Long HTTP requests get cut off by proxies and load balancers and scale poorly.
42. How can the frontend evaluate feature flags without UI flicker?
Correct answer: Evaluate flags on the server or edge and ship the result with the HTML
Loading flags on the client causes a "flash" of the old variant and layout shifts. Server-side evaluation (or bootstrapping values into the HTML) gives a stable first render. Flags are cached and included in the page cache key.
43. What should be minimized in logs and analytics for privacy?
Correct answer: Personal data: tokens, passwords, emails and the like in URLs and events
Tokens in query strings end up in server and proxy logs, and emails in analytics violate GDPR requirements. Mask fields, don't put secrets in URLs, limit log retention.
44. Why are signed links to private files made short-lived?
Correct answer: A leaked link quickly stops working
A signed URL grants access without authorization to anyone who has it. An expiry of minutes limits the damage from forwarding or leaks via logs and Referer. For long-term access, new links are issued after a permission check.
45. How does designing for strong consistency differ for a bank balance versus a like counter?
Correct answer: The balance needs transactions, likes don't
Consistency requirements are set by the domain: money needs ACID transactions and idempotency, while likes can be accumulated, aggregated asynchronously and shown with a delay ("1.2K"). The choice affects cost and scalability.
46. What are hedged requests and when are they useful?
Correct answer: Duplicating a slow request to another replica
If a response takes longer than usual, a copy is sent to another server and the first response wins. This lowers p99 at the cost of a small load increase. Suitable only for idempotent reads.
47. How do you keep the site working if the recommendations service is down?
Correct answer: Timeout, circuit breaker and a fallback without recommendations
Non-critical dependencies must not take down the main flow. Render the page, and show the recommendations block from cache, as popular products, or hide it. On the frontend - Suspense and an error boundary around the block, streaming instead of waiting.
48. How do you estimate storage requirements for 5 years of chat messages for 1M users?
Correct answer: Estimate volume: messages × size × retention, plus replicas
For example, 1M × 50 messages × 200 bytes ≈ 10 GB per day, ≈ 18 TB over 5 years before replication and indexes. Such an estimate drives the choice of storage, partitioning by conversation and time, and archiving of old data.
49. How does active-passive failover differ from active-active?
Correct answer: Passive nodes wait; active-active nodes all serve
Active-passive is simpler for consistency, but the standby sits idle and failover takes time. Active-active uses resources fully and survives a node failure unnoticed, but requires conflict resolution and load balancing.
50. Why should API responses for mobile clients be designed with long-lived old versions in mind?
Correct answer: Old app versions live on for months
Unlike the web, you can't "reload" all users. You need backward compatibility, versioning, forced updates for critical changes and metrics by client version.
51. Is "exactly-once" message delivery achievable in a distributed system?
Correct answer: In practice it's at-least-once plus idempotency
Brokers that advertise exactly-once rely on transactions and dedup within their boundaries; side effects outside still need idempotency.
52. One celebrity account gets millions of writes, overloading its partition. What helps?
Correct answer: Spreading the hot key with salting or sub-partitions
Hash partitioning spreads many keys, but one hot key still lands on one partition. Counters can be sharded and summed.
53. What are common options for tenant isolation in a multi-tenant SaaS?
Correct answer: Shared tables, a schema or a database per tenant
Row-level security in PostgreSQL enforces tenant filters in the database, reducing the risk of a forgotten
WHERE tenant_id.54. What data structure makes full-text search fast?
Correct answer: An inverted index from terms to documents
Search engines also store positions and statistics for ranking.
LIKE '%term%'can't use a normal index efficiently.55. How are metrics with billions of points stored cheaply?
Correct answer: In a time-series database with downsampling
Recent data stays high-resolution; older data is rolled up (e.g. 1-minute → 1-hour) to keep queries fast.
56. How would you implement a real-time game leaderboard?
Correct answer: With a sorted set, such as a Redis ZSET
Persist scores in a durable store; the sorted set acts as a fast, rebuildable index.
57. What does a Snowflake-style ID provide over random UUIDv4?
Correct answer: Roughly time-ordered IDs without coordination
Time-ordered keys keep B-tree inserts local. Clock skew between machines must be handled; UUIDv7 offers a similar property.
58. In a replicated store with N=3, why choose R=2 and W=2?
Correct answer: R + W > N makes read and write quorums overlap
Smaller quorums are faster and more available but may return stale data.
59. Why is two-phase commit rarely used across microservices?
Correct answer: It blocks participants and reduces availability
If the coordinator fails at the wrong time, participants hold locks until it recovers.
60. What is load shedding?
Correct answer: Deliberately rejecting some requests under overload
Failing fast with
503beats slowing everyone down until all requests time out. Prioritize critical paths like checkout.61. Why do serverless functions show latency spikes after idle periods?
Correct answer: Cold starts of a new execution environment
Smaller bundles, lazy initialization and provisioned/warm instances reduce cold-start impact.
62. After a WebSocket server outage, all clients reconnect at once and knock it over again. How do you prevent this?
Correct answer: Reconnect with exponential backoff and jitter
It's a thundering herd. Spreading reconnects over time lets the service recover.
63. Why do payment systems use an append-only double-entry ledger instead of a mutable
balancecolumn?Correct answer: Balanced entries give an auditable history
Corrections are new entries, not edits. A cached balance can be recomputed from the ledger.
64. How can you honor "right to be forgotten" requests when personal data lives in immutable event logs and backups?
Correct answer: Crypto-shredding: delete the per-user key
Keeping personal data out of event payloads (storing references instead) also helps.
65. How do you rename a database column without downtime?
Correct answer: Expand/contract: add, write both, switch, drop
During rolling deploys old and new code run together, so each step must be compatible with both.
66. What do RPO and RTO mean in disaster recovery?
Correct answer: Tolerable data loss and tolerable downtime
Lower values cost more: continuous replication and hot standby for minutes, periodic backups for hours.
67. What is chaos engineering?
Correct answer: Controlled experiments that inject failures
Start small with a hypothesis and a limited blast radius, ideally in production with safeguards.
68. How do data residency requirements (e.g. EU data stays in the EU) affect architecture?
Correct answer: Data must be stored and processed per region
Third-party tools (analytics, error tracking) must also respect the region.
69. 1M video views per day at 50 MB each - roughly what average egress bandwidth is needed?
Correct answer: About 4.6 Gbit/s on average
50 TB ÷ 86,400 s ≈ 0.58 GB/s ≈ 4.6 Gbit/s. This is why video is served from CDNs.
70. A service handles 1,000 requests/s with an average latency of 200 ms. How many requests are in flight on average?
Correct answer: About 200, by Little's law
This sizes thread pools and connection limits. If latency doubles at the same load, concurrency doubles too.
71. Why does a distributed lock need fencing tokens?
Correct answer: A paused client may still write after expiry
Lock expiry alone doesn't guarantee mutual exclusion in the presence of pauses and clock issues.
72. What is Change Data Capture (CDC) used for?
Correct answer: Streaming database changes to other systems
Reading the log avoids dual writes from application code and keeps derived stores eventually consistent.
73. A dashboard runs a heavy aggregation on every page load. What is a common fix?
Correct answer: Precompute results into a materialized view
It trades freshness for speed; show "updated N minutes ago" so users know the data lag.
74. How do you evolve event or message schemas without breaking consumers?
Correct answer: Make only backward and forward compatible changes
Producers and consumers are deployed independently; schema registries can enforce compatibility rules.
75. Why can sticky routing of WebSocket users to a server complicate deploys?
Correct answer: Restarting a server drops all its connections
Connection draining and spreading reconnects avoid sudden load spikes on the remaining servers.