System Design

Core Concepts

Choosing a Database

Nobody chooses a database. They choose a set of things they will not be able to do, and then name the product that makes that trade. Get the access patterns on paper and the product is nearly decided; skip them and no comparison table helps.

Why you are doing this at all

When an interviewer asks "which database would you use?", most candidates answer with a product. They pick Postgres because it's familiar, DynamoDB because the question said scale, or Cassandra because someone mentioned writes. The answer comes before anyone has said what the data is for. So the interviewer learns only which product the candidate has used before.

The fix is the same idea that runs through sharding:

You aren't choosing a database. You're choosing which access patterns stay cheap and which ones you give up. An access pattern is one specific way the data is read or written, such as "given a user id, get the profile". Every database has a storage engine, the part that decides how the data is laid out on disk, and each engine is built to make certain patterns cheap. If your workload matches what the engine is built for, it's easy to run. If it doesn't, you spend two years working around a choice nobody can undo.

This is why feature comparison tables are close to useless. They compare features, and features aren't what cause the trouble. The trouble comes when you pick a data store that is only fast at reading one key at a time, and then the product asks for "everything created last Tuesday, sorted by price."

"SQL against NoSQL" is the wrong axis

The split was useful around 2010, and now it's mostly a slogan. Postgres stores and indexes JSON documents. MongoDB has transactions across several documents. Vitess and Citus both scale relational databases horizontally, across many machines, and that was supposed to be the reason to leave relational databases. The label tells you almost nothing about whether a product fits.

Two claims come up often, and both are wrong.

"NoSQL scales and SQL doesn't." Relational databases shard. Sharding means splitting the data across machines by a key, and Slack, Figma, Notion and Pinterest have all written publicly about doing it. At scale, the question isn't whether you can shard. It's which queries still work after you do, and that's true of every family. A hash-partitioned key-value store places each key on a machine by hashing it, so it gives up ordered scans on day one. A sharded relational database gives up joins across shards on the day it splits. It's the same trade, made on a different day.

"Relational is safer, so start there and switch if needed." The first half is right. The second half assumes switching is easy, and it isn't. Slack spent three years moving 99 percent of its MySQL query load onto Vitess. Figma took nine months to shard its first table across machines. Treat the choice as close to permanent, because in practice it is.

The three questions that actually decide it

Almost every real decision comes from the answers to three questions. Ask them in this order, because each answer narrows down the next.

  1. What are the access patterns? Write them as sentences, with the key in them. Not "we read users", but "given a user id, get their profile" and "given a workspace, list its documents newest first." The keys in those sentences decide the design.
  2. What is the write rate and the data size? Give numbers, not adjectives. Most systems that people design unusual data stores for run a few thousand writes a second against a few hundred gigabytes. One machine handles that.
  3. What can you afford to lose? A rate limiter's counters can disappear. A payment can't. The answer decides durability, which is whether a write survives a crash, and also replication and backups. Candidates usually skip this question entirely.

Once you've answered those three, the family is nearly decided. If you skip them, you're choosing by brand.

When to skip this entirely

The default is one relational database, and it stays the right answer far longer than interviews suggest.

In 2020, Figma ran its whole product on a single Postgres database, on the largest physical machine AWS offered. When it outgrew that, its first steps were caching, read replicas (copies of the database that serve reads) and splitting tables by feature into a dozen separate databases. It didn't shard a table across machines until September 2023. When Notion sharded, it set its limits at 10 TB per machine and 500 GB per table. If your biggest table is 200 GB and you're drawing a design with several data stores, you've skipped several cheaper steps.

Have this sentence ready: "one Postgres, until a specific number says otherwise, and here is the number I would watch." It's a stronger answer than any product name. It also makes you work out which limit would force the change.

The families, and what each one gives up

Six families cover almost everything. They differ less in features than in what their storage engine makes cheap, and everything else follows from that.

The same query against two layouts
On the left, rows are kept sorted by workspace and time, so the four rows for workspace 7, in green, sit together and one range read returns them. On the right, each row goes to the partition its key hashes to. The same four rows, in red, are spread over all four partitions, so the query asks every partition and then sorts. Fetching one key is cheap in both.On the left, rows are kept sorted by workspace and time, so the four rows for workspace 7, in green, sit together and one range read returns them. On the right, each row goes to the partition its key hashes to. The same four rows, in red, are spread over all four partitions, so the query asks every partition and then sorts. Fetching one key is cheap in both.
The layout decides which query is cheap. On the left, rows are kept sorted by workspace and time, so the four rows for workspace 7, in green, sit together and one range read returns them. On the right, each row goes to the partition its key hashes to. The same four rows, in red, are spread over all four partitions, so the query asks every partition and then sorts. Fetching one key is cheap in both.
familythe engine makes cheapwhat you give upreach for it when
relational (B-tree)ordered scans, joins, transactions, ad-hoc querieshorizontal write scaling without extra machinery; cross-shard joins once splityou do not yet know every query, and correctness matters
key-value (hash)one key in, one value out, at any scaleevery ordered scan, every range query, every query not carrying the keythere is exactly one access pattern and it is by key
wide-column (LSM)very high write rates; ordered scans within a partitioncross-partition queries, cheap deletes, ad-hoc anythingwrites dominate and every read carries the partition key
documentfetching one nested object wholeanything spanning documents; the schema drifts silentlythe aggregate is the unit of both read and write
search (inverted index)matching by content, ranking, fuzzy termsbeing a source of truth; it is a derived indexthe query is about what is inside the data
in-memorymicrosecond access, atomic operationsdurability, and anything larger than RAMthe data expires soon, or is rebuildable

The labels, decoded

You'll still hear these labels in interviews. None of them is a good way to compare databases, but you should know what each one refers to.

