Picture an online shop’s data: customers, products, orders, reviews. The same data could sit in tables of rows, in nested documents, as values behind keys, as rows inside partitions, or as nodes in a graph. Each of those shapes makes some questions quick to ask, and others slow, awkward or impossible.
The shape a database gives your data is its data model. It decides what the database does for you, and what you must do yourself, in application code or by reading far more data than you need. The way a workload uses its data is its access pattern: what it reads and writes, by which key, how often, how large the answers are, whether the records refer to one another, and how far the data must grow.
Mental model. A data model is a decision about which questions are cheap. Whatever you did not plan for is paid for in application code, or in a scan of everything.
So the choice starts from the workload, not from the products. Write the access pattern down first: the three or four reads and writes that matter most, how often each happens, and what must never go wrong.
This lesson takes one well-documented example for each family, so that every statement can be checked against its documentation. Real products blur the lines, as the end of the lesson shows.
Model
The data is
Cheap
Expensive
Example
Relational
Rows in tables with declared columns, which refer to one another through keys
Several steps as one transaction, joins, rules enforced by the database
Changing the declared shape, and spreading writes over many servers
PostgreSQL
Document
A document with named, nested fields, holding together the data used together
Reading or writing a whole business object, records of one kind with different fields
Relating documents, and changes that span several documents
MongoDB
Key-value
An opaque value stored under a key
Reading and writing one item by its key, spreading keys over machines
Every question that is not “the item with this key”
Dynamo
Wide-column
Rows grouped under a partition key, kept in order within it
Heavy writes, and reading a range of rows of one partition in order
Joins, and any query the table was not designed for
Bigtable, Cassandra
Graph
Nodes and relationships, both with properties
Following relationships several levels deep
Open-ended patterns that match far more than you meant
Neo4j
What the documentation says, family by family:
Relational. PostgreSQL’s tutorial says that a transaction bundles multiple steps into a single, all-or-nothing operation, and that the intermediate states are not visible to other concurrent transactions. It also says that queries that access multiple tables at one time are called join queries. A foreign key constraint specifies that the values in a column must match the values appearing in some row of another table, so the database itself refuses an order for a product that does not exist. The price is that columns are declared before data is stored.
Document. MongoDB’s guidance is that data that is accessed together should be stored together, and that documents within a single collection are not required to have the same set of fields. An operation on a single document is atomic. A change across several documents needs a multi-document transaction, which MongoDB says usually costs more than single-document writes and should not replace effective schema design.
Key-value. The Dynamo paper describes its query model as simple reads and writes of a data item identified by a key, with the state stored as binary objects and no operation that spans several items. Its authors observed that many of Amazon’s services only store and retrieve data by primary key and do not need the complex querying of a relational database. The objects are relatively small, usually under 1 MB.
Wide-column. Bigtable keeps data in lexicographic order by row key, so reads of short row ranges are efficient and involve only a small number of machines, and every read or write under a single row key is atomic. Cassandra orders the rows of a partition by their clustering columns, which makes retrieving a range of rows within one partition very efficient. It has no joins: you start from the queries, and when you need something like a join you create a denormalised second table.
Graph. Neo4j’s documentation describes nodes as entities, relationships as connections between a source node and a target node, and properties as key-value pairs on both. It calls Neo4j schema optional. Its manual warns that a quantified path pattern can match very large numbers of paths and run slowly, and advises bounding it.
The explorer below holds the five options and seven requirements. Hide the options you are not interested in, tick the requirements that apply to a system you have in mind, and read the verdict on each option, with the reason. It does not pick a winner. It counts how each option measures up against what you ticked, and the reasons are the part to read.
Data models
Which data model fits the way your application reads, writes and connects its data, and how far must it scale?
Every option follows the same framework: decision, why, benefits, costs, failure modes, scaling limitations, alternative.
Choosing options and requirements needs JavaScript. All the options are shown below.
Relational
1. Decision
Data lives in tables of rows with declared, typed columns. Rows refer to one another through keys, and SQL filters, joins and aggregates tables in one query. PostgreSQL is the example used here.
2. Why?
A declared schema, constraints and transactions let the database protect the rules of the data itself, and joins let it answer questions the application did not plan for.
3. Benefits
A transaction bundles several steps into one all-or-nothing operation, and other sessions do not see the intermediate states.
One query can join several tables, and aggregate functions summarise the result.
The database enforces rules itself: unique, not-null, check and foreign key constraints, so a reference cannot point at a row that does not exist.
4. Costs
The columns are declared before data is stored, so changing them is a migration. Adding a column is quick when its default is constant or NULL, but a volatile default rewrites the whole table and its indexes.
A business object that is normalised over several tables takes a join to read and several rows to write.
Free-form fields fit awkwardly. A jsonb column can hold them, but PostgreSQL’s documentation advises a somewhat fixed structure so that queries stay easy to write.
5. Failure modes
A recursive query over cyclic data never ends. PostgreSQL’s own graph-search example loops if the links contain cycles, and needs cycle detection (the CYCLE clause).
If the primary fails, committed transactions can be lost. PostgreSQL streaming replication is asynchronous by default, so a transaction that the primary committed but had not yet sent to the standby is lost if the primary fails catastrophically.
6. Scaling limitations
To spread data over servers, PostgreSQL’s documentation describes data sets that are each modified by only one server; an application that needs two sets queries both servers.
Standby servers answer read-only queries, so they add read capacity, not write capacity. PostgreSQL does not offer synchronous multimaster replication, where every server accepts writes.
7. Alternative
Choose Document when a business object is almost always read and written whole, records of one kind differ in shape, and data must spread over several machines.
Document
1. Decision
Each record is a document with named fields, which can hold nested documents and arrays. Data that is used together is stored together in one document. MongoDB is the example used here.
2. Why?
A core principle is to store together the data that is accessed together, so one read returns a whole business object and one write to a document is atomic. Documents of one collection may have different fields.
3. Benefits
Embedded documents and arrays hold related data in one document, and an operation on a single document is atomic, so many changes need no transaction.
Documents in a collection need not have the same fields, and validation rules can be added only to the parts that need stricter control.
Sharding is built in: the shard key distributes a collection’s documents across machines, to support very large data sets and high throughput.
4. Costs
Embedding can mean duplicating data. MongoDB recommends references when the child side has high cardinality, when duplication is too complicated to manage, or when embedded data grows without bounds.
A change across several documents needs a multi-document transaction. MongoDB supports them, including on sharded clusters, but they usually cost more than single-document writes and should not replace good schema design.
Relating documents is the application’s job: MongoDB tells you to add application logic to keep references consistent. A join across collections is a $lookup stage, a left outer join in an aggregation pipeline.
5. Failure modes
A document that keeps growing. An embedded array with no natural bound grows until the document reaches the maximum size of 16 MiB.
Copies that disagree. When the same data is embedded in many documents, an update that stops half-way leaves the copies different, unless a transaction covers it.
A poorly chosen shard key spreads data unevenly, which can negate some benefits of sharding or cause performance bottlenecks.
6. Scaling limitations
The shard key sets the trade-off. Hashed sharding spreads data evenly, even for keys that increase steadily, but range queries on the key are more likely to reach every shard. Ranged sharding lets mongos send an operation only to the shards that hold the data, but its efficiency depends on the key chosen.
Transactions across documents cost more than single-document writes, so a request that touches one document is the cheapest to serve.
7. Alternative
Choose Relational when you must join and aggregate across many kinds of records in ways you cannot predict, or when transactions across many records are routine.
Key-value
1. Decision
Reads and writes address a value by its key. In Dynamo, the published design used here, the value is opaque bytes that the store does not interpret. Redis, the other example, adds data structures such as hashes and sorted sets, still addressed by key.
2. Why?
When the access pattern really is to fetch the object stored under a key, the store can stay simple, spread keys over nodes by hashing them, and add capacity one node at a time.
3. Benefits
Keys are spread over nodes by hashing: Dynamo uses consistent hashing, and Redis Cluster maps each key to one of 16,384 hash slots.
Dynamo aims to stay writable: its design goal is a store where no update is rejected because of failures or concurrent writes.
Any value shape fits. Dynamo treats keys and values as opaque arrays of bytes, so the store needs no change when the structure of a value changes.
4. Costs
Everything goes through the key. Dynamo’s query model is a read or write of one item identified by its key, with no operation spanning several items and no relational schema.
Searching by contents needs an index you maintain or an add-on query engine. Redis, for example, offers Redis Search as a secondary index and query engine.
Transactions are weak. Dynamo gives no isolation and permits only single-key updates, and Redis does not roll back a transaction when one of its commands fails.
5. Failure modes
Acknowledged writes are lost. Redis Cluster replicates asynchronously, so an acknowledged write is lost if its master fails before the write reaches a replica.
Conflicting versions. Dynamo accepts concurrent writes, so a read can return several versions of an object, and the application, or a simple rule such as last write wins, must reconcile them.
A hot key. The key alone decides which nodes hold a value (Dynamo hashes it, Redis Cluster takes its slot from it), so one very popular key cannot be split: its traffic stays on the nodes that hold it.
6. Scaling limitations
Redis Cluster has 16,384 hash slots, which caps the cluster at 16,384 master nodes, and its documentation suggests staying on the order of 1,000 nodes.
Operations across several keys are limited. In Redis Cluster, set unions and intersections work only when all the keys hash to the same slot, hash tags can force that, and such operations can be unavailable during resharding.
7. Alternative
Choose Wide-column when each key should hold many rows that are read back in order, such as one device’s readings between two times.
Wide-column
1. Decision
Data is addressed by a row key (Bigtable) or a partition key (Cassandra). Bigtable keeps rows in order by row key, and Cassandra sorts the rows of a partition by their clustering keys, so a range can be read together. A row can hold many columns, and tables are designed around the queries they must answer. Bigtable and Cassandra are the examples used here.
2. Why?
A key that partitions the data spreads writes and volume over many machines, the write path only appends, and rows that are read together sit together, in order.
3. Benefits
The write path only appends. Cassandra writes to a commit log and a memtable, then flushes to immutable SSTables, and its documentation calls the write path highly optimised.
Reading a range is efficient. Bigtable keeps rows in order by row key, so reads of short row ranges involve only a small number of machines, and Cassandra sorts the rows of a partition by clustering keys.
There is no single primary. Cassandra replicates every partition to many nodes, and every replica can accept writes (multi-master replication with tunable consistency).
4. Costs
No joins. Cassandra’s documentation says you cannot perform joins: you do the work on the client side or create a denormalised second table. You start from the queries, then design a table for each.
Only queries on the key are cheap. Only equality is allowed on a partition key, and filtering on another column needs a secondary index or ALLOW FILTERING, which runs a full scan.
Compaction rewrites data in the background, so each write is rewritten several times (write amplification), which adds background I/O.
5. Failure modes
A query the key does not serve. ALLOW FILTERING scans every partition, so latency grows with the amount of data and performance is unpredictable.
Copies out of step. The same data is stored in several tables, one per query, and each write must reach all of them. A logged batch makes the updates complete eventually or not at all, but isolation covers only updates that share a partition key, so a reader can see one table updated before another.
Replicas that disagree. Cassandra is eventually consistent: divergent versions of the same data can exist temporarily before they are reconciled.
6. Scaling limitations
A partition lives on one set of replicas, so it must stay small and evenly spread. Cassandra’s documentation gives a general guideline of fewer than 100,000 values and less than 100 MB per partition, and says the partition key must distribute data evenly across the cluster.
The unit of atomic change is small. Bigtable guarantees atomicity for one row and has no general transactions across row keys, and Cassandra isolates a batch only within a partition key.
7. Alternative
Choose Relational when the queries are not known in advance, or you need joins, constraints and transactions across many rows.
Graph
1. Decision
Data is stored as nodes, which are entities, and relationships, which are directed, typed connections between two nodes. Both can carry properties. A query describes a pattern of connections and the database finds the matches. Neo4j is the example used here.
2. Why?
When the questions are about how things connect, relationships are first-class, so following them is a pattern in the query rather than a chain of joins.
3. Benefits
Connections are written as patterns. Neo4j’s documentation says there is no need to JOIN tables, and variable-length patterns match paths of unknown length.
Indexes and constraints are optional: Neo4j is described as schema optional, and properties are key-value pairs on nodes and relationships.
Transactions are ACID: operations that access the graph, indexes or schema run in a transaction.
4. Costs
A business object is made of nodes, relationships and properties rather than stored as one record, so reading it back is a pattern query, not a single lookup.
Splitting a graph over several databases is a design decision. Behind a composite database, queries written for a single database must be modified according to the sharding rules.
Open-ended traversals have to be bounded. Neo4j’s manual recommends inline predicates that say precisely which nodes and relationships to include, so that unwanted results are pruned as the graph is traversed.
5. Failure modes
A pattern that matches far too much. Quantified path patterns can match very large numbers of paths, resulting in slow queries, especially with a large maximum length or a pattern that is too general.
Losing the write majority. A database remains available for writes as long as a simple majority of its primaries is working.
A write that spans two shards. A composite database allows only transactions that write to a single graph, so a change that must touch two shards cannot be one transaction.
6. Scaling limitations
One database has one writer. It pushes writes synchronously to other primaries and completes a commit only when enough members confirm, and secondaries are there to scale reads.
Beyond one database, Neo4j’s documentation lists composite databases over shards (an Enterprise Edition feature, with write concurrency scaling horizontally depending on the graph model) and property sharding (the structure stays in a single graph shard, with the write concurrency of a single instance).
7. Alternative
Choose Relational when the connections you follow are shallow, a join or two, and most questions are about the rows themselves.
Nothing is ticked yet. Tick a requirement to see how each option measures up.
The ledger. Tick One change touches several records and must apply entirely or not at all., Next month’s questions are not known yet: you must filter, join and aggregate across kinds of records without redesigning storage. and The database itself must reject bad data: duplicate values, missing required values and references to records that do not exist. The relational option meets all three. The key-value option meets none of them and fails all three. A system that moves money and answers unplanned questions is what the relational model is built for.
The catalogue. Untick those, and tick Writes and data volume exceed one machine, and reads are mostly a lookup by key., Records of one kind have different fields, and the fields change often. and The application reads or writes a whole business object, such as an order with its lines, in one request. The document and key-value options meet all three, and the relational option only partly meets each. Now add Next month’s questions are not known yet: you must filter, join and aggregate across kinds of records without redesigning storage. The document option still meets three of the four and partly the new one, while the key-value option fails it. What separates a document from an opaque value is that the database can see inside it.
The trade-off. Untick everything, and tick One change touches several records and must apply entirely or not at all. and Writes and data volume exceed one machine, and reads are mostly a lookup by key. Look at the five options: none of them meets both. Each meets exactly one of the two, and only partly meets the other or fails it. That is the plainest trade-off in this module, and the next three modules of the course, on transactions, replication and partitioning, are about what it costs to push on it.
Twelve descriptions of workloads, four models. Decide for each which model the access pattern points to. Every answer is explained, whether you got it right or not.
Challenge
Which data model?
Twelve workloads, four data models. Read the access pattern in each description and put it under the model it points to. Graph stores are left out of this exercise: the trade-off explorer above has a requirement for connected data.
Sorting needs JavaScript.
Categories
Relational
Tables, joins, transactions and rules enforced by the database.
Document
Whole objects with nested fields that can differ from one record to the next.
Key-value
One opaque value per key, read and written by that key alone.
Wide-column
Rows kept in order within a partition, written heavily and read by range.
Check your answers at least once before looking at the answers.
What happens if tomorrow’s question is not today’s?
A team stores each shopping cart as a value under the cart’s ID. It suits the access pattern perfectly: every request fetches one cart by ID and writes it back whole, nothing ever searches inside a cart, and the store spreads the keys over machines by hashing them.
Then the support team asks for every cart that a given customer has abandoned this month. The store cannot answer. In the Dynamo paper’s query model there is no operation across items, and a value is a binary object that the store does not look inside. So the application takes on the work. It keeps a second set of keys, from customer ID to cart IDs, and updates it on every write.
That costs more than it looks. Every cart change is now two writes to two keys. Dynamo permits only single-key updates and gives no isolation guarantees, so nothing makes the two writes one operation: a failure between them leaves the index and the carts out of step, and the application has to find and repair the difference. A relational model would have answered the support question with one query, and would have kept the two in step with a transaction. The key-value model has not done anything wrong: its question was “the item with this key”, and the new question is a different one.
The lesson is not that one model is better. A model is cheap for the questions it was chosen for, and each new kind of question has to be paid for somewhere: in the database, in application code, or in a second copy of the data that must be kept in step. The next lessons are about the copies, the indexes and the layouts that make each payment smaller.
A data model is a decision about which questions are cheap. Choose it from the access pattern: what the workload reads and writes, by which key, how the records relate, and how far it must scale.
Relational stores make transactions, joins and database-enforced rules cheap, and make a change of shape or a spread over many servers harder.
Document stores keep together what is used together and allow records of one kind to differ, and leave the relating of documents to the application.
Key-value stores read and write one item by its key and spread keys easily, and answer nothing else. Wide-column stores add order within a partition, and need a table for each query. Graph stores make following relationships cheap.
The explorer shows that no option meets both a transaction across records and a write load spread by key. The cost of a question you did not plan for is paid in code, in a scan or in a second copy.