The data model decides which questions are cheap. One album page is 1 document read, or 26 row reads across five tables. Renaming its producer is 1 row write, or 12,000 document writes.
Pick a model, then pick a question, and count the records each one touches. Then we build the relational, document and graph models from zero, and the languages that query them.
You need a little Python and what a table and a JSON object are. We build the rest from zero.
Illustrative catalog. The album has 6 tracks and 9 credits; its producer is credited in 12,000 album documents; each listener follows 150 others. Counts come from this lesson's equations; we checked them by running the queries in SQLite.
Chapter 0
Store the same album three ways, and find where each fact lives
You run a music service. An album page shows the album, its artist, six tracks, and who produced and mixed each track. Listeners follow other listeners, and each listener plays tracks every day. Now store all of that.
You have three common shapes. Tables split the data into rows that point at each other by id. A document keeps the whole album as one nested JSON tree. A graph makes every album, track and person a node, and every relationship an edge.
Purple boxes are records on disk. Pick a shape, then pick a fact; its copies light up blue.
Illustrative album, "Night Ferry" by The Lanterns: 6 tracks, Mo Okafor produced all 6 and Ines Varga mixed 3. A script generated and counted the JSON.
Count the producer's name. The tables store it once, in one row of people, and six credit rows point at it. The document stores it six times, once per track. The graph stores it once, on one node with six edges. The track list goes the other way: the document holds it in one place, and the tables spread it over three.
Neither shape is free. Each is a bet on which questions you ask most. This lesson follows Chapter 3 of Designing Data-Intensive Applications, 2nd edition, by Martin Kleppmann and Chris Riccomini (O'Reilly, 2026). The chapter compares relational, document and graph models and their query languages. We explain the ideas in our own words, with our own catalog and numbers. Chapter 2 turned requirements into numbers.
Failure. Symptom: a "simple" feature needs a rewrite of the storage layer. Measure: which questions the product asks most, against which ones the model makes cheap. Cause: the team picked the model by habit. Fix: list the top questions first, then pick the shape.
Chapter 1
Split the album into rows, then watch a join put it back together
In 1970 Edgar Codd proposed the relational model in "A Relational Model of Data for Large Shared Data Banks". The data is a set of tables. A program says which rows it wants, not how to walk to them on disk. The database chooses the path.
Each table has a primary key: a column whose value names one row. A foreign key is a column that holds another table's primary key, so a row can point at a row elsewhere. A join follows those pointers at query time and glues the matching rows together.
sqlCREATE TABLE artists (artist_id INTEGER PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE people (person_id INTEGER PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE albums (album_id INTEGER PRIMARY KEY, title TEXT NOT NULL, year INTEGER,
artist_id INTEGER NOT NULL REFERENCES artists);
CREATE TABLE tracks (track_id INTEGER PRIMARY KEY,
album_id INTEGER NOT NULL REFERENCES albums,
n INTEGER, title TEXT, seconds INTEGER);
CREATE TABLE credits (track_id INTEGER NOT NULL REFERENCES tracks,
person_id INTEGER NOT NULL REFERENCES people,
role TEXT, PRIMARY KEY (track_id, person_id, role));
The credits table holds only keys and a role. It links many tracks to many people, so it is a junction table. With foreign keys on, SQLite rejects a credit for person 99 when no such person exists: FOREIGN KEY constraint failed.
How much work does the album page cost? Call the number of tracks t and the number of credit lines c. The page reads R rows in all.
R equals two, plus t, plus two times c.
Read the album and its artist. Read each of the t tracks. For each of the c credits, read the credit and then the person. Add them up to get R. A document store reads the same page as one document.
Night Ferry: t = 6 and c = 9, so R = 2 + 6 + 18 = 26 rows. A 12-track album with 20 credits needs 54. The join returns 9 result rows, one per credit line.
Five tables of purple rows. Each step, a blue query reads one row; teal result lines collect on the right. Step through, or turn off the index on tracks.album_id.
The plan follows SQLite 3.51's real EXPLAIN QUERY PLAN for this query. Without an index on tracks.album_id it chose "SCAN c": read every credit in the catalog. The 2,000,000-credit catalog is illustrative.
sqlSELECT a.title, ar.name, t.n, t.title, p.name, c.role
FROM albums a
JOIN artists ar ON ar.artist_id = a.artist_id
JOIN tracks t ON t.album_id = a.album_id
JOIN credits c ON c.track_id = t.track_id
JOIN people p ON p.person_id = c.person_id
WHERE a.album_id = 1
ORDER BY t.n;
Failure. Symptom: a list of 50 albums takes 51 round trips to the database. Measure: queries per page in the database log. Cause: an ORM (a library that maps rows to objects) loads each album's tracks lazily, one query each. This is the N+1 query problem. Fix: load the children in one join, or in one batched query.
Chapter 2
Rename a shared fact, and time the window where readers see two names
Mo Okafor changes their professional name to Mo Okafor-Lind. In the tables, one statement changes one row: UPDATE people SET name = 'Mo Okafor-Lind' WHERE person_id = 1. SQLite reports one row changed, and every credit shows the new name at once.
That is normalization: store each fact in one place and point at it by id. The opposite, denormalization, copies the fact into every record that uses it. Copies make reads cheap and renames expensive. The relationship here is many-to-one: many credits, one person.
Suppose the documents copy the name instead. Call the number of documents that hold the old name n, and the rate at which you can rewrite them w. While the rewrite runs, some readers see the old name and some the new. That mixed window lasts T.
T equals n over w.
Count the copies, n. Divide by how many you can rewrite each second, w. That is how long the catalog disagrees with itself, T.
With made-up numbers: Mo is credited in n = 12,000 album documents, and w = 2,000 rewrites a second. T = 12,000 / 2,000 = 6 seconds of mixed names. Normalized, it is one row and no window.
Each cell is 100 album documents. Red cells still carry the old name while blue ones carry the new. Choose the shape, set the rewrite rate, and press Rename.
Illustrative: 12,000 documents. The animation compresses the window to a few seconds; the read-out gives the real T.
Normal forms name the copies to remove. First normal form (1NF): one value per cell, so no "Mo Okafor, Ines Varga" string. Second (2NF): with the key (track_id, person_id, role), a person_name column depends on only part of the key, so it moves to people. Third (3NF): an album_title column in tracks depends on album_id, not on the track, so it stays in albums.
Failure. Symptom: two spellings of one producer, months after a rename. Measure: SELECT DISTINCT person_name ... WHERE person_id = 1 on a copied table returns two rows. Cause: the rewrite stopped halfway, and nothing ties the copies together. Fix: keep the name in one row, or make the rewrite idempotent and rerun it until no old copy remains.
Chapter 3
Read a whole album in one fetch, and find the list that grows past the limit
Your app holds an album as a nested object: a title, a list of tracks, and a list of credits in each track. Turning it into five tables and back is work. People call that gap the object-relational mismatch. A document store keeps the tree as it is.
json{ "_id": 1, "title": "Night Ferry", "year": 2024, "artist": "The Lanterns",
"tracks": [
{ "n": 1, "title": "Harbour", "seconds": 214,
"credits": [ { "name": "Mo Okafor", "role": "producer" } ] },
{ "n": 2, "title": "Low Tide", "seconds": 187,
"credits": [ { "name": "Mo Okafor", "role": "producer" },
{ "name": "Ines Varga", "role": "mixing" } ] }
/* … 4 more tracks */ ] }
One read returns the whole page: this is locality, the data used together stored together. The tree has one-to-many links, album to tracks to credits, and each child belongs to one parent. Documents fit that shape well. They fit many-to-one links badly, as the rename showed.
So each related list asks one question: embed it inside the parent, or reference it by id in its own collection? Embed what is small, bounded and read with the parent. Reference what grows without end. MongoDB caps one document at 16 mebibytes. Call that cap L, the parent's fixed part b, and the size of one list entry s. The list can hold at most nmax entries.
n-max equals L minus b, over s.
Take the limit L. Subtract the fixed part b. Divide the room that is left by the size of one entry, s. That is n-max.
With made-up sizes: n-max = (16,777,216 − 4,096) / 600 = 27,955 entries. A 12-track album uses 0.07% of the limit. A play history that grows by 40 plays a day passes 27,955 on day 699.
The purple bar is the listener document. The line is the 16 MiB limit. Drag the days, then switch to a referenced list.
Illustrative sizes: 4,096 bytes for the listener, 600 bytes per play entry, 40 plays a day. The 16 MiB limit is from MongoDB's documented limits.
Documents have caught up on joins, and tables on trees. MongoDB's $lookup stage does a left outer join to another collection. PostgreSQL's jsonb type stores a JSON tree in one column; Chapter 8 uses it.
Failure. Symptom: writes to one heavy listener start to fail after about two years. Measure: the document's size against the limit, and its growth per day. Cause: an unbounded list embedded in the parent. Fix: move the list to its own collection, one record per play, keyed by listener.
Chapter 4
Add a field to a live catalog, and see which old records a query misses
The product team wants an "explicit lyrics" flag on every track. Old tracks have no flag. Who decides what an old track means?
With schema-on-write, the database checks each record against a declared shape when you write it. Tables work this way. With schema-on-read, the store accepts any shape, and the code that reads the record decides what it means. Document stores often work this way. There is still a schema; it lives in your code.
In PostgreSQL, ALTER TABLE tracks ADD COLUMN explicit boolean NOT NULL DEFAULT false stores the default once in the catalog. The documentation says a non-volatile default needs no table rewrite, so the change is fast even on a large table. Every old row reads as false.
Each cell is one track; the first 700 are old. Blue cells match the query for clean tracks. Pick an approach, then backfill the old records.
Illustrative catalog: 1,000 tracks, 700 written before the flag, 30 of the new ones explicit. MongoDB's equality match on false does not match a missing field; a match on null does. PostgreSQL behaviour checked in PGlite (PostgreSQL 16.4).
Some new fields cannot use one default: the value must be computed per record, from the lyrics. Then you backfill: rewrite old records in small batches so the live system keeps up. Call the records to fix N, the batch size k, and the time per batch, pause included, Δ. The backfill takes T.
T equals N over k, times delta.
Divide the N records into batches of k. Multiply the number of batches by delta, the time each one takes. That is T.
With made-up numbers: N = 200 million, k = 1,000 and delta = 0.05 s. That is 200,000 batches, so T = 10,000 s, about 2.8 hours.
The safe order is expand and contract. Add the new field so it may be empty. Deploy code that writes it and reads it with a fallback. Backfill. Switch reads to the new field. Last, make it required and drop the old one.
Failure. Symptom: after a "migration", a filter for clean tracks returns 270 of 1,000. Measure: count the records where the field is missing, for example with $exists: false. Cause: the backfill skipped old records, and the query treats missing as "not false". Fix: rerun the backfill until that count is zero, and default missing values in the read path meanwhile.
find({explicit: false}) return for them?Chapter 5
Add an index, and watch the same query take a shorter path while the loop does not
You want the titles of album 1's tracks. You can write the steps yourself, or describe the result and let the database find it.
python# imperative: you choose the path, and the path is "read every track" def tracks_of(album_id, tracks): out = [] for t in tracks: if t["album_id"] == album_id: out.append(t["title"]) return out
sql-- declarative: you say which rows; the planner picks the path SELECT title FROM tracks WHERE album_id = 1;
An imperative program fixes the algorithm. A declarative query states the result, and the query planner picks the algorithm. In SQLite, the plan for that query is SCAN tracks. After CREATE INDEX tracks_by_album ON tracks(album_id), the same text plans as SEARCH tracks USING INDEX tracks_by_album (album_id=?). The query did not change. The Python loop still reads every track.
An index here is a B-tree: a tree of fixed-size pages, each holding many sorted keys and pointers to the next level. Call the rows N and the keys per page, the branching factor, b. A search reads one page per level, d pages in all.
d equals the ceiling of log base b of N.
Each page splits the keys b ways. Count how many splits it takes to get from N rows down to one row, and round up. That count is d, the pages one search reads.
With b = 400 keys a page and N = 50 million: log base 400 of 50 million is 2.96, so d = 3 pages. A scan at 100 rows a page reads 500,000 pages. At 2 billion rows and b = 500, d is still 4.
The purple strip is the table. A scan sweeps all of it; an index search drops through d teal pages. Choose the program, add the index, then drag the table size.
Plan strings are SQLite 3.51's real output. Page counts are illustrative: 100 rows a data page, 400 keys an index page, and no pages cached.
Declarative queries also let the engine split work across cores, because the query names no order of steps. MongoDB's aggregation pipeline is declarative too: a list of stages such as $match (filter) and $group (aggregate). MongoDB 5.0 deprecated its older map-reduce, where you wrote the map and reduce functions yourself, in favour of the pipeline.
jsdb.plays.aggregate([ { $match: { at: { $gte: "2026-11-01" } } }, { $group: { _id: "$track_id", plays: { $sum: 1 } } }, { $sort: { plays: -1 } }, { $limit: 3 } ])
Failure. Symptom: one album page takes seconds as the catalog grows. Measure: EXPLAIN QUERY PLAN shows SCAN on a big table. Cause: no index on the column in the WHERE or the join. Fix: add the index; the query text stays the same.
Chapter 6
Model follows as a graph, and count the edges a two-hop question walks
Listeners follow listeners. Ana follows 150 people, each of whom follows 150 more. Tracks have credits, people have labels, labels sign artists. When most of your questions are about links, many-to-many relationships dominate, and the links become the data.
A graph has vertices (nodes: a listener, a track) and edges (a FOLLOWS or a PRODUCED link). In a property graph, each node and edge has a label and key-value properties; Neo4j uses this model. In a triple store, every fact is one (subject, predicate, object) triple, such as :ana :follows :ben; RDF and SPARQL use this model. Either one fits in two relational tables, one for nodes and one for edges.
turtle@prefix : <http://example.org/> .
:ana :name "Ana" . :ana :follows :ben . :ana :follows :caro .
:ben :name "Ben" . :ben :follows :dev . :ben :follows :caro .
:caro :name "Caro" . :caro :follows :eli .
"Who do the people Ana follows follow?" walks two hops. Call each listener's follow count the degree, d, and the number of hops H. The question walks E edges.
E equals the sum over h from 1 to H of d to the h.
At hop 1 you walk d edges. At each next hop, every person found adds d more edges, so multiply by d again. Add the hops up to get E.
With d = 150: one hop is 150 edges. Two hops is 150 + 22,500 = 22,650. Three hops is 3,397,650. In a simulated network of 100,000 listeners, the two-hop walk found 20,092 distinct new people: repeats are common.
Ana is the warm node; each ring is one more hop, drawn as a sample. Drag the degree, then choose how many hops the question walks.
Illustrative degree; the rings draw at most 24 edges per node. The red line marks one million edges, where an interactive query should stop and become a batch job.
Every model walks those 22,650 edges. The tables run 151 index searches on the follows table; a document store fetches 151 listener documents and joins them in your code. Graph databases keep each node's edges with the node, so a hop needs no index search. How much that saves depends on the engine and on caching. The bigger win is the question: it is one pattern, not a loop.
Failure. Symptom: one "people you may know" query pins a database core for minutes. Measure: the hop limit of the query, and the degree of its start node. Cause: an unbounded walk, where three hops from a popular account touch millions of edges. Fix: cap the hops, cap the edges per node, or precompute suggestions in a batch job.
Chapter 7
Write one question three ways, and step the engine until no new fact appears
Take eight listeners and nine follows. The question: whom do Ana's follows follow, that Ana does not follow yet? The answer is Dev and Eli. We checked each language's answer against a real engine where one exists, and against a small Python version where none does.
Cypher, the language of Neo4j, draws the pattern in ASCII: round brackets for nodes, arrows for edges.
cypherMATCH (me:Listener {name: 'Ana'})-[:FOLLOWS]->()-[:FOLLOWS]->(fof:Listener) WHERE fof <> me AND NOT EXISTS { (me)-[:FOLLOWS]->(fof) } RETURN DISTINCT fof.name
SPARQL, the W3C query language for RDF triples, matches triple patterns. A property path such as :follows/:follows means "follows, then follows". rdflib 7.6 returns Dev and Eli for this query.
sparqlPREFIX : <http://example.org/>
SELECT DISTINCT ?name WHERE {
:ana :follows/:follows ?fof .
?fof :name ?name .
FILTER (?fof != :ana)
FILTER NOT EXISTS { :ana :follows ?fof }
}
Datalog states facts and rules. A rule says: the left side is true whenever the right side is. A rule may use itself, which is how it says "reachable through any number of follows".
datalogfollows(ana, ben). follows(ana, caro). follows(ben, dev). % … 9 facts reach(X, Y) :- follows(X, Y). reach(X, Z) :- reach(X, Y), follows(Y, Z). fof(X, Z) :- follows(X, Y), follows(Y, Z), X != Z, not follows(X, Z).
Purple nodes are listeners. Each step lights the edges the engine follows in blue; teal nodes are answers. Pick a language and step it.
The SPARQL and SQL answers come from rdflib 7.6, SQLite and PGlite. The Cypher and Datalog answers come from a short Python matcher and a semi-naive Datalog evaluator; we had no Neo4j server to run.
A Datalog engine applies the rules in rounds and stops when a round adds nothing: a fixed point. Here the 9 follow facts grow to 17, 22, 25 and 26 reach facts, and round 6 adds none. SQL says the same with WITH RECURSIVE, which SQLite and PostgreSQL both ran:
sqlWITH RECURSIVE reach(id, hops) AS ( SELECT followee, 1 FROM follows WHERE follower = 1 UNION SELECT f.followee, r.hops + 1 FROM reach r JOIN follows f ON f.follower = r.id WHERE r.hops < 3 ) SELECT DISTINCT id FROM reach; -- Ben, Caro, Dev, Eli, Fay
Failure. Symptom: a query with -[:FOLLOWS*]-> never returns on the production graph. Measure: the length bound on the path, here none. Cause: an unbounded variable-length path walks the whole reachable graph. Fix: give a range, such as *1..3, and a LIMIT.
Chapter 8
Assign a model to four access patterns, and see which choices break
The music service has four access patterns. Album pages are read 5,000 times a second. A producer is renamed about once a day. "Fans of fans" suggestions run 200 times a second. Plays arrive at 40 per listener a day, and a weekly report counts them.
Each row uses a number from this lesson. They are the 26-row join (Chapter 1), the 6-second mixed window (Chapter 2), the cap on day 699 (Chapter 3) and the 22,650-edge walk (Chapter 6). Start from all relational, then try to beat it.
Each row is one access pattern; the bar is its work on a log scale. Green fits, grey works with extra code, red breaks. Choose a model per row.
Album pages
Producer rename
Fans of fans
Play history
Illustrative workload. Costs are records touched per second, from the chapters' equations; verdicts are this lesson's judgement, not a benchmark.
No single model wins every row. The document wins the album page and breaks on the rename and the play history. The graph states fans-of-fans most directly and is weak at counting all plays. Tables never break; they cost more on the album page.
That is why one PostgreSQL database often serves several shapes. Keep the shared facts in tables, and the album tree in a jsonb column. PostgreSQL's @> operator tests containment, and a GIN index serves it. In PGlite, WHERE extra @> '{"mood": "calm"}' planned as a Bitmap Index Scan on the GIN index. Running several databases is called polyglot persistence; each extra one is another system to run.
Failure. Symptom: a team adds a graph database, and now two stores disagree about who follows whom. Measure: follow counts per listener in each store. Cause: two systems of record for one fact. Fix: keep one system of record and derive the other from its change log; Chapter 12 covers that.
Chapter 9
Keep the numbers, the checklist and the code for your next schema
Tables store each fact once and rebuild trees with joins. Documents keep trees together and copy shared facts. Graphs make links first-class and pay per hop. Schema-on-write checks shapes at the door; schema-on-read checks them in every reader. Declarative queries let the planner use the indexes you add. Graph languages turn a loop of joins into one pattern.
| Idea | Rule | This lesson's number |
|---|---|---|
| Join cost of a tree | R = 2 + t + 2c | 6 tracks, 9 credits: 26 rows; as a document, 1 read |
| Rename window | T = n / w | 12,000 copies at 2,000/s: 6 s; normalized: 1 row |
| Embedded list cap | nmax = (L − b) / s | 16 MiB, 600-byte entries: 27,955; day 699 at 40 a day |
| Backfill time | T = (N / k) · Δ | 200 M rows, 1,000 a batch, 0.05 s: 2.8 h |
| Index depth | d = ⌈logb N⌉ | 50 M rows, 400 keys a page: 3 pages; scan: 500,000 |
| Graph walk | E = Σ dh | d 150: 22,650 edges at 2 hops, 3,397,650 at 3 |
$exists: false.pythonimport math, sqlite3 def join_rows(t, c): return 2 + t + 2 * c def mixed_window(n, w): return n / w def list_cap(L, b, s): return (L - b) // s def backfill(N, k, dt): return N / k * dt def depth(N, b): return math.ceil(math.log(N) / math.log(b)) def edges(d, H): return sum(d ** h for h in range(1, H + 1)) print(join_rows(6, 9), mixed_window(12_000, 2_000)) # 26 6.0 print(list_cap(16 * 2**20, 4096, 600)) # 27955 print(backfill(200e6, 1000, 0.05) / 3600) # 2.78 hours print(depth(50e6, 400), edges(150, 2)) # 3 22650 db = sqlite3.connect(":memory:") db.executescript(""" CREATE TABLE follows (follower INT, followee INT, PRIMARY KEY (follower, followee)); INSERT INTO follows VALUES (1,2),(1,3),(2,4),(2,3),(3,5),(4,6),(5,6),(6,7),(7,8);""") fof = db.execute(""" SELECT DISTINCT f2.followee FROM follows f1 JOIN follows f2 ON f2.follower = f1.followee WHERE f1.follower = 1 AND f2.followee <> 1 AND f2.followee NOT IN (SELECT followee FROM follows WHERE follower = 1) ORDER BY 1""").fetchall() print(fof) # [(4,), (5,)]: Dev and Eli
Now press Present or Teach and explain four things from memory. Why is a rename cheap in tables? Why can an embedded list break? Why does an index help SQL but not a loop? Why does a graph walk grow as d to the H? Then go back to the hero and find the one question each model wins.