Flashcards
Reading a page once is not the same as being able to recall it in an interview. This deck turns the key ideas of every section into questions you answer from memory, and schedules each card so that you see the hard ones often and the easy ones rarely. The original System Design Primer shipped Anki decks; this deck replaces them and stays in sync with the pages on this site.
Why spaced repetition
Section titled “Why spaced repetition”You forget most of what you read within days, and each successful recall slows that forgetting down. Spaced repetition uses this: review a fact just before you would forget it, and the gap before the next review can grow. Two habits make it work. Active recall: answer from memory before seeing the answer. Spacing: return to each card at growing intervals instead of cramming them all in one evening.
Flashcards suit facts, definitions, numbers and short trade-offs: what PACELC adds to CAP, how many round trips a new HTTPS connection costs, when a write-behind cache loses data. They do not replace practising whole designs out loud; use them alongside the study plan and the interview framework.
The deck
Section titled “The deck”Turn on JavaScript to study with spaced repetition. You can still browse every card below.
- Due
- 0
- Learned
- 0
- Total
- 150
Question
0 left in this round
Practice round: answers here do not change your schedule.
Keys: Space flips · 1 again · 2 got it
Progress is saved in this browser only.
Browse all cards (150)
Fundamentals Performance problem or scalability problem: how do you tell them apart?
Read more: Performance vs scalability →A performance problem shows up with one user: every request is slow, even on an idle system. Fix it with profiling, indexes and better algorithms.
A scalability problem shows up under load: one user is fine, ten thousand are not. Fix it by adding capacity, removing the shared bottleneck, caching or partitioning.
Fundamentals Scale up or scale out: what does each buy and cost?
Read more: Performance vs scalability →Scale up (a bigger machine): no code changes and simple operations, but a hard ceiling, a steep price at the top and a single point of failure.
Scale out (more machines): near-linear capacity and redundancy, but only for stateless tiers or data you can partition.
Default: scale up while it is cheap, and design for scale-out where you know you will need it.
Fundamentals What does Amdahl's law say about adding workers?
Read more: Performance vs scalability →With a parallel fraction
ponNworkers, the speed-up is1 / ((1 − p) + p / N), and it can never exceed1 / (1 − p). At 95% parallel the limit is 20×, at 99% it is 100×.In a web system the serial part is whatever every request passes through one at a time: a single primary, a global lock, a hot row.
Fundamentals Why report latency as percentiles rather than an average?
Read more: Latency vs throughput →Latency is skewed, so the mean describes no real request. In the page's example of 1,000 requests, the mean is 38.9 ms, while p50 is 20 ms and p99 is 400 ms.
Set targets on p99 or p99.9, and never average percentiles across servers: merge histograms and compute the percentile from the merged data.
Fundamentals 1% of servers are slow at any moment. How often does a request that touches 100 servers hit at least one slow one?
Read more: Latency vs throughput →1 − 0.99^100 ≈ 63%. The response is only as fast as the slowest shard, so at a fan-out of about 70 a backend's p99 becomes the frontend's median.Mitigations: hedged requests, partial results, fewer hops, and a deadline for each hop.
Fundamentals State Little's law and size a thread pool with it.
Read more: Latency vs throughput →L = λW: requests in flight = arrival rate × time in system.An API at 2,000 requests/s with 150 ms per request has 300 requests in flight. A pool of 200 threads therefore caps out at about 1,333 requests/s at that latency. The same arithmetic sizes connection pools and queues.
Fundamentals What happens to latency as a server's utilisation approaches 100%?
Read more: Latency vs throughput →It explodes. In the single-queue model, mean response time is
W = S / (1 − ρ): 2× the service time at 50% busy, 10× at 90%, 100× at 99%.Keep headroom for peaks and failover, bound every queue, and treat a rising p99 as an early warning.
Fundamentals What does the CAP theorem actually say?
Read more: CAP theorem and PACELC →Only during a network partition must a replicated system choose, per operation: stay consistent (linearizable, so some requests fail or time out) or stay available (every non-failing node answers, possibly with stale data).
Partitions are not optional, so “pick 2 of 3” is misleading, and only a single-node system is truly “CA”.
Fundamentals What does PACELC add to CAP?
Read more: CAP theorem and PACELC →If Partitioned, choose Availability or Consistency; Else, choose Latency or Consistency. The “else” half is paid on every request, not only during failures.
Cassandra and the original Dynamo are PA/EL; Spanner, CockroachDB and etcd are PC/EC. Modern databases are consistent by default and offer stale reads on request.
Fundamentals When does a quorum read see the latest write, and is that enough for linearizability?
Read more: CAP theorem and PACELC →With
Nreplicas, a write waits forWacks and a read asksRreplicas. IfR + W > N(say N = 3, W = 2, R = 2), every read set overlaps every write set.Overlap is not linearizability: concurrent writes, partially failed writes and sloppy quorums can still produce anomalies.
Fundamentals A user edits their profile, refreshes and sees the old version. Which guarantee is missing, and how do you provide it?
Read more: Consistency patterns →Read-your-writes. Options:
- read from the leader for a short window after the user writes;
- pin the session to one replica (sticky routing);
- return the write's log position (an LSN or version) and read only from a replica that has applied it.
Fundamentals Linearizability vs serializability: what is the difference?
Read more: Consistency patterns →Linearizability: single-object operations appear atomic and in real-time order, as if there were one copy. You need it for “check then act”: locks, claiming a username.
Serializability: transactions appear in some serial order, not necessarily the real-time one. Strict serializability (Spanner's external consistency) is both.
Fundamentals How do availabilities combine in series and in parallel?
Read more: Availability patterns →In series (every part is needed) availabilities multiply: 99.99% × 99.95% × 99.95% ≈ 99.89%, worse than any single part.
In parallel (any copy will do) failure probabilities multiply: two servers at 99.5% give
1 − 0.005² = 99.9975%. That holds only if the copies fail independently.Fundamentals RTO vs RPO, and what do hot, warm and cold standbys give you?
Read more: Availability patterns →RTO: how long you may be down. RPO: how much recent data you may lose.
- Hot standby: seconds to a minute; zero RPO with synchronous replication; about 2× the cost.
- Warm: minutes, because it must scale up; seconds of data.
- Cold: hours; everything since the last backup.
Fundamentals What is an error budget, and what happens when it runs out?
Read more: Availability patterns →The budget is
1 − SLO. A 99.9% SLO over 30 days allows 43.2 minutes of full outage, or 100,000 failed requests out of 100 million.While budget remains, ship features and take risks. When it is spent, the error budget policy freezes risky releases until the service is back within its SLO.
Fundamentals How many voting nodes does a consensus group need, and why use odd sizes?
Read more: Consensus and coordination →A decision needs a majority, so
2f + 1nodes tolerateffailures: 3 survive 1, 5 survive 2, 7 is the practical ceiling.Four nodes need 3 votes and still tolerate only one failure, so the fourth adds cost and latency, not resilience. To scale reads, add non-voting members (etcd learners, ZooKeeper observers); spread voters across zones.
Fundamentals How does Raft elect a leader and commit a log entry?
Read more: Consensus and coordination →Time is split into numbered terms with at most one leader each; a node that sees a higher term steps down, which makes a deposed leader harmless. A follower that hears no heartbeat for a randomised election timeout asks for votes; a majority makes it leader, and only candidates with an up-to-date log can win.
The leader appends commands and replicates them; an entry is committed once a majority has stored it.
Fundamentals A client holds a lease-based lock, pauses for a long GC, and the lease expires. How do you keep it from corrupting data?
Read more: Consensus and coordination →No lease can stop a paused client by itself, so the resource must protect itself. A fencing token grows with every lock grant (an etcd revision, a ZooKeeper zxid); the client sends it with each write, and storage rejects any token lower than the highest it has seen.
Or use conditional writes. A Redis lock without fencing is fine for efficiency, not for correctness.
Fundamentals What does a consensus commit cost, and when should you avoid running consensus yourself?
Read more: Consensus and coordination →About one round trip to the nearest follower plus an
fsync: ≈ 1.2 ms in one zone, ≈ 2 ms across three zones, ≈ 81 ms with followers across an ocean.Don't implement Raft or Paxos. Prefer, in order: your database (unique constraint, transaction, conditional write), your platform (Kubernetes Leases), a coordination service with 3 or 5 voters. Many “exactly once” problems need idempotency, not a lock.
Networking & traffic Walk through a DNS lookup from the browser to the answer.
Read more: Domain Name System (DNS) →The OS stub resolver asks a recursive resolver, which follows referrals from a root server to the TLD server to the authoritative server for the zone.
Root and TLD referrals carry long TTLs, so a warm resolver usually goes straight to the authoritative server, and caches at every layer make most lookups a single local hop.
Networking & traffic How do you pick a DNS TTL, and how do you prepare a migration?
Read more: Domain Name System (DNS) →Short TTLs (30–60 s) move traffic quickly but raise query volume and cache misses; long TTLs (hours) are cheap but slow to change.
Before a migration: lower the TTL, wait at least one old TTL, switch, then raise it again. Some clients ignore TTLs, so don't plan on DNS failover faster than about a minute.
Networking & traffic GeoDNS vs anycast: how does each steer users, and how fast does it react to a failure?
Read more: Domain Name System (DNS) →GeoDNS returns different answers per resolver location: fine-grained control, but it sees the resolver rather than the user and reacts only after a TTL and client caches.
Anycast announces one IP from many sites over BGP: failover in seconds to a minute, and attack traffic spreads over all sites, but control is coarse. Large providers combine both.
Networking & traffic Push CDN vs pull CDN: when do you use each?
Read more: Content delivery networks (CDN) →Pull: the edge fetches from the origin on the first miss and keeps what users request. Suits busy sites, long-tail catalogues and APIs.
Push: you upload content ahead of time. Suits large files with predictable demand (installers, game patches) and small sites that rarely change.
The common setup today is a pull CDN in front of object storage.
Networking & traffic What is the best way to change content that a CDN has cached?
Read more: Content delivery networks (CDN) →Best: versioned URLs. Put a content hash in the file name (
app.3f9c2b.js) and cache it forever; a deploy publishes new names, with no purge and no races.Next best: tag-based purge, then URL or prefix purge. Purging everything is a last resort: every PoP misses at once and the origin takes a stampede.
Networking & traffic What does an origin shield do, in numbers?
Read more: Content delivery networks (CDN) →It adds one upper-tier cache between the PoPs and the origin and collapses concurrent misses into a single origin fetch.
Without it, 300 PoPs with a 60-second TTL can send up to 5 requests per second for one popular object. With a shield it is one request per object per 60 seconds, at the cost of an extra hop on misses.
Networking & traffic Layer 4 vs layer 7 load balancing: what is the difference?
Read more: Load balancers →L4 works on TCP/UDP flows: it picks a backend once per connection by IP and port, without reading the payload. Fast, cheap, any protocol.
L7 terminates the connection, parses HTTP or gRPC and picks a backend per request: routing by path, header or cookie, TLS, retries, per-request metrics.
Gotcha: under L4, long-lived HTTP/2 or gRPC connections pin a client's load to one backend.
Networking & traffic Some requests take 10 ms and others 2 s. Which balancing algorithm do you choose?
Read more: Load balancers →Least outstanding requests, or power of two choices: pick two servers at random and send to the less loaded one. P2C removes most of the imbalance of pure random choice and suits many independent balancers or sidecars.
Round robin only fits uniform requests. For key affinity use consistent hashing: growing from 10 to 11 servers moves about 9% of keys, versus about 91% with
hash mod N.Networking & traffic Sticky sessions or stateless app servers?
Read more: Load balancers →Sticky sessions pin a user to the server holding their state: load becomes uneven, a crash loses those sessions, and scaling in waits for sessions to drain.
Default to stateless servers: keep sessions in a signed token or a shared store such as Redis or Valkey, and files in object storage. Use stickiness only as an optimisation that nothing depends on.
Networking & traffic What can go wrong with load balancer health checks?
Read more: Load balancers →- A deep check that queries a shared database fails on every server when the database blips, and the balancer has nowhere to send traffic. Keep checks mostly local.
- Detection is slow: with AWS ALB defaults (30-second interval, 2 failures) a dead server gets traffic for about a minute.
- Know whether the balancer fails open when every check fails; drain connections on deploy and slow-start new instances.
Networking & traffic Reverse proxy, load balancer, API gateway: what does each do?
Read more: Reverse proxy and API gateway →- Reverse proxy: one controlled front door for TLS, caching, compression, static files and filtering; useful even with a single backend.
- Load balancer: a reverse proxy whose main job is spreading load across identical servers and surviving their failures.
- API gateway: cross-cutting API concerns for many services: authentication, quotas, routing, versioning. Keep business logic out of it.
Architecture What is a modular monolith, and why is it the default?
Read more: Monolith, modular monolith and microservices →One deployable whose modules have explicit public interfaces, enforced dependency rules and their own tables.
It keeps one build, one deploy and in-process calls, while getting most of the design benefits of services. Its seams also make it the easiest system to split later. Shopify is the best-known example.
Architecture When do microservices pay off, and what do they cost?
Read more: Monolith, modular monolith and microservices →They pay off for mostly organisational reasons: many teams that need to deploy independently, very different scaling profiles, fault or security isolation.
Costs: network calls instead of function calls, partial failure, no cross-service transactions or joins, and heavy platform work. Ten services in sequence at 99.9% each succeed only about 99.0% of the time. The worst outcome is a distributed monolith.
Architecture How do you migrate away from a legacy system without a big-bang rewrite?
Read more: Monolith, modular monolith and microservices →The strangler fig pattern:
- Put a routing layer (reverse proxy or API gateway) in front of the legacy system.
- Rebuild one capability with a clear seam and shift its traffic gradually.
- Keep data in sync with CDC or an outbox during the move.
- Delete the old code path, then repeat.
Architecture Client-side vs server-side service discovery?
Read more: Service discovery and service mesh →Client-side: the caller queries the registry, caches the list and balances itself. No extra hop and smart per-request balancing, but every language needs a library.
Server-side: the caller hits a load balancer or virtual IP that does the lookup. Simple clients, but an extra component, and an L4 VIP pins long-lived gRPC connections.
On Kubernetes, Services, EndpointSlices and cluster DNS provide discovery out of the box.
Architecture What does a service mesh give you, and when is it overkill?
Read more: Service discovery and service mesh →Without code changes: mTLS with workload identities, timeouts, retries with budgets, traffic splitting for canaries, and uniform per-service metrics. Data planes are sidecars, sidecar-less “ambient” mode, eBPF or proxyless gRPC.
It is overkill with a few services owned by one team, or when nobody can own the control plane. Start from a concrete need such as “we need mTLS”.
Architecture How do you reason about latency for an LLM response, and why stream it?
Read more: LLM-powered systems →End-to-end ≈
TTFT + TPOT × (output tokens − 1). Time to first token covers queueing, retrieval and prefill (grows with prompt length); time per output token is a decode step (memory-bandwidth-bound).With 0.5 s TTFT, 20 ms per token and 300 tokens, the answer takes about 6.5 s, but streaming over SSE shows text after half a second. Don't buffer on the path, and cancel generation when the client leaves.
Architecture Why budget, price and rate-limit an LLM feature in tokens rather than requests?
Read more: LLM-powered systems →One request can cost a hundred times another. In the page's example (5 M requests a day, 2,000-token prompts, 300-token answers) input is 57% of a $17,500/day bill even though input tokens are five times cheaper; caching a repeated 60% prefix cuts the total by about 31%.
So use token buckets charged in tokens, concurrency limits on open streams and per-tenant budgets.
Architecture RAG over company documents: what are the hard parts?
Read more: LLM-powered systems →- Chunking into passages of a few hundred tokens, keeping titles and section paths.
- Hybrid search: vectors plus BM25 for exact terms, then a reranker over a broad candidate set.
- Freshness: the index is derived data fed by change events; deletions must apply fast.
- Permissions: store ACLs with each chunk and filter at retrieval time — never ask the model to hide what the user may not see.
Architecture How do resilience patterns change when the dependency is an LLM?
Read more: LLM-powered systems →- Separate timeouts for the first token, idle gaps between tokens and the whole call.
- Retry before the stream starts, not during it: a mid-stream retry produces a different second half.
- Fall back to another model behind a model gateway, with a circuit breaker per provider, and run the fallback through the same evals.
- Validate structured output; give each tool call an idempotency key.
- Treat output as untrusted input: no prompt-level defence fully stops prompt injection.
Databases & storage Define each letter of ACID precisely.
Read more: Relational databases →- Atomicity: all of a transaction's writes take effect, or none do.
- Consistency: each transaction keeps declared invariants; mostly your job, and not the C in CAP.
- Isolation: concurrent transactions don't see each other's partial work, to a chosen level.
- Durability: once
COMMITreturns, the change survives a crash, because the WAL is flushed first.
Databases & storage What are the default isolation levels of PostgreSQL and MySQL, and do they prevent write skew?
Read more: Relational databases →PostgreSQL: read committed. MySQL InnoDB: repeatable read. Neither prevents write skew.
Write skew: two transactions read the same data and write different rows, breaking an invariant together (both on-call doctors go off duty). Fix it with
SELECT … FOR UPDATE, a constraint, or serializable isolation plus retries.Databases & storage What is MVCC, and what is its operational catch?
Read more: Relational databases →Multi-version concurrency control keeps several versions of each row; a reader sees the newest version committed before its snapshot, so readers and writers don't block each other.
Catch: old versions must be cleaned up (
VACUUMin PostgreSQL, purge of the undo log in InnoDB). A transaction left open for hours pins them, bloating tables or the undo history.Databases & storage B-tree vs LSM-tree: which workloads does each favour?
Read more: Relational databases →B-tree (PostgreSQL, InnoDB): change pages in place, predictable point reads and range scans. Read-heavy OLTP.
LSM-tree (RocksDB, Cassandra, CockroachDB): append to a log and memory buffer, flush sorted files and compact later. High write throughput; reads may check several files, with Bloom filters skipping most. Write-heavy ingestion.
Databases & storage In what order do you scale a relational database?
Read more: Relational databases →- Tune queries, indexes and schema (often 10× to 1000× for one query).
- Scale up.
- Pool connections and cache.
- Add read replicas.
- Federate or shard.
Each step costs more complexity than the last, so climb only when measurements show the current step is exhausted.
Databases & storage Synchronous, asynchronous or semi-synchronous replication: what do you trade?
Read more: Replication →- Async: no commit latency, but failover can lose the last transactions.
- Sync: no loss if a sync replica is promoted, but every commit waits a round trip, and writes stall if the replica is unreachable.
- Semi-sync / quorum: wait for the fastest k replicas.
Watch out: MySQL semi-sync silently falls back to async after a 10-second timeout.
Databases & storage What is split brain, and how do you prevent it?
Read more: Replication →Two nodes both believe they are the leader and both accept writes, so the data diverges and merging is manual.
Defences: a majority quorum for leader election, fencing tokens (a higher epoch per leader, and storage rejects older ones), and STONITH. GitHub's 43-second partition in 2018 left the site degraded for 24 hours and 11 minutes.
Databases & storage Multi-leader replication: how are write conflicts resolved?
Read more: Replication →From crude to careful:
- Avoid them: route each record's writes to one home leader (the most effective).
- Last-writer-wins: simple, but silently drops writes and lets clock skew pick the winner.
- Merge siblings tracked by version vectors.
- CRDTs, which always converge.
- Detect and abort, as MySQL Group Replication does.
Databases & storage Can read replicas fix a write bottleneck? Are replicas backups?
Read more: Replication →No to both. Every replica applies every write, so replicas add read capacity, never write capacity; for writes you need partitioning.
A bad migration or
DROP TABLEreplicates within milliseconds, so keep point-in-time backups and delayed replicas as well.Databases & storage Federation vs sharding?
Read more: Partitioning and sharding →Federation splits by function: users, orders and catalogue each get their own database. It matches service ownership, but there are no cross-database joins or transactions, and it stops helping once one domain outgrows a server.
Sharding splits one dataset by key across servers, so it scales writes and data size within a domain.
Databases & storage What makes a good shard key?
Read more: Partitioning and sharding →- High cardinality: millions of distinct values.
- Even spread of both data and traffic.
- Matches the dominant queries, so they stay on one shard (
tenant_idfor B2B SaaS,user_idfor consumer apps). - Stable: changing it means moving the row.
Avoid a raw timestamp: in a range-sharded cluster all new writes land on the last shard.
Databases & storage Hash, range and directory sharding: the strength and weakness of each?
Read more: Partitioning and sharding →- Hash: even spread even with sequential keys, but range queries hit every shard.
- Range: efficient range scans and easy splits, but sequential keys create a hot last shard.
- Directory: any placement and per-tenant moves, but the lookup service must be fast, cached and highly available.
A common hybrid: hash into many logical shards and map them to servers with a small directory.
Databases & storage Why consistent hashing instead of
hash % N, and why virtual nodes?Read more: Partitioning and sharding →With
hash % N, going from 4 to 5 servers moves about 80% of keys. On a ring, a key belongs to the first server clockwise, so a joining node takes only about 1/(N+1) of the keys (20% going from 4 to 5).Virtual nodes (many ring positions per server; Cassandra uses 16 tokens per node by default) even out the arcs, let bigger machines take more, and spread a failed server's load over all survivors.
Databases & storage One celebrity key overloads its shard. What are your options?
Read more: Partitioning and sharding →- Split the key: append a suffix 0–9 so writes spread over ten shards (50,000 writes/s becomes about 5,000 per shard); reads gather all ten.
- Cache it: most celebrity traffic is reads.
- Give it its own shard through a directory.
- Handle it on read, as timelines do for celebrity posts.
Automatic splitting cannot divide a single row's traffic.
Databases & storage What do queries without the shard key cost, and how do you handle cross-shard transactions?
Read more: Partitioning and sharding →They become scatter-gather across every shard, paced by the slowest: with a 1% chance of a slow shard, a 32-shard fan-out hits one 27.5% of the time. Add global secondary indexes, co-locate related tables by the same key, and copy small reference tables to every shard.
Two-phase commit blocks if the coordinator fails, so keep invariants within one shard and use sagas for workflows.
Databases & storage When does denormalisation pay off, and what must you decide?
Read more: Denormalisation and SQL tuning →When reads vastly outnumber writes and joins are the bottleneck. A join costing 2 ms at 10,000 reads/s burns 20 s of database time per second; keeping a copy at 1 ms × 100 writes/s costs 0.1 s.
Decide who keeps the copies in sync (same transaction, trigger, materialized view or CDC) and run a reconciliation job to catch drift.
Databases & storage How do you design a composite index for a query?
Read more: Denormalisation and SQL tuning →Equality columns first, then the range or sort column:
(customer_id, created_at)servesWHERE customer_id = ? ORDER BY created_at. Make it covering if possible. In the page's example the plan dropped from about 17,000 pages and 143 ms to 7 pages and under 0.1 ms.Indexes don't help unselective filters (a status matching a quarter of the table), and every index slows writes.
Databases & storage What are N+1 queries and OFFSET pagination costing you?
Read more: Denormalisation and SQL tuning →N+1: 50 posts then each author is 51 queries, about 25 ms of round trips at 0.5 ms each; eager loading or a join makes it two (about 1 ms).
OFFSET:
OFFSET 1000000reads and discards a million rows, and pages shift on inserts. Keyset pagination (WHERE (created_at, id) < ($1, $2)) served page 50,001 in 0.18 ms instead of 226 ms.Databases & storage Why put a connection pooler in front of PostgreSQL, and what does transaction mode break?
Read more: Denormalisation and SQL tuning →PostgreSQL runs one OS process per connection, so thousands of mostly idle connections from autoscaled app servers waste memory and throughput. PgBouncer multiplexes them onto a few dozen server connections, sized near the core count times a small factor.
Transaction mode, the usual choice, breaks session state:
SET,LISTEN, session advisory locks andWITH HOLDcursors.Databases & storage Name the four classic NoSQL families and what each is good at.
Read more: NoSQL databases →- Key-value (Redis, DynamoDB): lookups by key at extreme throughput.
- Document (MongoDB, Firestore): whole aggregates read in one go, flexible fields.
- Wide-column (Cassandra, Bigtable): write-heavy, time-ordered data at scale.
- Graph (Neo4j, Neptune): multi-hop traversals.
Three more matter in 2026: time-series, search engines and vector stores.
Databases & storage How does NoSQL data modelling differ from relational modelling?
Read more: NoSQL databases →Relational modelling starts from entities; NoSQL starts from queries.
- List every access pattern with its rate and latency target.
- Choose partition and sort keys so each pattern reads one partition.
- Denormalise the fields each query needs.
- Add secondary indexes for the rest.
- Check for hot partitions (DynamoDB: 3,000 read and 1,000 write units per second per partition).
Databases & storage SQL or NoSQL for a new product?
Read more: SQL or NoSQL →Start relational (usually PostgreSQL) unless a clear requirement rules it out: writes beyond one primary, single-digit-ms latency at huge scale, or a data model it handles badly. If you cannot list the queries yet, you need SQL's flexibility.
Choose NoSQL for a specific workload with known access patterns. Keep one system of record per piece of data; treat every other copy as a rebuildable cache or index.
Databases & storage What does distributed SQL (Spanner, CockroachDB, YugabyteDB) give you, and at what price?
Read more: SQL or NoSQL →SQL and ACID transactions with horizontal write scaling, automatic rebalancing and survival of node or zone failures without manual failover.
Price: every commit needs a consensus round trip, so writes take a few ms within a region and tens to hundreds across regions; cross-range transactions cost more; some features are missing; hot rows still serialise.
Databases & storage What is the standard storage pattern for user uploads?
Read more: Object storage →Metadata in a database, bytes in object storage, a CDN in front. Clients upload and download directly with short-lived presigned URLs, so app servers never proxy bytes.
Give each version a new key so CDN caches never need purging, validate uploads asynchronously, and reconcile orphans between the two stores.
Databases & storage Durability vs availability for object storage such as S3 Standard?
Read more: Object storage →Durability (will the data survive?) is designed at 11 nines: store 10 million objects and expect to lose one about once every 10,000 years. Availability (can I read it now?) is 99.99%, about 53 minutes of errors a year.
The bigger durability risk is people and software, so use versioning, object lock and cross-account replication. S3 has been strongly consistent since December 2020.
Caching Why does caching work, and what makes a cache “load-bearing”?
Read more: Caching layers →Access is skewed: with a Zipf exponent of 1 over a million items, the top 1% get about 68% of requests. Recently used data is also likely to be used again.
At a 95% hit ratio the database sees 5% of reads; if the cache is flushed or restarted, it suddenly gets 20× its usual load. Plan for that cold-cache case.
Caching How does hit ratio translate into latency and database load?
Read more: Caching layers →Effective latency =
h·t_cache + (1−h)·t_origin. With Redis at 0.5 ms, a 20 ms query and 50,000 reads/s:- 90% hits: 2.5 ms, 5,000 reads/s reach the database;
- 99% hits: 0.7 ms, 500 reads/s.
The last few percent matter most: 90% → 99% cuts database load tenfold.
Caching Why cache objects rather than query results?
Read more: Caching layers →A query-level key is a hash of SQL and parameters; when one row changes you cannot tell which cached queries included it. That is why MySQL's query cache was removed in 8.0.
An object-level key comes from domain identity (
user:v1:42), so a change maps to known keys to delete, and every reader of the object shares the entry.Caching Describe cache-aside (lazy loading): the read path, the write path and the risks.
Read more: Cache strategies →Read: check the cache; on a miss, load from the database and store it with a TTL. Write: update the database, then delete the key.
Only requested data is cached and the cache can fail without losing data. Costs: a miss takes three round trips, data is stale until TTL or delete, and slow first reads after a flush.
Caching Write-through vs write-behind?
Read more: Cache strategies →Write-through: write to the cache, which writes the database synchronously. Fresh after every write through that path, but each write pays both latencies, and writes that bypass the cache go stale.
Write-behind: acknowledge after the cache write and flush to the database later, often batched. Very fast and coalesces updates, but data is lost if the cache fails before flushing. Never for payments without a durable log.
Caching On write, why delete the cache key instead of setting the new value, and in which order?
Read more: Cache strategies →Two writers that set values can reach the cache in a different order from their database commits and leave the older value cached. A delete is idempotent, so the order doesn't matter, and the next reader loads the latest value.
Commit first, then delete; deleting first lets a reader refill the old value. Keep a TTL as the backstop for the remaining race.
Caching What is a cache stampede, and how do you prevent it?
Read more: Cache strategies →A hot key expires (or the cache restarts) and hundreds of concurrent misses hit the database with the same expensive query. Fixes:
- TTL jitter;
- request coalescing (single-flight);
- a short lock or lease: Facebook's leases cut the peak from 17,000 to 1,300 queries/s;
- serve stale while one request revalidates;
- probabilistic early expiration (XFetch).
Caching Cache penetration and hot keys: what are they and how do you fix them?
Read more: Cache strategies →Penetration: requests for keys that don't exist always miss and always reach the database. Fix with negative caching (cache “not found” briefly), a Bloom filter of valid IDs, and input validation.
Hot keys: one key saturates its cache shard. Fix with a local L1 cache with a TTL of a second or two, or key replicas (
item:42#0…#7), reading one at random.Caching LRU, LFU or W-TinyLFU? And what is the Redis/Valkey default eviction policy?
Read more: Cache strategies →LRU suits recency-driven workloads, but one scan flushes the hot set. LFU suits stable popularity but is slow to forget. W-TinyLFU (Caffeine) admits a newcomer only if a frequency sketch says it beats the victim, so it resists scans.
Redis and Valkey default to
noeviction: writes fail when memory is full. For a cache setmaxmemoryandallkeys-lruorallkeys-lfu.Async & messaging When should a step go through a queue, and when not?
Read more: Message queues and back pressure →Use a queue for slow work (answer
202 Acceptedwith a job ID), bursty load (absorb a 10× spike and process at a steady rate) and decoupling producers from consumers.Don't when the user needs the answer now, the work is cheap, read-your-writes matters, or the system is small. A table with
SELECT … FOR UPDATE SKIP LOCKEDis a fine queue at modest volume.Async & messaging Why do message queues deliver duplicates, and how do you get effectively-once processing?
Read more: Message queues and back pressure →Real brokers deliver at least once: a worker can commit and crash before the ack, a lease can expire mid-job, or a producer can resend after a timeout.
Effectively-once = at-least-once + an idempotent consumer: a natural upsert, or recording processed message IDs in the same transaction as the side effect. External calls need an idempotency key.
Async & messaging How should a consumer handle acks, retries and poison messages?
Read more: Message queues and back pressure →- Ack after commit, never before.
- Set the visibility timeout above p99 processing time, extending it from a heartbeat for long jobs.
- Retry transient errors with a delay; dead-letter malformed payloads at once.
- Cap attempts and move failures to a dead-letter queue; alert when it holds anything and keep a redrive tool.
Async & messaging What is back pressure, and how do you apply it?
Read more: Message queues and back pressure →Pushing overload back to the source instead of letting an unbounded queue turn it into minutes of latency and memory exhaustion.
- Bound every queue.
- Reject at the edge:
429for one client over quota,503when the service is saturated, both withRetry-After. - Shed low-value or expired work first.
- Watch the age of the oldest message, not just depth.
Clients retry with exponential backoff and full jitter.
Async & messaging Size a worker pool: 400 jobs/s, 0.5 s per job. And how long does a 10-minute backlog take to drain?
Read more: Message queues and back pressure →In flight: 400 × 0.5 = 200. For 70% utilisation, 286 slots: 18 pods × 16 = 288 slots, maximum 576 jobs/s.
A 10-minute outage leaves 240,000 jobs. They drain at 576 − 400 = 176 jobs/s, about 23 minutes; 25 pods would take 10 minutes. Headroom decides how fast you recover.
Async & messaging How does ordering work in a Kafka-style log, and how do you choose the partition key?
Read more: Event streaming and logs →Order exists per partition only. Pick the key by the invariant: if “payment captured” must follow “order placed”, both use the order ID.
Watch out: hot keys make hot partitions; adding partitions remaps keys and breaks per-key order during the change (so over-provision up front); and retries reorder unless the producer is idempotent.
Async & messaging How do consumer groups and offsets work, and what is the key health metric?
Read more: Event streaming and logs →Each partition goes to at most one member of a group: 12 partitions and 4 members means 3 each, and a 13th member sits idle. Parallelism is capped by the partition count. Other groups read independently with their own offsets.
Commit after processing for at-least-once. Watch consumer lag, converted to time, and alert when it keeps growing.
Async & messaging What does “exactly-once” in Kafka really cover?
Read more: Event streaming and logs →A consume → transform → produce loop that stays inside Kafka, built from the idempotent producer, transactions that write outputs and commit offsets atomically, and
read_committedconsumers.Once you write to Postgres, call an API or send an email, you are back to at-least-once plus idempotence, which is why “effectively-once” is the more honest name.
Async & messaging A service must update its database and publish an event. How do you avoid a dual write?
Read more: Event streaming and logs →Transactional outbox: insert the event into an
outboxtable in the same local transaction as the business change. A relay publishes it, usually via CDC that tails the replication log (Debezium).The event is published if and only if the transaction commits, in commit order. The relay may publish twice, so consumers dedupe by event ID.
Async & messaging Message queue or log: when do you use which?
Read more: Event streaming and logs →Queue (RabbitMQ, SQS): a message is deleted on ack; competing workers share one queue; per-message retries and DLQ are built in. Use it to distribute work.
Log (Kafka, Kinesis, Pulsar): records stay until retention; many independent groups read with their own offsets and can replay; strict order per partition. Use it to distribute facts.
Communication & APIs Which HTTP methods are safe, which are idempotent, and how do you retry a POST safely?
Read more: HTTP →Safe (no state change requested): GET, HEAD, OPTIONS, TRACE and the new QUERY (RFC 10008). Idempotent: the safe ones plus PUT and DELETE, so clients and proxies can retry them.
POST and PATCH are neither; make them retry-safe with an idempotency key. In practice caches store GET and HEAD responses; QUERY is cacheable, but support is still new.
Communication & APIs
no-cachevsno-store,privatevss-maxage: what does each mean?Read more: HTTP →no-cache: may be stored, but must be revalidated before each use.no-store: must not be stored at all.private: keep out of shared caches (anything personalised).s-maxage: freshness for shared caches such as CDNs, overridingmax-age.
Revalidate cheaply with
ETag+If-None-Match→304 Not Modified.Communication & APIs What does HTTP/3 fix compared with HTTP/2, and what does it cost?
Read more: HTTP →HTTP/2 multiplexes streams over one TCP connection, but one lost packet stalls all of them. HTTP/3 runs over QUIC (UDP): loss stalls only its own stream, transport and TLS handshakes are combined, and connections survive a network change.
Costs: UDP is blocked on some networks (keep a fallback), more CPU per byte, and less mature self-hosted tooling.
Communication & APIs How many round trips before the first response byte on a new HTTPS connection?
Read more: HTTP →- New TCP + TLS 1.2: 4 (400 ms at 100 ms RTT).
- New TCP + TLS 1.3: 3.
- New QUIC (HTTP/3): 2.
- QUIC resumption with 0-RTT, or a reused warm connection: 1.
So reuse and pool connections. Accept 0-RTT early data only for safe, idempotent requests, because it can be replayed.
Communication & APIs TCP vs UDP: what do you get and give up with each?
Read more: TCP and UDP →TCP: a one-round-trip handshake, then reliable, in-order bytes with flow control (protects the receiver) and congestion control (protects the network). One lost segment stalls everything behind it.
UDP: an 8-byte header and nothing else — no connection, ordering, retransmission or congestion control. Used when late data is useless (voice, games), for DNS and DHCP, and for broadcast. You own congestion control and amplification protection.
Communication & APIs Why are new TCP connections expensive, and why pool them?
Read more: TCP and UDP →- Handshake round trips, plus TLS.
- Slow start: a new connection starts with 10 segments (about 14.6 KB), so a 1 MB response needs about 7 round trips, 0.7 s at 100 ms RTT.
- TIME_WAIT: about 28,000 ephemeral ports run out at roughly 470 new connections/s to one backend.
- 500 app instances × 20 database connections = 10,000 server connections.
Communication & APIs RPC (gRPC) or REST: which do you choose, and where?
Read more: RPC and REST →REST + JSON + OpenAPI for public APIs: any HTTP client works, HTTP caching applies, conventions are familiar.
gRPC between internal services: typed Protobuf contracts, compact encoding, deadlines, streaming and generated clients over HTTP/2. Browsers need gRPC-Web or Connect.
Many organisations run gRPC inside and expose REST through a gateway.
Communication & APIs How do you paginate and version a public API?
Read more: RPC and REST →Pagination: cursors, not offsets. An opaque token encoding the last position stays fast at any depth and stable under inserts; offsets slow down with depth and skip or duplicate items.
Versioning: prefer additive, backward-compatible changes; reserve a new major version (
/v1/…) for breaking ones, and announce retirement withDeprecationandSunsetheaders.Communication & APIs GraphQL: when does it fit, and what problems must you handle?
Read more: API styles beyond REST →Fits many clients needing different views of a rich, connected domain: one round trip per screen and no over-fetching.
Handle N+1 resolvers with a per-request DataLoader (batch and memoise), weak HTTP caching (all POST to one endpoint; use persisted queries) and query cost: limit depth and page size and rate-limit by cost. Avoid it for simple CRUD or internal calls.
Communication & APIs Long polling, SSE or WebSockets: which do you pick for server push?
Read more: API styles beyond REST →- SSE: one-way server → client over plain HTTP, with built-in reconnect via
Last-Event-ID. Notifications, dashboards, LLM token streams. - WebSockets: full duplex, low latency. Chat, collaboration, games; you must build reconnect, heartbeats and acks.
- Long polling: the universal fallback when streaming is blocked.
A message reaches a user on another server through a pub/sub layer between connection gateways.
- SSE: one-way server → client over plain HTTP, with built-in reconnect via
Communication & APIs What must the sender and the receiver of webhooks do?
Read more: API styles beyond REST →Sender: deliver from a queue; retry with backoff and jitter for hours or days (Stripe retries for up to three days); sign each delivery with HMAC-SHA256 over ID, timestamp and raw body; block private addresses to prevent SSRF.
Receiver: verify the signature on the raw body, reject stale timestamps, answer
2xxfast, dedupe by event ID (delivery is at least once) and don't assume order.Reliability & security Metrics, traces, logs: which question does each answer, and how are they linked?
Read more: Observability →Metrics say that something is wrong, cheaply. Traces say where the time went. Logs say why.
Link them with a shared trace ID: alert on a metric, open an exemplar trace from the bad minute, then find its logs by trace ID. OpenTelemetry is the vendor-neutral standard for all three.
Reliability & security What do RED and USE stand for, and where does each apply?
Read more: Observability →RED, for every request-driven service: Rate, Errors, Duration (a latency distribution).
USE, for every resource, including thread pools, connection pools and queues: Utilisation, Saturation (work waiting), Errors.
Google's four golden signals (latency, traffic, errors, saturation) combine the two. Measure the latency of successes and failures separately.
Reliability & security How do you alert on an SLO? Give the burn-rate thresholds for a 99.9% SLO.
Read more: Observability →Alert on the burn rate: how fast the error budget is being spent (1 = exactly the whole budget in 30 days).
- Page: burn rate 14.4 over 1 h and 5 min (2% of the budget used).
- Page: 6 over 6 h and 30 min (5%).
- Ticket: 1 over 3 days and 6 h (10%).
The long window makes the alert significant; the short one lets it stop soon after the problem does.
Reliability & security Why must metric labels be bounded?
Read more: Observability →Every distinct label combination is a separate time series, and they multiply: 50 endpoints × 4 methods × 5 status classes × 200 pods × 14 histogram series = 2.8 million. Add
customer_idwith 10,000 values and you get 28 billion.Keep metric labels bounded (endpoint template, region, status class); put user IDs, order IDs and URLs into traces and logs.
Reliability & security How does a token bucket rate limiter work?
Read more: Rate limiting →A bucket holds up to
btokens and refills atrper second; each request takes a token or is rejected (or delayed). Over any intervalt, at mostb + r·trequests pass: bursts up tob, long-run averager.You store just two numbers per key (tokens and last refill time) and refill lazily. It is the default for APIs.
Reliability & security What is wrong with a fixed-window limiter, and how does the sliding-window counter fix it?
Read more: Rate limiting →With 100 per minute, a client can send 100 at 10:15:59 and 100 at 10:16:00: up to 2× the limit at a boundary.
The sliding-window counter weights the previous window by its overlap: 15 s into the minute,
84 × 45/60 + 36 = 99, so one more request is allowed. Cloudflare measured only 0.003% wrong decisions over 400 million requests.Reliability & security Distributed rate limiting in Redis: what are the classic bugs, and what if Redis is down?
Read more: Rate limiting →Bug 1: check-then-act (
GET, compare,INCR) lets two nodes both allow at 99. Bug 2:INCRthen a separateEXPIRE; a crash in between leaves a key that never expires.Fix:
INCRwithEXPIRE … NXin oneMULTI, or a Lua script using the server'sTIME.If the store fails, decide in advance: fail open (most public APIs, with a coarse local limit) or fail closed. Reject with
429andRetry-After.Reliability & security How do cascading failures happen? What is a metastable failure?
Read more: Resilience patterns →A feedback loop: failure causes more load or waiting, which causes more failures. Survivors take the dead replica's load; a slow dependency fills pools (by Little's law, 20 ms → 2 s means 100× in flight); 3 attempts at each of 4 layers turn one request into 3⁴ = 81 calls.
Metastable: the trigger is gone, but retries, queues and cold caches keep load above capacity. Recovery needs load well below the original level.
Reliability & security How do you set timeouts, and why propagate a deadline?
Read more: Resilience patterns →Every remote call needs a timeout (gRPC sets no deadline by default). Set it slightly above the dependency's p99.9, not a round “30 s”, and separate connect from request timeouts.
Better, the edge sets an end-to-end budget (say 800 ms) and each hop passes on the remaining time, so services stop working on requests nobody is waiting for. Dropping abandoned work is the cheapest load shedding there is.
Reliability & security What are the rules for retries that don't cause retry storms?
Read more: Resilience patterns →- Retry only safe operations: reads, idempotent writes, writes with an idempotency key. Never retry 4xx except 408 and 429.
- Exponential backoff with full jitter:
sleep = random(0, min(cap, base × 2^attempt)). - Cap attempts (about three) and respect the caller's deadline.
- Retry at one layer only.
- Use a retry budget (about 10% of requests): worst-case load grows about 1.1× instead of 3×.
Reliability & security The payment call timed out. How does an idempotency key make the retry safe?
Read more: Resilience patterns →The client generates one unique key per logical operation and sends it with every attempt. The server:
- stores the key with a request fingerprint, atomically, before doing the work;
- replays the stored response for a repeat with the same parameters;
- returns an error if the parameters differ;
- answers
409while the original is still running; - expires keys after a retention period (Stripe: 24 hours).
Store the key in the same transaction as the effect.
Reliability & security Explain the three states of a circuit breaker.
Read more: Resilience patterns →- Closed: calls pass through; failures and slow calls are counted over a sliding window.
- Open: calls fail immediately or go to a fallback, giving the dependency room to recover.
- Half-open: after a wait, a few trial calls go through; success closes it, failure opens it again.
Keep one breaker per endpoint and shard, and alert on its state, because breakers hide failures.
Reliability & security Bulkheads and load shedding: what does each protect against?
Read more: Resilience patterns →Bulkhead: each dependency or tenant gets its own bounded pool of threads or connections, so a hung recommendations service fills only its own 20 connections and checkout keeps working. At scale this becomes a cell-based architecture.
Load shedding: under overload, reject early and cheaply, by priority, so the rest finish within their deadlines. Otherwise goodput (useful completed work) collapses while throughput still looks high.
Reliability & security What are hedged requests, and what do they buy?
Read more: Resilience patterns →If a request has not answered within about the p95 latency, send a copy to another replica and take whichever reply comes first.
In The Tail at Scale, hedging after 10 ms cut p99.9 from 1,800 ms to 74 ms for only 2% more requests. Only for idempotent reads; cancel the slower copy and cap hedges with a budget.
Reliability & security Authentication vs authorisation, and where do you check each?
Read more: Security →AuthN proves who you are; authZ decides what you may do with this object. AuthZ failures, such as fetching
/invoices/1043after being allowed only/invoices/1042, are far more common: broken access control is the top web risk.Authenticate at the gateway, but check authorisation in the service, on every request and every object. Store passwords only as slow salted hashes (Argon2id).
Reliability & security Server-side sessions or JWTs?
Read more: Security →Session: a random ID in a cookie, looked up in a shared store. Revocation is immediate. Best for browser apps, with
HttpOnly,SecureandSameSitecookies.JWT: signed claims verified locally, with no lookup, so any service can check them, but revocation is hard. Keep them short-lived with revocable refresh tokens, pin the algorithm, validate
iss,audandexp, and never keep them inlocalStorage.Reliability & security What is envelope encryption, and why is it the standard?
Read more: Security →Data is encrypted locally with a per-object data key; only that small key is encrypted by a KMS whose root keys never leave its HSMs.
Bulk data never travels to the KMS, every KMS call is authorised and audited, rotating the root key needs no re-encryption of terabytes, and destroying a key makes everything under it unreadable. Encryption at rest doesn't stop someone with valid credentials: control who can use the keys.
Reliability & security Injection, XSS, CSRF, SSRF: the main defence against each?
Read more: Security →- Injection: parameterised queries; allowlists for identifiers.
- XSS: context-aware output encoding, HTML sanitisation, plus a Content Security Policy.
- CSRF:
SameSitecookies, rejecting cross-site requests viaSec-Fetch-Site, and never changing state on GET. - SSRF (webhooks, link previews): resolve the host, block private and link-local ranges, send traffic through an egress proxy.
Numbers Typical latency of an L1 cache hit, an L2 hit and a main memory (DRAM) reference?
Read more: Latency numbers every programmer should know →L1 about 1 ns, L2 about 3.5 ns, DRAM about 100 ns (70 ns on a DDR5 desktop, 110–130 ns on many-core servers).
They have barely changed since 2012, because clock speeds stopped at 3–6 GHz and cache latency is a fixed number of cycles. Memory bandwidth grew; latency did not.
Numbers Random 4 KB read from NVMe vs a round trip inside an availability zone: which is faster?
Read more: Latency numbers every programmer should know →The NVMe read: about 50 µs at queue depth 1, against about 200 µs for a same-zone round trip.
In 2012 a network round trip beat a disk seek by twenty times. Today a local NVMe read is cheaper than a network hop, so a remote cache earns its place when it saves a query, computation or a cross-region trip, not just a disk read.
Numbers Round-trip times: within a zone, between zones, US East ↔ Western Europe, California ↔ Netherlands, the other side of the world?
Read more: Latency numbers every programmer should know →- Within a zone: ~200 µs (about 5,000 sequential trips per second)
- Between zones: ~1 ms (~1,000/s)
- US East ↔ Western Europe: ~80 ms (~12/s)
- California ↔ Netherlands: ~145 ms (~7/s)
- Other side of the world: ~280 ms (3–4/s)
Light in fibre covers about 200 km per ms, so sequential cross-region calls are the most expensive part of most requests.
Numbers How fast are hard disks, NVMe drives and cloud block volumes?
Read more: Latency numbers every programmer should know →- HDD random read (seek + rotation): ~10 ms, so only about 100 random IOPS per drive; 1 MB sequential ~5 ms.
- NVMe: 1 MB sequential ~100 µs (7 GB/s on PCIe 4, 14 GB/s on PCIe 5), 7–14 times the 2012 SSD.
- Network-attached cloud block volume I/O: ~1 ms, ten times a local NVMe drive, because every I/O crosses the network.
Numbers Typical latency of a Redis/Valkey GET, an indexed PostgreSQL query, a TLS 1.3 handshake and an object storage GET?
Read more: Latency numbers every programmer should know →- Redis/Valkey GET in the same zone: ~250 µs; the server needs well under 1 µs, the rest is the network.
- Indexed PostgreSQL query over the network: ~500 µs (19 µs over a Unix socket).
- TLS 1.3 handshake within a region: ~1 ms.
- Object storage first byte: ~30 ms median, with a tail to 200 ms.
All of them are dominated by the round trip, so fewer round trips beat faster servers.
Numbers How long does a DNS lookup take with and without a resolver cache hit?
Read more: Latency numbers every programmer should know →Resolver cache hit: ~10 ms, roughly one round trip to the resolver (under 1 ms inside a cloud VPC, 5–30 ms from home or mobile networks).
Cache miss with full recursion: ~100 ms, about 130 ms on average when servers answer, 300–400 ms with timeouts and retries. OS and browser caches answer in microseconds.
Numbers How much downtime do 99.9%, 99.99% and 99.999% allow per year and per month?
Read more: Availability numbers →- 99.9%: 8 h 46 min a year, 43 min 50 s a month. A human can be paged and roll back.
- 99.99%: 52 min 36 s a year, 4 min 23 s a month. Detection and failover must be automatic.
- 99.999%: 5 min 16 s a year, 26 s a month. No single global dependency.
Each extra nine divides the budget by ten and costs roughly ten times the effort.
Numbers How do failure rate and recovery time determine availability?
Read more: Availability numbers →A = MTBF / (MTBF + MTTR). A component that fails once a month and takes 30 minutes to recover is about 99.93% available; cutting recovery to 5 minutes raises it to 99.99% without making failures any rarer.That is why high-availability work focuses on fast detection and recovery: health checks, automatic failover, quick rollbacks, small blast radii.
Numbers Which powers of two should you know for estimates?
Read more: Powers of two →- 2¹⁰ ≈ 10³: every ten powers add about three zeros, so 2²⁰ ≈ a million, 2³⁰ ≈ a billion, 2⁴⁰ ≈ a trillion.
- 2³² ≈ 4.3 billion: IPv4 addresses, unsigned 32-bit integers.
- 2³¹ − 1 ≈ 2.1 billion: the classic signed-integer overflow.
- 2⁶⁴ ≈ 1.8 × 10¹⁹: does not run out at web scale.
Numbers KB vs KiB, and bits vs bytes: what are the traps?
Read more: Powers of two →KB, MB, GB are powers of 1,000; KiB, MiB, GiB are powers of 1,024. The gap grows from 2.4% at kilo to 10% at tera, which is why a “1 TB” disk shows up as 931 GB.
Network bandwidth is quoted in bits per second, storage in bytes: a 10 Gbit/s link moves about 1 GB/s of payload. Mixing bits and bytes is the more common slip.
Numbers Convert 1 million, 100 million and 1 billion requests per day into requests per second.
Read more: Back-of-the-envelope estimation →A day is 86,400 s ≈ 10⁵ s.
- 1 million/day ≈ 12/s
- 100 million/day ≈ 1,200/s
- 1 billion/day ≈ 12,000/s
Then find the peak: typically 2–3× the daily average, up to 10× for launches. Size servers for the peak and storage for the average.
Numbers Roughly what can one machine handle in 2026?
Read more: Back-of-the-envelope estimation →- Stateless web or API server: 1,000–10,000 requests/s.
- PostgreSQL or MySQL primary on a large instance: 10,000+ simple writes/s, 50,000+ indexed reads/s, tens of TB.
- Valkey or Redis node: 100,000+ operations/s.
- Kafka-style broker: hundreds of MB/s of writes.
- Server memory 256 GB – 2 TB; network port 25–100 Gbit/s.
Numbers Photo sharing: 20 M daily users, a 2 MB photo every other day, 50 views each. What dominates the design?
Read more: Back-of-the-envelope estimation →Request rates are modest (about 120 uploads/s and 6,000 views/s), but egress and storage dominate: about 90 Gbit/s of views (370 Gbit/s at peak) and about 7 PB of new data a year, 220 PB over ten years with three copies.
So: a CDN in front, object storage with erasure coding and colder tiers, and metadata as a separate, much smaller problem.
Interview framework What are the seven steps of the system design interview framework?
Read more: How to approach a system design interview →- Clarify requirements.
- Estimate.
- Define the API and data model.
- Sketch the high-level design.
- Deep-dive into one or two components.
- Scale it and break it: bottlenecks, failures, trade-offs.
- Wrap up against the requirements.
Interview framework How do you budget time in a 45-minute design interview?
Read more: How to approach a system design interview →About 40 minutes of design time: requirements 4, estimates 3, API and data model 4, high-level design 10, deep dives 11, scaling and failures 6, wrap-up 2.
Checkpoint: by the halfway mark a complete high-level design should be on the board. If you are still on requirements at minute 15, state your assumptions and move on.
Interview framework Functional vs non-functional requirements: how do you capture them?
Read more: How to approach a system design interview →Functional: what the system does — agree on three to five core use cases and explicitly park the rest.
Non-functional: how well it does it — as numbers, not adjectives: “p99 under 200 ms”, “99.99% for redirects”, “no lost links”.
Ask about users, scale, read/write ratio, data size, latency, consistency, geography and constraints. If told “you decide”, decide out loud.
Interview framework What makes a back-of-the-envelope estimate useful in an interview?
Read more: Back-of-the-envelope estimation →A conclusion. “About 3,500 reads a second at peak, so one database with a cache is enough”; “220 PB, so object storage with tiering.”
State assumptions first, keep units on every number, size for the peak, count replicas and overhead, round to one significant figure. A table of numbers without “so we need X” is half an answer.
Interview framework How do you run a deep dive, and what do you stress-test afterwards?
Read more: How to approach a system design interview →Pick one or two components where the requirements are hardest (uniqueness, a hot path, consistency, data growth). Lay out two or three options, compare them against the written requirements, pick one and say what you give up.
Then, component by component: what breaks first at 10× load, and what happens when it fails? Name the fixes and their costs.
Interview framework Name the most common mistakes in system design interviews.
Read more: How to approach a system design interview →- Jumping to the diagram before requirements and scale.
- Over-engineering: microservices, Kafka and five databases for a one-server problem.
- Buzzwords without saying what they do here and cost.
- Estimates that are never used.
- No trade-offs and no answer to “what if this node dies?”
- Going deep too early, monologuing, losing track of time.
Interview framework What separates a senior performance from a mid-level one?
Read more: How to approach a system design interview →Mid-level: drives with some help and produces a working end-to-end design with standard components.
Senior: drives the whole interview, lets numbers justify choices, goes deep on the hardest component, raises bottlenecks and failure modes before being asked, and compares alternatives with clear trade-offs.
Staff+: also frames or challenges the problem and covers operations, cost, migration and when not to build.
Case studies URL shortener: how do you generate short keys?
Read more: Design Pastebin or a URL shortener →Default: a random 7–8 character Base62 key plus an atomic “insert if absent”; on conflict, draw again. 62⁷ ≈ 3.5 × 10¹², so with 360 M keys only about 1 insert in 9,800 retries — but the retry path is mandatory.
For the shortest keys, lease counter ranges and pass them through a scrambling permutation, because raw counters are enumerable.
Case studies URL shortener: 301 or 302 redirect?
Read more: Design Pastebin or a URL shortener →301 is cacheable by default, so repeat clicks may never reach you: less load, but lost analytics, and a takedown doesn't reach browsers that cached it.
302 brings every click back: accurate counts, editable links and instant takedown of a phishing link, at the cost of serving every repeat visit. A middle ground is a 301 with a short
max-age.Case studies Twitter home timeline: fan-out on write or fan-out on read?
Read more: Design the Twitter timeline and search →Hybrid. Push an ordinary user's tweet ID into each active follower's cached timeline (about 800 IDs per user); reads are one list fetch plus a multiget. Pull tweets from accounts with millions of followers and merge them at read time.
Why: reads outnumber tweets about 17×, so push is cheaper overall, but one celebrity tweet would mean 5 M inserts.
Case studies Twitter search: how do you partition the inverted index?
Read more: Design the Twitter timeline and search →By document (tweet ID), not by term: term sharding sends every popular term to one hot shard and makes multi-term queries cross shards.
Each query scatters to all shards in the relevant time tiers (an in-memory realtime tier, older tiers on SSD), takes the top K per shard, merges, re-ranks and hydrates. An indexer fed from the tweet stream keeps it fresh.
Case studies Web crawler: how does the URL frontier keep both priority and politeness?
Read more: Design a web crawler →Front queues hold URLs by priority; a selector routes them to back queues, one per host; a heap keyed by “earliest time this host may be contacted” picks the next host.
If each host gets one request about every 10 s, sustaining 1,650 fetches/s needs at least 16,500 hosts with queued work. Respect robots.txt (RFC 9309), cached up to 24 hours.
Case studies Web crawler: how do you deduplicate URLs and content?
Read more: Design a web crawler →URLs, before they enter the frontier: normalise, then check a “seen” set or a Bloom filter (about 12 GB for 10 B URLs at 1% false positives, which only skips a few new URLs).
Content, after fetching: an exact hash for identical bodies, and SimHash for near-duplicates — 64-bit fingerprints within Hamming distance 3, found with the block trick.
Case studies Social graph: how do you find the shortest path between two users at scale?
Read more: Design the data structures for a social graph →Bidirectional BFS, always expanding the smaller frontier. With 50 friends each, a path of length 4 touches about 5,000 nodes instead of about 6 million.
Adjacency lists live in memory on person servers sharded by user ID. Fetch each BFS level with one batched call per shard, in parallel, so round trips equal the depth (about 4), not the number of friends.
Case studies Search query cache: what goes into the key, and how do results stay fresh?
Read more: Design a key-value cache for a search engine →Key: the normalised query plus everything that changes the page — locale, safe-search, page number, index version. Leaving one out serves the wrong results.
Freshness: a TTL with jitter plus the index version in the key, so a new snapshot gives new keys and old entries age out. Shard with consistent hashing, keep a local tier for the hottest queries, and coalesce misses.
Case studies Sales rank by category: how do you compute and serve top-N lists?
Read more: Design sales rank by category (Amazon) →Sales events go to a durable log; checkout never waits for ranking. Count units per
(category, product)over a sliding 7-day window — an hourly batch job classically, a windowed stream job today — and keep a bounded heap per category, not a global sort.The read side is tiny (top 100 × 1,000 categories ≈ 1.6 MB): publish versioned snapshots and cache them in memory and at the CDN.
Case studies Personal finance tracker: how do you ingest bank transactions without duplicates or lost data?
Read more: Design a personal finance tracker (Mint.com) →Store only a consented token, encrypted in a vault — never the bank password. A scheduler and provider webhooks feed a job queue; sync workers pull incremental changes by cursor and upsert on a unique provider transaction ID, saving the cursor in the same transaction.
A circuit breaker per institution keeps a 6-hour bank outage contained; money is integer cents, never floats.
Case studies Scaling a web app from one box to millions of users: in what order?
Read more: Scale a web app from 1 to millions of users →It is a loop: load test → profile → fix the top bottleneck → repeat. The usual order:
- Separate the database.
- Stateless app tier behind a load balancer.
- Cache and read replicas.
- Object storage and a CDN for static content.
- Queues and async workers.
- Then partition data and go multi-region.
Name what each step buys and costs.
Case studies How do you approach an unfamiliar design question?
Read more: More interview questions →Find its one core difficulty — fan-out, ordering, hot keys, exactly-once or geography — in the first five minutes, and spend most of the interview there.
Use the framework: requirements, estimates, high-level design, deep dive, scaling. Read reference architectures only after sketching your own answer, and compare trade-offs rather than copying a company's design.
Object-oriented design Hash map: how do you keep operations O(1) on average?
Read more: Design a hash map →Buckets indexed by
hash(key) % capacity, each a short list of entries (separate chaining). Keep the load factor (size / capacity) under 0.75; when it goes over, double the array and rehash every entry. Doubling means each entry moves a constant number of times on average, so inserts are amortisedO(1).Worst case is
O(n)when all keys collide; defences are randomised hashing (SipHash) or tree-ified buckets.Object-oriented design LRU cache: which data structures, and what is the key trick?
Read more: Design an LRU cache →A dict (key → node) for
O(1)lookup plus a doubly linked list in recency order.getandputmove the node to the head; eviction removes the tail.The trick: each node stores its own key, so after unlinking the tail you can delete it from the dict in
O(1). Sentinel head and tail nodes remove the empty-list special cases.Object-oriented design Parking lot: how do you model “does this vehicle fit this spot?”
Read more: Design a parking lot →Make
Sizean ordered enum; then fitting is one comparison,spot.size >= vehicle.size, and vehicle subclasses carry only a size and the number of spots they need.Single-spot vehicles take the smallest spot that fits (best fit), keeping large spots for buses; a bus needs 5 adjacent large spots in one row.
parkreturns aTicketthatleaveuses to free the spots.Object-oriented design Call center: how does escalation work without special routing code?
Read more: Design a call center →Each
Callrecords the minimum rank allowed to take it (OPERATOR < SUPERVISOR < DIRECTOR). Escalation just raises that minimum and dispatches the call again, so one routing path handles new, escalated and queued calls.Only
CallCenterroutes. With one FIFO queue per rank, a freed employee takes the waiting call needing the highest rank they have.Object-oriented design Deck of cards: how do you model cards and score aces in blackjack?
Read more: Design a deck of cards →Cardis an immutable value (rank,suit, both enums) with no game logic;Deckbuilds, shuffles and deals;Hand.score()is overridden only inBlackjackHand.Aces: count each as 1, then add 10 once if that doesn't bust. Two aces as 11 would be 22, so at most one ace can ever count high.
Object-oriented design Online chat: what keeps the object model consistent?
Read more: Design an online chat →Entities refer to each other by id, not by object, so a friendship or membership changes in one place and the model maps directly to tables later. One
ChatServiceowns everything and enforces cross-user rules.A private chat is keyed by the unordered pair of users (
frozenset), so A→B and B→A find the same chat.
How the deck works
Section titled “How the deck works”The deck uses the Leitner system: five boxes, and a card’s box sets how long it waits before it is due again.
| Box | How long a card waits there |
|---|---|
| New | Due now |
| 1 | Today, at the end of the round |
| 2 | 1 day |
| 3 | 3 days |
| 4 | 7 days |
| 5 | 16 days, and it stays in box 5 |
- Got it (key
2) moves the card up one box, where it waits that box’s interval; a new card goes straight to box 2. Again (key1) sends it back to box 1, and it returns at the end of the current round. - Due counts cards to review now in the selected section; Learned counts cards in box 2 or higher.
- By default the weakest cards come first. Shuffle mixes the order instead.
- When nothing is due, you can run a practice round over every card in the section. Practice rounds do not change the schedule.
- Progress is saved in your browser, separately for English and Russian. Clearing site data or using a private window starts from scratch. Reset progress puts every card back to new.
- Without JavaScript, open Browse all cards to read every question and answer.
Use them in Anki
Section titled “Use them in Anki”Anki is a free spaced-repetition app for desktop and mobile. Both decks have the same cards as the deck above; each answer ends with a link to the page on this site.
To import a deck:
- Download the file and open Anki on a computer (version 2.1.54 or later).
- Choose File → Import and select the file.
- Anki reads the settings from the file header: tab-separated, HTML allowed, note type Basic, deck System Design Map. Check them in the dialog and click Import.
Each card is tagged system-design plus a section tag such as sdp::data, so you can study one section with a filtered deck. Cards carry stable IDs: when the site publishes a new version of the deck, importing it again updates the existing notes and keeps your review history.
Related topics
Section titled “Related topics”- Study plan — when to review the cards and what to practise alongside them.
- Latency numbers — the numbers behind many cards, with an interactive explorer.
- Interview framework — the structure to use when the cards turn into a real question.
Based on The System Design Primer by Donne Martin (CC BY 4.0). Restructured, rewritten and updated; site content is licensed under CC BY 4.0.