Skip to lesson

System design interview questions and short answers

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Many interviews skip the full design round and ask short questions: "Replication or sharding?" "What is idempotency?" Try to answer each one aloud in two or three sentences before you read the answer.

Short answers across the section

Short answer is two or three sentences: a plain definition, when to use it, and one trade-off.

Cover the answer, say yours aloud, then compare. Questions 1 to 12 cover requirements, latency, availability, architecture, APIs and caching.

Example 1 · Questions 1–12: core ideas

Text
1  Functional vs non-functional requirement?   What the system does (place an order) vs how well (checkout in under 1 s, 99.9% up).2  Latency vs throughput?   Latency = time for one request; throughput = requests handled per second.3  Why look at p99 latency, not the average?   The average hides the slowest 1% of users, often the ones with the biggest carts.4  What does 99.9% availability allow?   About 43 minutes of downtime a month; 99.99% allows about 4.3 minutes.5  Monolith or microservices for a new product?   A (modular) monolith: one deploy, one DB; split only when team size or load demands it.6  What is a stateless server?   It keeps no user data in memory between requests, so any copy can serve any request.7  When do you use a queue?   For slow or optional work after the user's request: emails, PDFs, stock updates.8  What is an idempotency key?   A client-sent id stored with the first result, so a retry returns the same result.9  Offset or cursor pagination for a huge table?   Cursor (WHERE id > last ORDER BY id LIMIT n): fast at any depth, no shifting pages.10 How should a client retry?   Only on timeouts/5xx, with exponential backoff, jitter and a maximum number of attempts.11 What is cache-aside?   Read the cache; on a miss read the DB and put the result in the cache.12 How does an LRU cache evict?   It removes the entry that was used longest ago when it is full.
Covers
12 questions: requirements, latency, availability, architecture, APIs, caching

What this code does

  • Each answer is a definition plus when to use it, in about two lines.
  • Answers with numbers (p99, 43 minutes, cursor SQL) are easier to remember and sound stronger.

Add a number when you can (43 minutes of downtime a month for 99.9%): numbers make an answer sound real.

Concept pairs: cache vs CDN, replication vs sharding, and more

Concept pair is a question that compares two ideas that sound alike, such as cache vs CDN. Answer one line for each side and one line on when to pick which.

These are the pairs asked most often. Read them, then find the wrong sentence in three sample answers.

Example 2 · Questions 13–20: concept pairs

Text
13 Cache vs CDN?   A cache keeps data near the app (Redis); a CDN keeps files near users (edge servers).14 Replication vs sharding?   Replication copies all data to more servers (more reads, failover); sharding splits data   across servers (more writes and storage).15 Vertical vs horizontal scaling?   Vertical = a bigger machine (simple, has a ceiling); horizontal = more machines (needs   stateless servers and a load balancer).16 SQL vs NoSQL?   SQL for related data with transactions (orders); NoSQL for one access pattern at huge   scale or flexible shape (sessions, events).17 Sync vs async call?   Sync: the caller waits for the answer; async: the caller hands off work and moves on.18 Fan-out on write vs on read?   Write: push post ids into followers' feeds (fast reads); read: merge at view time   (cheap posts, fits celebrities).19 Fixed window vs token bucket?   Fixed window counts per minute and allows a burst at the boundary; token bucket   refills steadily and allows bursts only up to its capacity.20 Liveness vs readiness check?   Liveness: is the process alive (restart if not); readiness: can it take traffic now   (remove from the balancer if not).
Covers
8 pairs, each answered as side A, side B, when to pick which

What this code does

  • Every pair gives both sides; most also say when each one wins.
  • Replication vs sharding is the pair asked most often: copies for reads and failover, splits for writes and size.

The trap is answering only one side, or giving two definitions without saying when each wins.

Find the bug

Find the wrong sentence

Select the line that is wrong.

Cache vs CDN. Which sentence is wrong?

Round 1 of 3

Tricky follow-ups and saying "it depends" correctly

Tricky follow-up is a question about the limits of an idea, such as "Is a cache always good?". The honest answer usually starts with "it depends on...".

Each answer below names the condition and then commits to a choice.

Example 3 · Questions 21–30: tricky follow-ups

Text
21 "Is adding a cache always good?"   It depends on the hit ratio and how stale data may be: great for product pages,   wrong for stock during a flash sale unless it is very short-lived.22 "Would you choose consistency or availability?"   During a network split: consistency for payments and stock, availability for feeds.23 "Why not shard from day one?"   Cross-shard queries and transactions get hard; indexes, caching and replicas come first.24 "Can a load balancer be a single point of failure?"   Yes; run two in active-passive with a shared virtual IP, or use a managed one.25 "Is a message ever delivered exactly once?"   In practice queues give at-least-once; make consumers idempotent so a repeat is harmless.26 "What if the cache goes down?"   All reads hit the DB at once; protect it with timeouts, a rate limit and warming the cache.27 "Why is your token bucket per user and not global?"   One noisy client must not use up everyone's limit; a global cap can sit on top.28 "Why not just add more servers?"   Only if they are stateless and the bottleneck is CPU; a slow database gets worse with more servers.29 "How do you handle a hot key?"   Cache it (even in each server's memory), and for writes split the counter into parts.30 "When would you say 'it depends'?"   Always followed by what it depends on and a choice: "on the read/write ratio; here   reads are 100x, so I add a cache."
Pattern
10 follow-ups, each answered as "it depends on X; here I choose Y"

