Choosing a database
Read first: Back-of-the-envelope estimation
The read and the write pick the database. Relational rows earn their keep when a join is local and a schema protects an invariant. Key-value, document, wide-column, and graph stores each match a different shape, and a second database is a dual-write problem you should not start with.
You pick a database by the shape of the read and the write. A trip that must agree with a payment wants rows and a transaction. A message that is always loaded with its channel wants a key you can point at. A follow wants an edge stored as an edge. The product name on the box is the last thing you say.
Core concepts
Every store answers a small menu of questions quickly and makes the other questions someone else’s problem. Name the question before you name the engine. The five shapes below cover almost every interview you will get in this course.
Relational. A table of typed rows, a primary key, and joins against other tables that live on the same machine. A transaction groups several reads and writes so they commit or fail together. That is the tool when two facts have to move as one: the trip row and the charge, the reservation and the seat. Transactions and isolation is the menu of guarantees inside that commit. The schema is part of the product. A missing rider id, a duplicate trip id, or a state that is not in the allowed set is a write the database rejects, so every service does not have to remember the check.
Key-value. The question is get, put, or delete by one key. A session, a feature flag, a precomputed page. There is no join, and a pure hash index has no range: “the keys from A to M” is not a question it answers. If the values have to come back in key order, say so. You just asked for the ordered structure in Indexes: B-trees and LSM trees, or for a wide row, not for a hash table.
Document. The unit of read and write is one nested value per key. A trip document can hold the rider, the route, the fare, and the state, and you fetch it in one get. Adding a field does not require a table migration. The cost is everything that used to be a constraint across rows. Two documents do not commit together unless you add a transaction the engine may not have, and a reader must tolerate a document written by an older version of the code.
Wide-column. The model in the Bigtable paper is a sparse, sorted map. The key is a row key, then a column family and a qualifier, then a timestamp, then bytes. Empty cells cost nothing. Column families are the unit of locality and of access control: put the columns you read together in one family. Rows are split into tablets by row-key range. The access pattern that fits is “this row key, these columns, in order.” Discord’s message cluster used that shape in Cassandra: the partition key was a channel id plus a time bucket, so one channel’s messages in a window landed together. The Discord’s message store page is the production version of that sentence.
Graph. The question is an edge, not a join. Given a person, list the edges of one type. Given a post, list who liked it. Facebook TAO is a graph-shaped cache in front of MySQL, and the association it stores is id1, type, id2, plus a time and a small payload. The inverse association is stored as its own row, so “who liked this” is a range read and not a scan of every like in the system. You pay for that on the write: a like writes both directions. You do not pay for it with a join on the read.
A useful test is to write the one query the page cannot live without, and to circle the key it starts from. If you cannot circle a key, you do not yet know which of the five you are using.
When a join hurts
A join on one machine, backed by an index, is a fine plan. It is the reason you start with a relational database. It hurts in three concrete ways.
The rows are not on the same machine. Once Partitioning and sharding places the trip on one shard and the rider on another, the join is a network call. A round trip inside one datacenter, on the teaching list in Latency numbers that matter, is 0.5 ms before any bytes of the row. Twenty of those in series is 10 ms of network, and the arithmetic is 20 times 0.5. In parallel you wait on the slowest, and a fanout of twenty is how a page gets slow while every service looks healthy.
The application does the join as a loop. Loading forty edges by forty point reads is forty round trips. At 0.5 ms each, done one after another, that is 20 ms of network for data that was one range. The join was not expensive because SQL is expensive. The plan was a loop.
The product does not want a join. “The last page of this channel” is a range on channel id and time. Joining every message to the users table on the way adds a hotspot and a query you cannot keep on one shard. Store the sender’s display name the way the read wants it, or fetch the handful of distinct senders after the page is loaded. Do not make the message read depend on a join you will regret the day you shard.
Schema as a feature
A schema is a list of writes you refuse. Rider id is present. Trip id is unique. State is one of a small set. Message rows name a channel that exists. The database enforces that on every writer, including the backfill job someone runs at 2 am. That is the feature. Application code will forget.
The cost is a migration. Adding a column or a constraint on a large table can rewrite it or lock it, and that rewrite becomes the incident. There is a middle path that keeps the feature: a relational key and the constraints that matter, plus a payload column for fields that are still moving. You decide, out loud, which checks are the database’s and which checks are the application’s. “We will figure the shape out later” means every reader is the schema, and the first typo lands in production.
Dropping the schema is a real response to a real migration problem. It is a bad response to a fear of migrations you have not hit yet. The grown-up version of that story is in the aside below. Do not start there.
Start with one database
One database gives you one transaction, one backup, and one place an invariant can live. A saga, which you will meet later, exists because there is no global rollback across services. The right answer, while the rows still fit in one database, is the transaction you already have.
A second store is a second failure domain. The message commits and the trip’s last-message pointer does not, or the process dies between the two calls. The outbox pattern and sagas is how you close that hole after you have earned it. You earn it when a measured access pattern does not fit, not when a diagram looks complete with five boxes.
Read scale of the same rows is Replication, not a new data model. A cache in front of one database is still one database. Survival of a disk is also replication. None of those change the key you query by.
Slack’s published message path is the existence proof for staying relational: MySQL from the start, messages sharded by channel id so one large workspace does not sit on one shard. The access pattern is still “append and read a window for this channel.” The engine did not have to become a different species to match that key. Discord’s published path used a wide-column partition key of channel id plus a time bucket for the same window. Two engines, one question. Pick the question first.
A worked example
You are storing three things for one product: trips, messages, and a social graph of follows and likes. One team, one region, and you have to say where each byte goes. Every number in this section that is not a conversion of a day is an assumption. Say them as assumptions.
- 5 million daily active users.
- 0.4 trips per user per day. Each trip is 5 writes and 10 reads over its life.
- 30 messages sent per user per day. Each user opens 10 message pages a day, and a page is one range read of one channel.
- Each user loads one social view a day. Done well, that view is one range of 40 associations. Done badly, it is 40 point reads.
- A message is 400 bytes, a trip row is 1 KB, an association is 100 bytes.
- Peak is 3 times the average. That multiplier is an assumption, inside the 2x to 5x band you have to state.
- Three copies on disk when we talk about a month of messages. That is a replication factor you chose for the estimate.
A day is 86,400 seconds. The interview shortcut is about 100,000 seconds, from Back-of-the-envelope estimation. Both are below so you can see the shortcut miss by a little.
trips 5,000,000 * 0.4 = 2,000,000 trips/day
writes 2,000,000 * 5 = 10,000,000 / 86,400 = 115.7/s
reads 2,000,000 * 10 = 20,000,000 / 86,400 = 231.5/s
shortcut 10,000,000 / 100,000 = 100 writes/s
messages 5,000,000 * 30 = 150,000,000 / 86,400 = 1,736.1 writes/s
shortcut 150,000,000 / 100,000 = 1,500 writes/s
pages 5,000,000 * 10 = 50,000,000 / 86,400 = 578.7 reads/s
social 5,000,000 / 86,400 = 57.9 range reads/s
bad plan 57.9 * 40 = 2,316 point reads/s
peak 3x message writes 1,736.1 * 3 = 5,208.3/s
bytes 5,208.3 * 400 = 2,083,320 bytes/s, about 2.1 MB/s
day 150,000,000 * 400 = 60 GB of messages
month 30 * 60 GB = 1,800 GB
3 copies 5,400 GB
Read the result before you reach for a second engine. A few thousand small writes a second, and a couple of megabytes a second at a pessimistic peak, is a single database. The month of messages, even times three copies, is a disk-capacity conversation, not a new data model. The model still has to match the three questions.
Trips stay relational. A trip has a unique id, a rider id that must be present, and a state in a small set. Settling a trip reads the old state and writes the new state in one transaction, and the charge either commits with that or it does not. A document would let the fare object grow without a migration, and you can put a JSON payload on the row for fields that are still moving. The uniqueness and the required rider id stay in the schema. That split is the schema doing its job.
Messages are a range, not a join. The primary key starts with the channel id, then time, then the message id. The page read is one range of about fifty messages. It does not join the users table. Display names for the distinct senders on that page are a second, small lookup. Slack’s shape and Discord’s shape both do this. You can keep the table in the same database as trips for a long time. What you must not do is make “load this channel” a join that will be wrong the day the table moves to its own shard.
The graph is edges, even while it lives in the same database. An association row is actor, type, object, time, and a short payload. A follow writes that row and the inverse row, object, type, actor. “Who does this person follow” and “who follows this person” are both range reads. TAO does this in a cache in front of MySQL because the product questions would have been joins on the read path. You can copy the row layout now and leave the cache for the day 58 reads a second stops being 58.
The bad social plan is the one to say out loud. Forty point reads at 0.5 ms, in series, is 20 ms of datacenter round trips for one view, from 40 times 0.5. At peak that is 2,316 times 3, about 6,950 point reads a second, against a machine that only had to serve 57.9 range reads a second times 3, about 174. The database did not get harder. The access pattern did.
flowchart TD
path[Access pattern]
rel[Relational rows and joins]
kv[Key value point lookup]
doc[Document per key]
wide[Wide column row key]
edges[Graph edges both ways]
path --> rel
path --> kv
path --> doc
path --> wide
path --> edges
The failure you get if you split anyway. Suppose the message table moves to its own database on week one, because messages are “a different domain.” Sending a message inside a trip writes the message store, then updates the trip’s last-message pointer. The message commit succeeds. The trip update times out. The driver sees a trip with no message, or the rider retries and you store a second message. There is no transaction across the two stores. That window exists on every one of the 1,736 sends per second. A single crashed process is enough. You did not buy scale. At 116 trip writes per second the trip database was not full. You bought a disagreement you cannot roll back.
Disk is not the forcing function either. 60 GB of new messages a day is real, and 5,400 GB after a month at three copies is something you plan for. It is still one primary and a backup story. When a single channel inside that 60 GB is hotter than the disk, the fix is a partition key, which is the next lessons, not a second species of database.
Tradeoffs
| Choice | What you keep | What you give up |
|---|---|---|
| One relational database | Local joins, a schema, one transaction | A migration when a constraint changes, and a hotspot if every query joins the same hot row |
| Key-value for the point reads | A cheap get by key | Ranges, joins, and any invariant that spans two keys |
| Document per trip | One get, and a new field without a migration | Constraints that cross documents, and readers that must accept an old shape |
| Wide-column row for messages | A sparse, ordered row keyed the way the page reads | Joins and multi-row transactions as the normal tool |
| Edges stored in both directions | Each product question is a range, not a scan | A write that must update two rows, and a repair if one of them fails |
| A second database on day one | An engine aimed at one pattern | A dual write, two backups, and no single rollback |
The last row is the one people choose too early. An engine aimed at one pattern is a good second system when the first system has a measurement. It is a bad first system when the measurement is “we might need it.”
Pitfalls
- Picking a graph database because the product is social. The hot path is “last page of this channel,” which is a key range. The symptom is a traversal with no bound on a page that wanted fifty messages.
- Dropping the schema before a migration has ever hurt you. The symptom is a writer storing a string where a reader expects a number, found by a user.
- Starting with three databases for trips, messages, and follows. The symptom is a send that commits in one store and times out in the other, with no rollback.
- Doing the join in a loop of point reads. The symptom is a page whose latency is N times a datacenter round trip, here 40 times 0.5 ms, while a range read of the same edges would have been one.
- Joining messages to users on every load. The symptom is a user table that becomes the hotspot, and a query you cannot place on a channel shard later.
- Treating “the rows are related” as “the query must be a join.” The symptom is a read path that cannot be partitioned by the key the product actually has.
- Copying a large company’s second store into a five-person design. The symptom is operational work, dual writes, and a rate, like the 116 trip writes per second above, that never needed it.
- Hiding a range inside a hash-only key-value store. The symptom is “recent items” implemented as a full scan, which will be the incident the day the bucket grows.
In the interview
Spend the first five minutes on the questions, not the vendors. Say: trips are relational because a state change and a charge commit together, and the schema refuses a trip without a rider. Messages are a range on channel id and time, in the same database until a shard forces them out. Follows are two association rows so neither direction is a scan. Then give one number you derived. At 5 million users and 30 messages a day you are at about 1,700 writes a second average, about 5,000 at a peak you state as 3x, and about 2 MB/s. That fits one primary.
Skip the tour of five products. Skip replication factor, cache tiers, and multi-region. Those are later, and you can say they are later. The interviewer is listening for a key, a transaction boundary, and one reason you did not split.
The question that usually follows is “the message table outgrows the box, what do you do?” The answer is a partition key of channel id, not a new species of database, and you say what the split costs: the trip pointer and the message are no longer one transaction. If they ask about the social read, say you store the inverse edge so the read stays a range. If they ask about schema, say which invariants the database still rejects and which fields are allowed to move.
Check yourself
The channel id is known, and the page loads the last 50 messages by joining messages to users and then to channels. What is wrong, and what key should the read use?
The product question is a range on one channel, ordered by time. The joins add the users table to every load and will not survive a shard keyed by channel. Read by channel id and time. Resolve the few distinct senders on that page after the range returns, instead of joining every message to a user row.
You estimate about 100 trip writes a second and a teammate wants separate databases for trips, messages, and follows before launch. What do you refuse, and which property did you just lose?
Refuse the split. That rate is one database, and the estimate should be shown as a daily count divided by 86,400. What you lose on the day you split is a single transaction. A message can commit while the trip update fails, and nothing rolls the pair back.
A document store lets a trip gain a field without a migration. What did you give up, and when is the document the right unit?
You gave up a database-enforced invariant across documents, and you accepted that old documents lack the new field. The document is the right unit when the read and the write are that one object. It is the wrong unit when two objects must commit together or a constraint must reject a bad write from every client.
A like is stored as one row from the user to the post. Why is who liked this painful, and what do you write so it stays a range?
The inverse question is not indexed, so it becomes a scan of likes. Store the inverse association as its own row, the way TAO stores both directions of an edge. The like path writes two rows. Each product question is then a range on a known key, which is the cost you wanted to pay.
Based on: Designing Data-Intensive Applications, Kleppmann and Riccomini; Bigtable, Chang and others; Facebook TAO, Bronson and others; Uber Schemaless; Discord message store; Slack Engineering.