the labelwhat it actually meanswhich families
SQL / relationaltables, a schema, joins, and a query plannerrelational
NoSQL"not this one thing", so it covers four families that share nothingkey-value, wide-column, document, graph
NewSQL / distributed SQLrelational semantics on a horizontally distributed enginerelational, with the sharding built in
OLTPmany small operations by key, serving the productrelational, key-value, wide-column, document
OLAPfew enormous scans across columns, answering questionscolumn-oriented analytical
ACIDatomicity, consistency, isolation, durabilitysee the transactions section; the letters have very different prices
BASEmarketing for "eventually consistent", not a real counterpart to ACIDmostly wide-column and key-value

NoSQL is the least useful word on that list. It's defined by what it isn't, so it puts a hash-partitioned key-value store in the same group as a graph database, and the two have nothing in common. If an interviewer uses it, answer in terms of families. The conversation gets more specific straight away.

The products, by family

Here are the products in each family. The right-hand column gives the one thing to know about each, which is usually not what its home page says.

familyproductsthe thing to know
relationalPostgreSQL, MySQL, MariaDB, SQL Server, OraclePostgres is the default answer in almost every interview and is very hard to be wrong with. MySQL is comparable and more common where a sharding layer already exists
relational, distributedCockroachDB, Google Spanner, YugabyteDB, TiDB, Vitess and Citus as layersrelational semantics with sharding built in. You pay for it in cross-region write latency, because a distributed commit is a round trip
key-valueDynamoDB, Redis (as a data store), Riak, etcd for configDynamoDB is the archetype: name the partition key or the query does not work. etcd is for small, strongly consistent config, not for data
wide-columnCassandra, ScyllaDB, HBase, Google Bigtablebuilt for write volume. Cassandra and Scylla are the same data model, Scylla being a C++ rewrite. Deletes are tombstones and repair is real operational work
documentMongoDB, Couchbase, DocumentDB, Firestorefine products with a real failure mode: the schema drifts because nothing enforces it, and you find out two years later during a migration
searchElasticsearch, OpenSearch, Solr, Typesense, Meilisearchall built on inverted indexes, most on Lucene. Always a derived store, never the source of truth
in-memoryRedis, Valkey, Memcached, HazelcastMemcached is a cache and nothing else. Redis has data structures, optional persistence and scripting, which is why it ends up holding real state
time-seriesPrometheus, InfluxDB, TimescaleDB, VictoriaMetricsappend-only, time-partitioned, heavily compressed. Timescale is a Postgres extension, so it is the cheap step if you are already there
analytical, columnClickHouse, BigQuery, Snowflake, Redshift, DuckDBscans columns rather than rows. Never put product traffic on these, and never put analytics on your product database
graphNeo4j, Neptune, JanusGraphgenuinely right for multi-hop traversal, and reached for far more often than it is needed. One or two hops is a join
object storageS3, GCS, Azure Blob, MinIOnot usually called a database and it is where most of your bytes belong. Eleven nines, immutable objects, priced per gigabyte

The distinction that explains most of it

Nearly every product here is built on one of two storage engines. If you know which one a product uses, you can predict how it behaves better than its marketing can.

B-trees keep data sorted, and change it where it sits. A range read is cheap, because keys that are next to each other in the order are also next to each other on disk. Writes cost more, because an insert in the middle has to make room, sometimes by splitting a page in two. A delete leaves dead space behind, and a cleanup process has to reclaim it later. Postgres, MySQL and every classic relational engine work this way.

LSM trees, short for log-structured merge trees, never change data where it sits. Every write is appended, first to a sorted buffer in memory and then to a new file on disk. A background process called compaction merges those files over time. So writes are very cheap, but a read may have to check several files. A delete is a write too. It adds a tombstone, a marker that says the key is gone. You pay for it again during compaction, and every read that passes it pays until compaction removes it. Cassandra, RocksDB and most wide-column stores work this way.

This difference explains why a huge delete rate hurts both engines, for different reasons. In a B-tree, dead rows pile up faster than the cleanup reclaims them. In an LSM tree, reads slow down as they step over tombstones. It's also why the WhatsApp spool in this course lets rows expire instead of running DELETE.

Where a write and a delete go
On the left, inserting 21 into a full page splits it in two, and deleting 18 leaves dead space that stays on disk until vacuum reclaims it. On the right, the insert and the delete are both appends to a sorted buffer in memory, and the delete is a tombstone. The buffer is flushed to a new file when it fills. A read checks memory and then each file, newest first, and a range read steps over every tombstone it meets until compaction merges the files and drops them.On the left, inserting 21 into a full page splits it in two, and deleting 18 leaves dead space that stays on disk until vacuum reclaims it. On the right, the insert and the delete are both appends to a sorted buffer in memory, and the delete is a tombstone. The buffer is flushed to a new file when it fills. A read checks memory and then each file, newest first, and a range read steps over every tombstone it meets until compaction merges the files and drops them.
A B-tree pays when it writes, and an LSM tree pays when it reads. On the left, inserting 21 into a full page splits it in two, and deleting 18 leaves dead space that stays on disk until vacuum reclaims it. On the right, the insert and the delete are both appends to a sorted buffer in memory, and the delete is a tombstone. The buffer is flushed to a new file when it fills. A read checks memory and then each file, newest first, and a range read steps over every tombstone it meets until compaction merges the files and drops them.

It also explains a lot of confusing benchmark results. A write-heavy benchmark makes LSM engines look far better than B-tree ones, and a range-scan benchmark reverses the result. Neither result is about the product. Both are about which engine the product uses. If you know the engine underneath, you can predict the benchmark without running it.