What this code does

  • Each answer names the condition and then commits to a choice.
  • Several reuse earlier lessons: at-least-once delivery, hot keys, cache stampedes, stateless servers.

"It depends" is a good answer only when you say what it depends on and then choose for this case. On its own it sounds like avoiding the question.

Mixed exercises: estimate, pick a design, find a flaw

Short rounds mix three tasks: estimate, pick a design, and find a flaw. First an estimate for ShopLite at 10 million users, then a bug in a shard function.

Example 4 · Estimate: 10 million daily users

QuickEstimateDemo.javaJava
public class QuickEstimateDemo {    public static void main(String[] args) {        long dau = 10_000_000;        int requestsPerUser = 30;        int peakFactor = 3;        int readPercent = 90;        int rpsPerServer = 500;
        long avgRps = dau * requestsPerUser / 86_400;        long peakRps = avgRps * peakFactor;        long writeRps = peakRps * (100 - readPercent) / 100;        long servers = (peakRps + rpsPerServer - 1) / rpsPerServer + 1; // +1 spare
        System.out.println("Average RPS: " + avgRps);        System.out.println("Peak RPS: " + peakRps);        System.out.println("Peak writes/s: " + writeRps);        System.out.println("App servers (500 RPS each, one spare): " + servers);    }}
Output
Average RPS: 3472
Peak RPS: 10416
Peak writes/s: 1041
App servers (500 RPS each, one spare): 22

What this code does

  • 10 million × 30 requests ÷ 86,400 gives about 3,472 requests per second on average, about 10,400 at a 3x peak.
  • With 90% reads, peak writes are about 1,040 per second, the number that decides the database plan.
  • Servers are rounded up, plus one spare so a crash does not overload the rest.

Example 5 · Find the flaw: Math.abs in a shard function

HashModBugDemo.javaJava
public class HashModBugDemo {    static final int SHARDS = 3;
    static int buggyShard(String key) {        return Math.abs(key.hashCode()) % SHARDS;    }
    static int shard(String key) {        return Math.floorMod(key.hashCode(), SHARDS);    }
    public static void main(String[] args) {        String[] keys = {"user-17", "priya@mail.in", "polygenelubricants"};        for (String key : keys) {            System.out.println(key + ": hashCode=" + key.hashCode()                    + " buggy=" + buggyShard(key) + " fixed=" + shard(key));        }        System.out.println("Math.abs(Integer.MIN_VALUE) = " + Math.abs(Integer.MIN_VALUE));    }}
Output
user-17: hashCode=-147182744 buggy=2 fixed=1
priya@mail.in: hashCode=-1498263189 buggy=0 fixed=0
polygenelubricants: hashCode=-2147483648 buggy=-2 fixed=1
Math.abs(Integer.MIN_VALUE) = -2147483648

What this code does

  • "polygenelubricants" has the hash code Integer.MIN_VALUE, and Math.abs of that is still negative, so the buggy shard is -2.
  • An array of 3 shards indexed with -2 throws ArrayIndexOutOfBoundsException for this one key, a rare and confusing bug.
  • Math.floorMod always returns 0 to n − 1, so it is the safe way to map a hash to a shard.

A classic flaw is Math.abs(key.hashCode()) % n. Math.abs(Integer.MIN_VALUE) is still negative in Java, so one rare key gets a negative shard number and crashes the lookup.

Math.floorMod(hash, n) always returns 0 to n - 1. Predict both.

Predict the output

Math.abs against floorMod

Read the code and pick what it prints.

Round 1 of 2

A key has the hash code Integer.MIN_VALUE and there are 3 shards. What is printed?

public class HashShard {
public static void main(String[] args) {
int hash = Integer.MIN_VALUE;
System.out.println(Math.abs(hash) % 3);
}
}

Rapid-fire round

Rapid-fire round is a run of one-line questions with no time to think. Answer with the key fact only.

Cover the right column and answer all ten in under a minute.

Example 6 · Rapid-fire self-test

Text
Status for "too many requests"?            429, with Retry-AfterStatus for a redirect that counts clicks?  302Seconds in a day?                          86,400 (about 10^5)One write path rule for caches?            update the DB, then delete the cache entryWhere does a celebrity's post go?          fetched at read time, not pushedQueue for jobs that keep failing?          dead-letter queueShard key for "my orders"?                 user idTwo copies at 99% each, in parallel?       99.99%Base62 symbols?                            0-9, a-z, A-ZFirst thing in a design round?             clarify requirements
Target
10 answers in under a minute

What this code does

  • Each answer is a fact from this section, short enough to say in one breath.
  • If one takes you more than a few seconds, go back to the lesson it came from.

If one answer takes you more than a few seconds, go back to the lesson it came from.

Finish up

Mark complete & continue

Next: Milestone project: ShopLite at scale