Two benchmarks, opposite winners
Each bar is the range one node handles, from the working figures in the per-node table later in this section. On writes, the LSM engine is ahead, in green. On reads, the B-tree is ahead. A write-heavy benchmark and a read-heavy one pick opposite winners from the same two engines.Each bar is the range one node handles, from the working figures in the per-node table later in this section. On writes, the LSM engine is ahead, in green. On reads, the B-tree is ahead. A write-heavy benchmark and a read-heavy one pick opposite winners from the same two engines.
The benchmark measures the engine, not the product. Each bar is the range one node handles, from the working figures in the per-node table later in this section. On writes, the LSM engine is ahead, in green. On reads, the B-tree is ahead. A write-heavy benchmark and a read-heavy one pick opposite winners from the same two engines.
A clustering key sorts inside one partition
Each customer's orders sit in their own partition, on their own node, sorted by time. Customer B's last hour, in green, is one slice of one partition. The last hour for all customers, the yellow band, has no partition key, so the query reads every partition on every node.Each customer's orders sit in their own partition, on their own node, sorted by time. Customer B's last hour, in green, is one slice of one partition. The last hour for all customers, the yellow band, has no partition key, so the query reads every partition on every node.
Across partitions there is no order to use. Each customer's orders sit in their own partition, on their own node, sorted by time. Customer B's last hour, in green, is one slice of one partition. The last hour for all customers, the yellow band, has no partition key, so the query reads every partition on every node.

The access pattern lookup

Keep this table. Find the sentence that matches your busiest query and read across the row.

the query, as a sentencewhat it needsfamily
"given this id, get this thing"a key lookupany; do not choose on this alone
"given this parent, list its children, newest first"ordered scan under a keyrelational, or wide-column with a clustering key
"given these filters I did not plan for, find matching rows"a query planner and secondary indexesrelational
"given a phrase a human typed, find and rank"an inverted indexsearch
"given this id, add one to a number"an atomic counterin-memory
"everything in the last hour, across all keys"a time-ordered scan of everythingtime-series, or a column store
"these five things must change together or not at all"a transactionrelational
"walk from this node to things three hops away"index-free adjacencygraph, and rarely
"the whole object, exactly as written"one document readdocument, or a blob

There are two rules for using it. First, the busiest query wins, not the most complicated one. Second, if two rows are both essential and point to different families, you need a second store. A compromise product that does both badly is the wrong answer.

What to store where

This is the table most people come looking for. Treat each row as a starting point that you then justify with numbers, never as an answer you just state.

what you are storingwhere it goeswhy, in one line
bank balances, payments, orders, inventoryrelationalseveral rows must change together and be right; this is what transactions are for
user accounts, profiles, settingsrelationalsmall, relational, queried in ways you have not thought of yet
social posts and the follow graphrelational, sharded by userordered scans per user, and it outgrows one machine on storage before throughput
a precomputed feed or timelinein-memory lista cache of a query, rebuildable, so durability is not required
sessions, tokens, rate limit countersin-memoryexpires on its own, and losing it costs one window
shopping cartsin-memory with persistence, or documentone object read and written whole, and moderately sad but survivable if lost
likes, reactions, view countswide-column, or in-memory counterswrite rate an order of magnitude above the thing being counted, no joins
chat messages awaiting deliverywide-column with TTLhuge append rate, read once, and expiry rather than deletion
chat message history, if the product keeps itwide-column, partitioned by conversationappend-only, always read with the partition key, grows forever
images, video, documents, backupsobject storagetoo big for a database, immutable, and served by a CDN
product catalogue searchsearch index, derived from relationalthe query is about what is inside the text, which needs an inverted index
metrics and telemetrytime-seriesappend-only, time-ordered, compresses well, dropped by partition
application logslog store or object storage plus searchwrite-heavy, read rarely, and retention is the real design question
audit trails, ledgers, event historyappend-only relational, or a lognever updated, must be complete, and read in ranges by time
clickstream and analytics eventsqueue, then column storewrite path must not block the product; the read path is enormous scans
revenue by region by monthcolumn storescans columns across everything, and must never touch the product database
recommendations and embeddingsvector index, alongside the sourcesimilarity search, which is a different index structure again
who is connected to which serverin-memory registrychanges constantly, rebuildable by asking the servers
feature flags and configurationsmall store replicated to every noderead on every request, changed rarely, so it lives in memory everywhere

The records that must be right are relational, and most systems end up with three or four data stores rather than one or ten. If your design has one data store, check where the large files and the counters live. If it has eight, check that each one has a property the others lack.

What each family does, in numbers

These are rough figures for one node, so you can tell whether you're near a limit. They're working figures for judging the order of magnitude, not measurements. They move by 5x with the hardware, the row size and how much of the working set, the data that is read often, fits in memory.

Back of envelopePer node, and how each family grows
                        writes/s    reads/s    scales by
  ────────────────────────────────────────────────────────
  relational              5k-20k   50k-100k    replicas for
                                               reads, sharding
                                               for writes

  distributed SQL         2k-10k    20k-50k    add nodes; a
                          per node             commit crossing
                                               regions costs a
                                               round trip

  key-value (SSD)        10k-50k   50k-200k    add nodes, near
                                               linearly

  wide-column (LSM)      20k-100k  10k-50k     add nodes, near
                                               linearly; reads
                                               lag writes

  document                5k-20k    20k-80k    add nodes, by
                                               shard key

  in-memory             100k-1M    100k-1M     add nodes; one
                                               node is usually
                                               already enough

  search                  5k-20k     5k-30k    add nodes; index
                                               build is the cost

  time-series           100k-1M      varies    add nodes;
                                               cardinality is the
                                               real limit

  column / analytical      bulk     GB/s scan  add nodes; sized
                          loads                by scan volume

  object storage         unlimited  unlimited  it is somebody
                        in practice            else's problem

Two things this table is really saying:

1. In-memory is 10-100x everything else, and that is
   the entire reason caches exist.
2. Every family except relational scales writes by
   adding nodes. Relational needs sharding, which is
   machinery. That is the one real difference behind
   "NoSQL scales" and it is narrower than the slogan.

Throughput, the number of operations a second a store can do, tells you whether it keeps up. Latency, how long each one takes, tells you whether it fits your time budget. These are different questions. A data store can do 200,000 reads a second and still be too slow for a request with a 5 ms budget if each read takes 12 ms.

familyread p50read p99the thing that dominates it
in-memory, same datacentre0.2 to 1 ms1 to 3 msthe network round trip, not the lookup
relational, cached in the buffer pool0.5 to 2 ms5 to 15 msthe round trip, plus lock waits under load
relational, from disk2 to 10 ms20 to 100 msan SSD seek per index level it has to walk
key-value, SSD-backed1 to 5 ms10 to 30 msthe round trip and one disk read
wide-column (LSM)2 to 10 ms20 to 100 mshow many files a read touches before compaction merges them
document1 to 5 ms10 to 40 msthe same as relational, plus document size
search5 to 50 ms50 to 500 mshow many terms, and how many documents match
column / analytical100 ms to minutesseconds to minuteshow many bytes the scan has to read
object storage20 to 100 ms100 to 500 msfirst byte latency, then bandwidth

Three points come out of this table, and each one changes a design.

Your users feel the p99, not the p50. The p50 is the median read, and the p99 is the read that only 1 in 100 reads are slower than. Say a feed page hydrates twenty items, which means it fetches the full data for twenty ids in parallel. The page waits for the slowest of those twenty reads. The chance that at least one of them is slower than the p99 is 1 − 0.99^20, about 18 percent. So with a 12 ms p99, about one page load in five waits 12 ms or more, even though a typical read takes 1 ms. The more reads a request fans out to, the more often it lands in the slow tail, and latency numbers that matter works through that arithmetic.

How often a page waits on a slow read
The red curve is 1 − 0.99^n, the chance that at least one of n parallel reads is slower than the p99. At 20 reads it is 18 percent, so about one feed page in five waits 12 ms or more. At 100 reads it is 63 percent, and most pages wait on the p99.The red curve is 1 − 0.99^n, the chance that at least one of n parallel reads is slower than the p99. At 20 reads it is 18 percent, so about one feed page in five waits 12 ms or more. At 100 reads it is 63 percent, and most pages wait on the p99.
Twenty parallel reads hit the p99 on about one page in five. The red curve is 1 − 0.99^n, the chance that at least one of n parallel reads is slower than the p99. At 20 reads it is 18 percent, so about one feed page in five waits 12 ms or more. At 100 reads it is 63 percent, and most pages wait on the p99.

A read from disk is about 5 times slower than a cached one, and your hit rate decides which one you get. In the table, a relational read from the buffer pool, the database's own cache in memory, takes 0.5 to 2 ms at p50, and a read from disk takes 2 to 10 ms. The p99s differ by about the same factor. This is the same result as working set caching, reached from a different direction. A relational database with its working set in memory behaves like a different product from the same database with a cold cache.

LSM read latency depends on compaction keeping up. That's a property of how the cluster is run, not of its design. If compaction falls behind, each read checks more files and gets slower. Adding capacity doesn't fix it until compaction catches up. This failure happens in production at 3 a.m., and no comparison table lists it.

Transactions, and how much you actually need

People say "we need ACID" far more often than they mean it. ACID stands for atomicity, consistency, isolation and durability. Take the four letters one at a time, because they cost very different amounts.

Atomicity is usually what people mean, and it's the cheapest to get. It means several writes happen together or not at all. Most data stores give you this for free within a single partition or document. The only question is whether your writes span partitions.

Consistency, in the ACID sense, means your constraints hold, such as a balance never going below zero. It has nothing to do with the "consistency" in the CAP theorem or in eventual consistency. The two meanings share a word by accident, and consistency models separates them.

Isolation is where the real cost is. It decides what one transaction can see of another one running at the same time. The default in most relational engines isn't serialisable, the level where transactions behave as if they ran one after another. So anomalies like write skew can happen in your system today, and most teams don't know it. In write skew, two transactions read the same rows, each makes a change that is fine on its own, and together they break a rule. The good answer names the specific anomaly you care about, instead of asking for the strongest level.

Durability is the one to question, as step 4 of the method does. It's the only letter you can sometimes turn down completely.

So the useful version of "do we need transactions?" is this: do any two writes that must agree live in different partitions? If not, almost every store can do it. If they do, you have three options. You can use a relational engine. You can use a distributed transaction, which needs a coordinator and extra round trips. Or you can redesign so the two writes share a partition. The third option is usually the right one, and candidates almost never raise it.

Two writes that must agree
Sending a message writes the message and updates the conversation's last message. On the left, the two rows have different partition keys, so a coordinator prepares both (1) and then commits both (2). Each step is a round trip to both partitions and waits for the slower one. On the right, both rows are keyed by conversation id, so they sit in one partition and one atomic write covers both.Sending a message writes the message and updates the conversation's last message. On the left, the two rows have different partition keys, so a coordinator prepares both (1) and then commits both (2). Each step is a round trip to both partitions and waits for the slower one. On the right, both rows are keyed by conversation id, so they sit in one partition and one atomic write covers both.
If both rows share a partition key, the two writes are atomic for free. Sending a message writes the message and updates the conversation's last message. On the left, the two rows have different partition keys, so a coordinator prepares both (1) and then commits both (2). Each step is a round trip to both partitions and waits for the slower one. On the right, both rows are keyed by conversation id, so they sit in one partition and one atomic write covers both.

How reversible is each decision

Some of these choices are much easier to undo than others. If a team treats every one of them as permanent, it stalls. Here they are, from cheap to change to nearly impossible:

decisioncost to change later
adding an indexminutes to hours, online in most engines
adding a cachedays, and it can be removed just as easily
adding a derived store (search, analytics)weeks, plus permanent syncing cost
changing the storage engine's tuningdays, and reversible
changing the database productmonths to years; Slack took three
changing the shard keythe hardest thing on this list

Spend your caution on the bottom two rows. The top two are experiments rather than commitments, so don't agonise over them. And the shard key is harder to change than the product. That's why partitioning and sharding treats it as the hardest decision in the system to undo.

What one machine actually does

Here are the numbers, because most architectures are chosen for a load nobody has measured.

Back of envelopeOne machine, roughly, before anything exotic
A well-provisioned single relational primary:

  point reads (cached)               50,000 - 100,000 /s
  point writes (committed)            5,000 -  20,000 /s
  data size, comfortable                  up to ~10 TB
  single table, comfortable              up to ~500 GB

Read replicas multiply reads, not writes.
Caching multiplies reads, not writes.
Nothing multiplies writes except sharding.

Now compare against what people actually build for:

  a startup at 1M daily actives, 20 writes each
    = 20M writes/day = 231 /s mean, ~700 /s peak
    ⇒ 4-14% of one machine's write capacity

  a feed at 500M daily actives (this course's news feed)
    = 6,000 writes/s
    ⇒ still one machine, on writes alone

  the reads are what break first, and replicas fix
  those, which is why so many systems never shard

Sharding is forced by storage and maintenance long
before it is forced by write throughput. That is the
opposite of how it is usually taught.

The last line of that worksheet matters most. The limit you hit first is rarely write throughput. It's that a 40 TB table can't be vacuumed in a day. Vacuum is the Postgres job that reclaims the dead rows left by updates and deletes. The same table's indexes can't be rebuilt in any maintenance window you'll be given, and restoring it takes days. This is what pushed Figma to shard: tables of several terabytes were causing reliability problems during Postgres vacuums.

How long one full pass over a table takes
The orange line is the time to read a table once at an assumed 200 MB/s, roughly what vacuum, an index rebuild or a restore has to do. Notion's 500 GB limit per table takes under an hour. A 40 TB table takes 56 hours, over two days, in red. The write rate never comes into it.The orange line is the time to read a table once at an assumed 200 MB/s, roughly what vacuum, an index rebuild or a restore has to do. Notion's 500 GB limit per table takes under an hour. A 40 TB table takes 56 hours, over two days, in red. The write rate never comes into it.
Past about 17 TB, a full pass no longer fits in a day. The orange line is the time to read a table once at an assumed 200 MB/s, roughly what vacuum, an index rebuild or a restore has to do. Notion's 500 GB limit per table takes under an hour. A 40 TB table takes 56 hours, over two days, in red. The write rate never comes into it.

The operational questions

Interviews ask which store fits the queries. At work, the other question is who gets paged when it breaks. The four questions below decide more real choices than any benchmark, and raising even one of them in an interview shows experience.

How long does a restore take, and when did you last try one? Taking backups is easy. Restoring from them is the part you need. If a restore takes days, a bad enough failure means days without the data, and no replication figure tells you that.

What does a version upgrade cost? Some engines upgrade in place with a short failover, where a replica takes over while the old primary is upgraded. Others need you to export all the data and load it into the new version. For a large dataset that's a project, not a maintenance task. You'll do it several times over the life of the system.

What happens in a second region? A database with a single primary, as most Postgres and MySQL setups have, copies data to a follower in the other region. But every write still goes to the one primary, so a write from the other region pays the cross-region round trip. Some distributed stores accept writes in any region, and then you have to resolve conflicts when two regions change the same row. Neither is free. If you say "multi-region" without saying which of these you mean, you haven't answered. Usually only part of the data needs to be in more than one region at all.

Who runs it at 3 a.m.? A managed service and a cluster you run yourself are different products, even when the engine is the same. Tuning compaction, scheduling repair (the job that brings replicas back into agreement) and changing capacity are ongoing work, done by people you have to hire and keep.

The method

The method has seven steps. The first three take 5 minutes and decide most of the answer.

The method, step by step
Each box shows a step and its answer for the rate limiter in the worked examples below. Steps 1 to 3 take about 5 minutes. Step 5 is a branch: if one relational database still does the job, stop there. Steps 4 and 7, tagged often skipped, are the ones candidates leave out. Step 4 says the counters can be lost, and that is what lets step 7 give up durability.Each box shows a step and its answer for the rate limiter in the worked examples below. Steps 1 to 3 take about 5 minutes. Step 5 is a branch: if one relational database still does the job, stop there. Steps 4 and 7, tagged often skipped, are the ones candidates leave out. Step 4 says the counters can be lost, and that is what lets step 7 give up durability.
Steps 4 and 7 turn a preference into a decision. Each box shows a step and its answer for the rate limiter in the worked examples below. Steps 1 to 3 take about 5 minutes. Step 5 is a branch: if one relational database still does the job, stop there. Steps 4 and 7, tagged often skipped, are the ones candidates leave out. Step 4 says the counters can be lost, and that is what lets step 7 give up durability.

1. Write the access patterns as sentences. Each one names its key. "Given a post id, get the post." "Given a user, list their posts newest first." "Given a search term, find matching products." If you can't write the sentence, you don't know the query yet.

2. Mark the one that runs most. Usually one pattern runs 10 to 1,000 times more often than the rest, and you choose the data store for that one. Everything else can bend.

3. Get the write rate and the data size as numbers. Use writes per second and bytes, at peak, not the mean. Back-of-envelope estimation shows how.

4. Ask what you can afford to lose. This is three separate questions. Can this data be lost? Can it be stale? Can it be rebuilt from something else? A cache can be rebuilt, and so can a timeline. A payment can't. Data you can rebuild doesn't need durability, and dropping durability removes most of the cost.

5. Check whether one relational database still does it. Check it against the numbers from step 3, not against a feeling. If it does, stop here and say so, because that's the answer.

6. If it does not, name the single property forcing you off. It might be a write rate above what one primary can commit. It might be a data size, or maintenance work, beyond what one machine can sustain. It might be an access shape a B-tree can't serve, like matching words inside text. Or it might be a latency a disk can't meet. If you can't name it, you haven't found one, and you're about to add a data store for a reason you can't defend.

7. Pick the family with that property, and say what you are giving up. Say it out loud, as a sentence: "A hash-partitioned store, and I am giving up every query that does not carry the key, which is fine because there is exactly one and it does."

Worked examples

There are four examples. Each one ends in a decision, and each shows a different way the obvious answer fails.

A social feed, where the obvious store is not wrong but is not enough

Access patterns: given a user, get the recent posts of everyone they follow, newest first, in under 200 ms, 300,000 times a second.

The obvious answer is one relational database, and the arithmetic in news feed and timeline shows how it fails. A user follows 200 accounts on average. At 300,000 feed loads a second, that's 60 million lookups a second, before any ranking or rendering. The write rate is fine, and so is the data size. Read amplification breaks it: every feed load turns into 200 reads, and no index fixes a query that has to touch 200 partitions.

The fix isn't a different database. It's a second one. Posts and follows stay relational, because they're read with ordered scans and must not be lost. Timelines move to memory. A timeline is a cache of a query, the list of recent post ids for one user, and it can be rebuilt from posts and follows.

The record and the precomputed answer
A new post is written to the relational record (1). A fanout worker appends its id to each follower's timeline in memory (2). A feed load is then one read of one list (3), 300,000 times a second. If a timeline is lost, it is rebuilt from posts and follows (4), so it needs no durability.A new post is written to the relational record (1). A fanout worker appends its id to each follower's timeline in memory (2). A feed load is then one read of one list (3), 300,000 times a second. If a timeline is lost, it is rebuilt from posts and follows (4), so it needs no durability.
Timelines are a cache of a query, so they live in memory. A new post is written to the relational record (1). A fanout worker appends its id to each follower's timeline in memory (2). A feed load is then one read of one list (3), 300,000 times a second. If a timeline is lost, it is rebuilt from posts and follows (4), so it needs no durability.

Decision: relational for posts and follows, and in-memory lists for the precomputed timelines. Step 4 decided it. Timelines can be rebuilt, so they need no durability, so they can live in memory at a speed no disk matches.

Metrics, where the write rate and the cardinality both bite

Access patterns: append a measurement with a timestamp and a set of labels; read one series over a time range; aggregate across series.

The obvious answer is a table with (metric, labels, ts, value) and an index on (metric, ts). It works in staging and fails in production, for two reasons at once.

The write rate. If 1,000 hosts each send 500 metrics every ten seconds, that's 50,000 rows a second, about 4.3 billion a day. Commits aren't the limit, because each host's report can go in as one batched insert, about 100 commits a second. The rows are. Each row costs at least 52 bytes before its index entry, for an 8-byte value, each one adds an entry to the (metric, ts) index, and keeping a month means deleting billions of old rows one at a time.

The cardinality. A series is one metric with one exact set of label values, and the cardinality is how many distinct series there are. Labels multiply. If you add pod_id to a metric on a cluster that keeps replacing its pods, every new pod creates new series. The number of series grows without limit, so the index grows without limit, and every query relies on that index. The same multiplication breaks the cache key of a content delivery network (CDN), as CDNs and edge compute shows.

Series in the index, with and without pod_id
The assumed cluster runs 2,000 pods, replaces each one once a day, and every pod reports 50 metrics. With pod_id as a label, each new pod adds 50 new series, so after 30 days the index holds 3.1 million series and is still growing, in red. Without pod_id, the same metrics stay at 1,000 series, the flat green line along the axis.The assumed cluster runs 2,000 pods, replaces each one once a day, and every pod reports 50 metrics. With pod_id as a label, each new pod adds 50 new series, so after 30 days the index holds 3.1 million series and is still growing, in red. Without pod_id, the same metrics stay at 1,000 series, the flat green line along the axis.
A label that keeps changing makes the index grow without limit. The assumed cluster runs 2,000 pods, replaces each one once a day, and every pod reports 50 metrics. With pod_id as a label, each new pod adds 50 new series, so after 30 days the index holds 3.1 million series and is still growing, in red. Without pod_id, the same metrics stay at 1,000 series, the flat green line along the axis.

Both problems point to the same answer: an append-only store, partitioned by time and laid out in columns. Old partitions are dropped whole instead of deleted row by row. Values compress well, because neighbouring values in a series are similar.

Decision: a time-series store. It gives up joins, and ad-hoc queries across dimensions you didn't plan for. That's the price, and it's why a metrics store never becomes the general analytics store, even though it looks close.

A product catalogue, where the query is about what is inside the data

Access patterns: given a product id, show it. Given a phrase a human typed, find products that match, ranked by relevance, tolerating typos and plurals.

The first is easy in any store. The second is where the obvious answer fails worst. The obvious answer is WHERE name LIKE '%running shoe%'. A B-tree index can't help with a pattern that starts with %, so every search scans the whole table.

This isn't a scaling problem. It's a wrong index structure problem. An ordered index answers "where does this value sit in the order?" Text search asks "which documents contain these words?" That needs an inverted index, which maps each word to the list of documents that contain it. No amount of hardware turns one kind of index into the other.

Finding a phrase in product names
On the left, a B-tree on the name column keeps names sorted by their first letters. The words being searched for can be anywhere in a name, so the query reads every entry. On the right, the inverted index maps each word to the products that contain it. The search reads two short lists, keeps the ids found in both, 1, 6 and 9, in green, and ranks them.On the left, a B-tree on the name column keeps names sorted by their first letters. The words being searched for can be anywhere in a name, so the query reads every entry. On the right, the inverted index maps each word to the products that contain it. The search reads two short lists, keeps the ids found in both, 1, 6 and 9, in green, and ranks them.
An ordered index cannot find a word in the middle of a value. On the left, a B-tree on the name column keeps names sorted by their first letters. The words being searched for can be anywhere in a name, so the query reads every entry. On the right, the inverted index maps each word to the products that contain it. The search reads two short lists, keeps the ids found in both, 1, 6 and 9, in green, and ranks them.

Decision: relational as the source of truth, plus a search index as a derived store, one built entirely from the source. Change data capture keeps it up to date, rather than dual writes. Change data capture reads the database's own log of changes and applies each one to the index. In a dual write, the application writes to both stores itself.

Name this trap before the interviewer does: the search index is not a source of truth. You can always rebuild it, it will drift from the source, and the plan for rebuilding it is part of the design. Backfill and reprocessing covers the rebuild, and dual-write migration covers keeping the two stores in step.

A rate limiter, where durability is the wrong requirement

Access patterns: given a principal, increment a counter and compare it to a limit, in under 5 ms, 1 million times a second.

The obvious answer is a durable data store, because counters look like data. It fails at step 4. Of the four examples, this is the only one that fails on a question rather than on a number.

A counter is only useful until its window ends. If the node holding it dies, its counters start again from zero. Each affected principal, the user or API key being limited, gets a fresh allowance for the rest of that window, so at most twice its limit. In the next window the counts are right again. The error has a known size and fixes itself. Durability buys nothing anyone would notice. It costs a write-ahead log flush to disk and a replication round trip on every request, inside a 5 ms budget.

What losing the counters costs
The assumed limit is 100 requests a minute, the dashed line. In window 3 the node dies after 60 requests, in green, and the replacement counter starts at 0, so the principal gets up to 100 more, in red. That makes 160 in one window, under the ceiling of twice the limit. From window 4 the counts are right again.The assumed limit is 100 requests a minute, the dashed line. In window 3 the node dies after 60 requests, in green, and the replacement counter starts at 0, so the principal gets up to 100 more, in red. That makes 160 in one window, under the ceiling of twice the limit. From window 4 the counts are right again.
A lost counter costs one extra allowance, once. The assumed limit is 100 requests a minute, the dashed line. In window 3 the node dies after 60 requests, in green, and the replacement counter starts at 0, so the principal gets up to 100 more, in red. That makes 160 in one window, under the ceiling of twice the limit. From window 4 the counts are right again.

Decision: in memory, with persistence turned off on purpose. Distributed rate limiter works through it in full.

Across all four, the obvious store fails for a different reason each time: read amplification, then write rate and cardinality, then index structure, then durability. Knowing these four ways to fail is more useful than knowing four products.

Where it goes wrong

1. Naming a product before naming an access pattern

This is the most common failure, and interviewers watch for it. It gets the order backwards. The data store should follow from the queries, but here the queries get bent to fit a data store chosen in minute three.

You can spot it when a candidate can't say what happens to a query that doesn't carry the partition key. They can't say, because they never wrote the queries down.

2. Choosing for a write rate you do not have

Teams choose Cassandra for write throughput when they do 400 writes a second. That's 2 to 8 percent of what one Postgres primary commits. They've taken on eventual consistency, where replicas can briefly disagree, plus tombstones, repair and the loss of ad-hoc queries, to solve a problem they didn't have.

Do step 3 first. The real number is usually around 100 times below what the unusual store is built for.

400 writes a second, to scale
The blue sliver is your system's 400 writes a second. One Postgres primary commits 5,000 to 20,000 a second, and one Cassandra node takes 20,000 to 100,000, from the working figures in the per-node table. Cassandra is built for a write rate around 100 times this one.The blue sliver is your system's 400 writes a second. One Postgres primary commits 5,000 to 20,000 a second, and one Cassandra node takes 20,000 to 100,000, from the working figures in the per-node table. Cassandra is built for a write rate around 100 times this one.
The write rate barely shows against one primary. The blue sliver is your system's 400 writes a second. One Postgres primary commits 5,000 to 20,000 a second, and one Cassandra node takes 20,000 to 100,000, from the working figures in the per-node table. Cassandra is built for a write rate around 100 times this one.

3. Assuming one system means one database

Polyglot persistence, using several kinds of data store in one system, is the normal outcome, not a lack of discipline. Two of the four worked examples above end with two stores, and this course's Instagram design uses four. What matters is that each one is justified by a property the others lack, and that you can say which.

The opposite mistake happens too. A system ends up with five data stores where two would do, each added by a different team, and each one now needs someone on call.

4. Forgetting that a second store must be kept in step

Adding a search index or a cache is easy. Keeping it correct is the real work, and it never ends. A dual write can half-fail: the write to the database succeeds and the write to the index doesn't. Change data capture adds a pipeline that can lag or stall. You also need a reconciliation job, one that compares the two stores and fixes what differs. Teams rarely write it, and it's the job you need at 3 a.m.

Budget for the syncing, not just the data store. As a rough rule, a derived store costs about as much to keep correct as it cost to add.

Two ways to keep a search index in step
With a dual write, the application writes the database (1) and then the index (2). If the second write fails, nothing retries it and the stores differ. With change data capture, the application writes only the database (1). A consumer reads the database's change log (2) and applies each change to the index (3). If it stalls, the index falls behind and then catches up from its place in the log. Both still need a reconciliation job.With a dual write, the application writes the database (1) and then the index (2). If the second write fails, nothing retries it and the stores differ. With change data capture, the application writes only the database (1). A consumer reads the database's change log (2) and applies each change to the index (3). If it stalls, the index falls behind and then catches up from its place in the log. Both still need a reconciliation job.
A dual write can fail halfway, and change data capture can fall behind. With a dual write, the application writes the database (1) and then the index (2). If the second write fails, nothing retries it and the stores differ. With change data capture, the application writes only the database (1). A consumer reads the database's change log (2) and applies each change to the index (3). If it stalls, the index falls behind and then catches up from its place in the log. Both still need a reconciliation job.

5. Ignoring who runs it

For a team of four, a managed relational database and a Cassandra cluster you run yourself, usually called a ring, aren't comparable choices, whatever the benchmark says. Repair, compaction tuning, version upgrades and capacity changes are real work, done by people you have to hire.

This is a valid answer in interviews, and candidates rarely give it: "technically both fit; I would take the managed one because the team is four people and nobody here has run a ring."

6. Treating "we might need it later" as a reason

If you choose a distributed store today for scale you might reach in three years, you pay for its complexity every day until then. Usually that scale never arrives. The counter-argument is that migration is expensive. It is, and that's why step 6 exists: name the property that forces you off one database now. If the property is hypothetical, so is the requirement.

7. Confusing the transactional store with the analytical one

"Which database" is often two questions. The data store serving your product is built for many small operations by key. The data store answering "revenue by region by month" is built for scanning a few columns across every row. If you run the second workload on the first store, one dashboard query can take down production.

The product database and the dashboard
On the left, the product's small reads by key and a dashboard query that scans every row share one Postgres, so the scan takes the disk and memory the product reads need, in red. On the right, a pipeline copies changes into a column store such as ClickHouse, and the dashboard scans that instead.On the left, the product's small reads by key and a dashboard query that scans every row share one Postgres, so the scan takes the disk and memory the product reads need, in red. On the right, a pipeline copies changes into a column store such as ClickHouse, and the dashboard scans that instead.
Give the dashboard its own store. On the left, the product's small reads by key and a dashboard query that scans every row share one Postgres, so the scan takes the disk and memory the product reads need, in red. On the right, a pipeline copies changes into a column store such as ClickHouse, and the dashboard scans that instead.

In an interview, naming the split and the pipeline between the two stores is usually worth more than the products you pick.

8. Letting the schema decide the data store, or the reverse

"The data is nested, so we need a document store" argues from the data's shape when it should argue from how the data is read and written. Relational engines store nested documents well, and a document store will hold flat rows. The question isn't what the data looks like. It's whether the nested object is the unit of both reading and writing. If you always fetch the whole order with its line items, and always write it back whole, the order is the aggregate. That means it's the unit you read and write, and a document store fits. If anything queries line items across orders, it doesn't fit, and the nesting didn't matter.

The same mistake happens the other way round. A team normalises the data, splitting it into separate tables so that each fact is stored once. It ends up with eleven tables, one for each kind of thing, and then finds every read is an eleven-way join. Normalising is a default, not a law, and the access patterns tell you when to stop.

9. Not asking what can be lost

This is the question from step 4 that gets skipped, and it leads to the cheapest designs in this course. Timelines need no durability. Rate limiter counters need no durability. A CDN's copy of an image needs no durability. Each of those answers removes replication, backup and recovery from a whole tier, and nobody sees the saving unless somebody asks the question.

If you memorise nothing else

the linewhy it holds
You choose access patterns, not databasesthe data store follows the queries, never the reverse
Write the queries as sentences with the key in themif you cannot write the sentence, you do not know the query
One relational database, until a number says otherwiseFigma ran on one Postgres in 2020 and sharded its first table only in 2023
Sharding is forced by maintenance before throughputa 40 TB table cannot be vacuumed or restored in any usable window
Read replicas multiply reads; nothing multiplies writes but shardingreplicas and caches do not touch write capacity
B-tree makes ranges cheap and deletes expensivedead tuples must be reclaimed
LSM makes writes cheap and deletes expensivea delete is a tombstone you pay for twice
Clustering keys give ordered scans inside a partitioncross-partition ordering is a full scan
Search indexes are derived, never sources of truththey will drift, and the rebuild is part of the design
Rebuildable data needs no durabilitythis removes replication, backup and recovery from a whole tier
Ask what you can afford to loseit is the question that decides the cheapest designs
Polyglot is normal; unjustified polyglot is noteach store must own a property the others lack
A derived store costs as much to keep correct as to addbudget the syncing, not just the data store
Nobody switches databases casuallySlack took three years to move onto Vitess

What is expected at each level

Mid-level

Knows the families and can describe what each is for. Reaches for a relational database by default, which is right, and can name a case for a key-value store. Tends to answer with a product before stating the access patterns, and to justify a distributed store with "scale" rather than a number. Usually assumes one system means one database, and does not raise what happens to a query that does not carry the key.

Senior

Writes the access patterns down first and picks the data store from them. Sizes the write rate and data volume before deciding, and knows that one relational primary covers more than the question implies. Can say what a chosen store gives up, and names the second store when one is needed. Distinguishes the transactional store from the analytical one and puts a pipeline between them.

Staff+

Names the single property forcing the move off one database and says explicitly that a hypothetical property is not one. Separates the three questions inside "what can we lose": lost, stale and rebuildable, and uses rebuildability to strip durability out of an entire tier. Prices the ongoing correctness cost of every derived store rather than only its introduction, and names the reconciliation job. Weighs who operates the thing as a first-class input, and knows that maintenance windows bind before write throughput does.

Sources

Every real-world figure here comes from a published source, named below. Where a number is a working assumption, it's marked as one where it's used.

  • Figma's engineering blog on scaling Postgres, for the single Postgres instance on AWS's largest physical machine in 2020, and for the caching, read replicas and dozen vertically partitioned databases by the end of 2022. Also vacuum on multi-terabyte tables as the reason to shard, the nine-month timeline to their first horizontally sharded table, and logical sharding as an intermediate step, measured at under 10 percent overhead in the worst cases. At cutover in September 2023 they saw roughly ten seconds of partial availability on primaries.
  • Notion's engineering writing on sharding Postgres, for the operating ceilings of 10 TB per machine and 500 GB per table.
  • Slack's engineering writing on Vitess, for the three-year migration of 99 percent of their MySQL query load, at roughly 2.3 million queries per second at peak.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.