Some workloads outgrew one relational server, and some never needed what it offers. NoSQL is a loose label for databases that store data in a model other than related tables, usually to gain something specific.
It is not a single technology, and the name says nothing about SQL itself: several of these systems have SQL-like query languages. Treat each model below as a tool with a narrow job.
Four ideas explain most of the designs.
Scaling out. A store built to spread data across many machines from the start can add capacity by adding nodes, with no retrofitting of the kind the sharding chapter described.
Flexible records. A document or key-value store does not make every record share one fixed set of columns. MongoDB's data modelling page lists this as a feature: documents in a collection need not have the same fields or data types, and new fields can be added without rewriting existing documents.
Designing for known access patterns. Instead of normalising data and asking any question later, you decide the questions first and store the data in the shape that answers them cheaply. The DynamoDB developer guide puts it as a rule: do not start designing the schema until you know the questions it must answer. The Cassandra documentation says the same in fewer words: data modelling is query-driven.
A narrower promise. A key-value store answers "give me the value for this key" very quickly and promises little else. Narrow promises are easier to keep at large scale, and each of the four models below is a different choice of which promise to narrow.
What is given up is just as specific. Joins are the first loss: Cassandra's documentation says joins are not supported, so every field a query needs must be grouped in one table. Ad hoc questions are the second: a relational schema can answer a question nobody planned for, and a key-based design usually cannot.
The same lookup, two ways
The first script puts three invented users in a Postgres table and, in parallel, in Redis as one value per key. Redis here is version 6.2.14, started on a port of its own on this machine, and the Postgres side is PGlite, PostgreSQL 18.6 running inside Node. Results are printed with the helper from the SQL chapter.
ts
const db = new PGlite()
const redis = new Redis({
host: '127.0.0.1',
port: 56355,
lazyConnect: true,
})
await redis.connect()
await redis.flushdb()
await db.exec(`CREATETABLE users (
user_id int PRIMARY KEY, name text NOT NULL, city text NOT NULL);
INSERT INTO users (user_id, name, city) VALUES (1, 'Asha', 'Pune'), (2,
'Ravi', 'Chennai'), (3, 'Meena', 'Pune');`)
for (const u of [
[1, 'Asha', 'Pune'],
[2, 'Ravi', 'Chennai'],
[3, 'Meena', 'Pune'],
] asconst)
await redis.set(
`user:${u[0]}`,
JSON.stringify({ name: u[1], city: u[2] })
)
ts
console.log('-- one user, by key')
show(
(
await db.query(
'SELECT user_id, name, city FROM users WHERE user_id = $1',
[2]
)
).rows
)
console.log('GET user:2 ->', await redis.get('user:2'))
console.log('-- every user in Pune')
show(
(
await db.query(
`SELECT user_id, name FROM users WHERE city = $1
ORDER BY user_id`,
['Pune']
)
).rows
)
console.log(
'No plain command answers this. KEYS user:* returns',
(await redis.keys('user:*')).length,
'keys and says nothing about city'
)
text
user_id | name | city
--------+------+--------
2 | Ravi | Chennai
(1 row)
GET user:2 -> {"name":"Ravi","city":"Chennai"}
-- every user in Pune
user_id | name
--------+------
1 | Asha
3 | Meena
(2 rows)
No plain command answers this. KEYS user:* returns 3 keys and says
nothing about city
Fetching one user by its key is easy in both systems. The first question that is not a key lookup, every user in Pune, is one line of SQL, and the output lists Asha and Meena. In Redis the data is a set of opaque values under names like user:1. The script asks for the keys that match user:* and gets three names back, with nothing about the cities inside the values, because plain Redis commands do not look inside a value you stored as text. Even for key names KEYS is not a tool for a live system: its documentation gives the cost as O(N) in the number of keys and says to use extreme care with it in production.
Building the index yourself
The key-value answer is to keep your own index: a second structure that maps a city to its user ids. The script builds one with Redis sets and reads it back. Then it moves a user in SQL and checks the set.
ts
console.log('-- to answer it, the application keeps its own index')
for (const [id, city] of [
[1, 'Pune'],
[2, 'Chennai'],
[3, 'Pune'],
] asconst)
await redis.sadd(`city:${city}`, String(id))
console.log(
'SMEMBERS city:Pune ->',
(await redis.smembers('city:Pune')).sort()
)
console.log(
'-- and when a user moves, the application must change both'
)
await db.query('UPDATE users SET city = $1 WHERE user_id = $2', [
'Chennai',
3,
])
console.log(
'SQL took one UPDATE; the set still says',
(await redis.smembers('city:Pune')).sort(),
'until code runs SREM and SADD'
)
text
SMEMBERS city:Pune -> [ '1', '3' ]
-- and when a user moves, the application must change both
SQL took one UPDATE; the set still says [ '1', '3' ] until code runs
SREM and SADD
The Pune set still contains users 1 and 3 after user 3 moved to Chennai, because Redis has no way to know that the set and the stored value belong together. The application has to remove the user from one set and add them to another, in code, every time a user moves, and a crash between the two commands leaves the index wrong. A relational database does this work for you with an index it maintains itself.
That is the whole trade in one example. A key-value design gets a fast, simple, easily spread lookup by key, and the application takes on every other question and every consistency rule. When the access patterns are few, known and stable, that is a good deal. When they keep changing, it is not.
Two changes in one step
Redis can group commands so that other clients never see half of them. The Redis documentation describes MULTI and EXEC: commands sent after MULTI are queued, EXEC runs them in one step and in order, and a request from another client is never served in the middle. If the connection is lost before EXEC, none of the queued commands run. The script moves user 3 from the Pune set to the Chennai set that way. Then it queues a command that is certain to fail between two good ones.
ts
const redis = new Redis({
host: '127.0.0.1',
port: 56355,
lazyConnect: true,
})
await redis.connect()
await redis.flushdb()
const members = async (key: string) =>
(await redis.smembers(key)).sort().join(' ')
await redis.sadd('city:Pune', '1', '3')
await redis.sadd('city:Chennai', '2')
console.log('-- user 3 moves: both set changes in one transaction')
const done = await redis
.multi()
.srem('city:Pune', '3')
.sadd('city:Chennai', '3')
.exec()
console.log('EXEC ->', JSON.stringify(done))
console.log('city:Pune ->', await members('city:Pune'))
console.log('city:Chennai ->', await members('city:Chennai'))
console.log('-- a command that fails inside MULTI undoes nothing')
await redis.set('plain', 'text')
const mixed = await redis
.multi()
.sadd('city:Pune', '4')
.hget('plain', 'x')
.sadd('city:Pune', '5')
.exec()
for (const [err, value] of mixed ?? [])
console.log(err ? `error: ${err.message}` : `ok: ${value}`)
console.log('city:Pune ->', await members('city:Pune'))
await redis.quit()
text
ok: 1
error: WRONGTYPE Operation against a key holding the wrong kind of value
ok: 1
city:Pune -> 145
EXEC returned one result per queued command, and the two set changes took effect together, so a reader of the index never sees user 3 in both cities or in neither. The second run shows the limit. The middle command, HGET on a key that holds a string, failed with WRONGTYPE when EXEC ran, and the commands on either side of it still ran: the set ended with users 1, 4 and 5. The documentation says so directly: when a command fails inside a transaction the others are still processed, and Redis does not support rollback. A Redis transaction is a single isolated step, not an all-or-nothing guarantee against run-time errors, and it covers one server only. The SQL UPDATE that moved the user in the first script is still a separate write in another system, and a crash between that write and EXEC leaves the two stores apart.
Check yourself
Name two things a team gives up when it moves a workload from a relational database to a key-value store.
Joins and ad hoc queries: only the access patterns designed into the keys are cheap.
Rules the database kept, such as an index that updates itself when a row changes.
In the run, why did the Pune set in Redis still list user 3 after the SQL update?
Redis stores the user value and the city set separately and does not know they are related.
The application must update both, and a crash between the two commands leaves them out of step.
According to the DynamoDB and Cassandra documentation, what comes first when designing for these stores?
The queries or access patterns the application needs to answer.
The data model is then shaped to serve those queries.
Part 2 · Key-value stores: Redis strings, hashes, sorted sets and TTLs
What a key-value store is
A key-value store holds values under unique keys. You write a value with a key and read it back with the same key. The store does not interpret the value, or interprets it only in the ways its data types allow. A hash table in your program is a key-value store that lives in one process; a database like Redis offers the same shape across the network, with persistence and many clients.
Redis calls itself a data structure server. The data types page of the Redis documentation lists the basic ones: strings are the most basic type and represent a sequence of bytes; hashes are record types modelled as collections of field-value pairs; sets are unordered collections of unique strings; sorted sets are collections of unique strings that keep their order by an associated score; lists, streams and others follow. A command works on one type, and Redis refuses a command meant for a different type than the one stored under a key.
Because the type is part of the stored value, a single command can do something useful and atomic. Incrementing a counter, adding a member to a set, and raising a score each take one command, with no read-modify-write in the application.
Strings, hashes and sorted sets in a run
The script below covers the types that most applications use first. It counts page visits with a string, keeps a player's profile as a hash, and ranks four players on a sorted-set leaderboard. Each line prints the command and then its result.
INCR visits:home
-> 1
INCRBY visits:home 10
-> 11
GET visits:home
-> "11"
-- a hash is one record
HGET player:asha city
-> "Pune"
HINCRBY player:asha level 1
-> 8
HGETALL player:asha
-> {"name":"Asha","city":"Pune","level":"8"}
INCR and INCRBY return the new value and do the read and the write in one step: two clients incrementing at the same time cannot lose an update. A hash holds several fields under one key, so one HGETALL returns a whole profile. The numbers inside are strings, since Redis stores bytes, and HINCRBY treats a field as a number when you ask it to.
The sorted set keeps its members ordered by score. ZRANGE ... REV WITHSCORES returns members from the highest score, and ZREVRANK returns Ravi's position counting from the top, 2 meaning third place. When two members have equal scores, as Asha and Meena do at 1200, a sort order is still needed: in this run the highest-first listing put Meena before Asha. After ZINCRBY raised Ravi by 300 he moved to first place at 1250, and ZCOUNT counted three players with a score of at least 1000. The Redis documentation lists the cost of these commands: adding a member is O(log N) for each item, and a range of M members costs O(log N + M), so a leaderboard stays cheap as it grows.
Keys that expire
A time to live, or TTL, tells Redis to delete a key by itself after a number of seconds. That suits one-time passwords, sessions and cached results, which are wrong or useless after a while. In the last part of the script a code is stored for two seconds, read back, and read again after 2.2 seconds.
ts
console.log('-- a key that expires')
await redis.set('otp:asha', '482910', 'EX', 2)
say('GET otp:asha', await redis.get('otp:asha'))
say('TTL otp:asha (seconds)', await redis.ttl('otp:asha'))
awaitnew Promise((r) => setTimeout(r, 2200))
say('GET otp:asha after 2.2 s', await redis.get('otp:asha'))
say('TTL otp:asha', await redis.ttl('otp:asha'))
say('TTL visits:home (no expiry set)', await redis.ttl('visits:home'))
console.log('-- a wrong type')
try {
await redis.hget('visits:home', 'x')
} catch (e) {
console.log('ERROR ' + (e as Error).message)
}
await redis.quit()
text
GET otp:asha
-> "482910"
TTL otp:asha (seconds)
-> 2
GET otp:asha after 2.2 s
-> null
TTL otp:asha
-> -2
TTL visits:home (no expiry set)
-> -1
-- a wrong type
ERROR WRONGTYPE Operation against a key holding the wrong kind of value
Right after the write, GET returned the code and TTL reported 2; that figure depends on timing and can read 1 if a second boundary passes between the two commands. After 2.2 seconds the key was gone: GET returned null, and TTL returned -2, the value that means the key does not exist. A key written with no expiry reports -1, as visits:home did. The last statement shows the type rule: asking for a hash field of a key that holds a string fails with the error WRONGTYPE Operation against a key holding the wrong kind of value.
Notice what Redis is good at here and what it is not asked to do. Every command above is a lookup, an update or a range on one key. Questions that cross keys, such as "which players live in Pune", need an index you build, as the last lesson showed. This run used a copy of Redis started with both snapshots and the append-only file turned off, so nothing it holds survives a restart.
Check yourself
Why can two clients call INCR at the same time without losing an update?
INCR reads and writes the counter in a single command inside the server.
The application does no read-modify-write of its own.
In the run, what did GET and TTL return after the key's two seconds had passed?
GET returned null, because the key had been deleted.
TTL returned -2, which means the key does not exist; a key with no expiry returns -1.
What type of Redis data fits a leaderboard, and what is the cost of adding a member?
A sorted set, which keeps unique members ordered by score.
Adding a member costs O(log N), according to the Redis command documentation.
Part 3 · Document stores: embed or reference
What a document store is
A document store keeps records as self-describing documents, usually JSON or a binary form of it, grouped into collections. A document can hold nested objects and arrays, so one document can carry what a relational design would spread over several tables: an order together with its customer details and its line items.
MongoDB's data modelling documentation states the guiding principle plainly: data that is accessed together should be stored together, and the data model should follow the application's access patterns. It describes two ways to model a relationship. Embedding puts the related data inside the document, and the page says this avoids complex joins across collections. Referencing stores an identifier in one document and keeps the related data in another, much as a foreign key does.
The same page lists the flexibility that document stores offer: documents in one collection need not have the same fields, and a model can evolve without a schema migration. For teams that want a fixed structure it also mentions schema validation. Postgres can play this role for one lesson's worth of experiments: its jsonb type stores JSON documents, supports containment queries with the @> operator, and can be indexed with GIN, as the run below shows.
Embed or reference
The choice between the two depends on how the data is read and how it changes. Data that is read together and changes together is a good candidate for embedding. Data that is shared by many documents and changes on its own, such as a product's description, is a candidate for referencing.
Question
Embed
Reference
Is it read with its parent almost every time?
Yes: one read returns everything
No: a second read is needed
Does it change independently of the parent?
Painful: every copy must be updated
Good: one place to change
Is the set unbounded, such as every message a user ever sent?
Dangerous: the document grows without limit
Good: documents stay small
Is it a snapshot at one moment, such as the price when an order was placed?
Right: the copy is the point
Wrong: the history would change
The third row matters in practice. A record in any such store has a maximum size (DynamoDB's is 400 KB per item, according to its developer guide), and a design that keeps adding to one document eventually hits it. The fourth row is a reminder that embedding is not always a compromise: an order line should keep the price the customer paid, even if the catalogue price changes tomorrow.
MongoDB's transactions page adds a related point. An operation on a single document is atomic, and embedding related data in one document reduces the need for multi-document transactions. The page also says that a distributed transaction usually costs more than a single-document write, and that good schema design should minimise the need for them. It states just as plainly that MongoDB supports multi-document ACID transactions, so the document model does not mean giving up transactions; the advice is about their cost.
Orders as documents, with an index
The script below builds an order collection in Postgres as a table of jsonb documents: 20,000 invented orders, each with a customer object and an array of items. Then it runs a containment query, orders from Pune that include item S7, first without an index and then with a GIN index, the index type from the indexes chapter, on a jsonb column.
ts
const db = new PGlite()
await db.exec(`
CREATETABLE order_docs (order_id int PRIMARY KEY, doc jsonb NOT NULL);
INSERT INTO order_docs (order_id, doc)
SELECT i, jsonb_build_object(
'customer', jsonb_build_object('name', 'Customer ' || i,
'city', (ARRAY['Pune','Chennai','Jaipur','Indore'])[1 + i % 4]),
'items', CASE WHEN i % 2 = 0
THEN jsonb_build_array(
jsonb_build_object('sku', 'S' || (1 + i % 50),
'qty', 1 + i % 3, 'price', 20 + i % 50),
jsonb_build_object('sku', 'S' || (1 + (i * 7) % 50),
'qty', 1, 'price', 20 + (i * 7) % 50))
ELSE jsonb_build_array(
jsonb_build_object('sku', 'S' || (1 + i % 50),
'qty', 1 + i % 3, 'price', 20 + i % 50)) END)
FROM generate_series(1, 20000) AS i;
ANALYZE order_docs;`)
ts
console.log('-- one read returns the order with its items')
const first = await db.query<{ doc: unknown }>(
`SELECT doc FROM order_docs WHERE order_id = 4`
)
console.log(JSON.stringify(first.rows[0].doc, null, 1))
console.log('-- orders from Pune that include sku S7, without an index')
const q = `SELECT count(*)::int AS orders FROM order_docs
WHERE doc @> '{"customer": {"city": "Pune"},
"items": [{"sku": "S7"}]}'`
show((await db.query(q)).rows)
await plan(db, q)
await db.exec(
`CREATE INDEX order_docs_gin
ON order_docs USING gin (doc jsonb_path_ops)`
)
console.log('-- the same query with a GIN index')
show((await db.query(q)).rows)
await plan(db, q)
text
{
"items": [
{
"qty": 2,
"sku": "S5",
"price": 24
},
{
"qty": 1,
"sku": "S29",
"price": 48
}
],
"customer": {
"city": "Pune",
"name": "Customer 4"
}
}
-- orders from Pune that include sku S7, without an index
orders
------
400
(1 row)
EXPLAIN SELECT count(*)::int AS orders FROM order_docs WHERE doc @>
'{"customer": {"city": "Pune"}, "items": [{"sku": "S7"}]}'
Aggregate
-> Seq Scan on order_docs
Filter: (doc @> '{"items": [{"sku": "S7"}], "customer": {"city":
"Pune"}}'::jsonb)
text
orders
------
400
(1 row)
EXPLAIN SELECT count(*)::int AS orders FROM order_docs WHERE doc @>
'{"customer": {"city": "Pune"}, "items": [{"sku": "S7"}]}'
Aggregate
-> Bitmap Heap Scan on order_docs
Recheck Cond: (doc @> '{"items": [{"sku": "S7"}], "customer":
{"city": "Pune"}}'::jsonb)
-> Bitmap Index Scan on order_docs_gin
Index Cond: (doc @> '{"items": [{"sku": "S7"}],
"customer": {"city": "Pune"}}'::jsonb)
One read returned the whole order with its customer and items, which is the point of embedding. The query found 400 orders. Without an index the plan is a sequential scan over all 20,000 documents with the containment test applied to each. Adding a GIN index with the jsonb_path_ops operator class changed the plan to a bitmap index scan on the index, followed by a recheck of the matching rows. The row counts are the same, and the planner is free to use the index because the query uses the @> containment operator that the index supports. This is the machinery behind queries on documents in MongoDB as well: the stores differ, the need for an index on the fields you search by does not.
The cost of copies
The last part of the script shows the price of embedding. Suppose item S7 is a product whose price must change in every order that contains it. With the items embedded, every such order is a document that has to be found and rewritten. With a products table that orders refer to, it is one row.
ts
console.log('-- embedded copies: change the price of sku S7')
const touched = await db.query(
`UPDATE order_docs SET doc = jsonb_set(doc, '{items}',
(SELECT jsonb_agg(CASE WHEN e->>'sku' = 'S7'
THEN jsonb_set(e, '{price}', '99') ELSE e END)
FROM jsonb_array_elements(doc->'items') AS e))
WHERE doc @> '{"items": [{"sku": "S7"}]}'`
)
console.log(`UPDATE ${touched.affectedRows}`)
console.log('-- referencing keeps one copy: the same change is one row')
await db.exec(`CREATETABLE products (
sku text PRIMARY KEY, price numeric NOT NULL);
INSERT INTO products (sku, price) VALUES ('S7', 27)`)
const one = await db.query(
`UPDATE products SET price = 99 WHERE sku = 'S7'`
)
console.log(`UPDATE ${one.affectedRows}`)
text
UPDATE 800
-- referencing keeps one copy: the same change is one row
UPDATE 1
The update touched 800 documents, and the single products row changed in one statement. For a price that should change everywhere, that is the argument for referencing. For the price a customer paid, rewriting 800 old orders would be the bug, which is the argument for embedding. Most real designs mix the two, embedding what is a snapshot or is read together, and referencing what is shared.
Check yourself
Give one reason to embed and one to reference.
Embed data that is read together with its parent and is a snapshot, such as the price paid on an order line.
Reference data shared by many documents that changes on its own, such as a product description.
How did the plan for the containment query change when the GIN index was added?
Without it the plan was a sequential scan over all 20,000 documents.
With it the plan was a bitmap index scan on the GIN index, followed by a recheck.
What does MongoDB's documentation say about single-document operations and transactions?
An operation on a single document is atomic, and embedding reduces the need for multi-document transactions.
Distributed transactions usually cost more than single-document writes, so schema design should minimise them.
Part 4 · Wide-column stores: partition keys and clustering keys
One table per query
A wide-column store organises data into tables whose rows are grouped by a partition key and kept in order inside each partition. Cassandra is the best known example, and its data modelling documentation is the source for the terms here. The documentation says that data modelling in Cassandra is query-driven, that queries are best designed to access a single table, and that joins are not supported, so all the fields a query needs must sit in one table.
Two kinds of key make up the primary key. The partition key is hashed to decide which node stores the row: the documentation says the first component of the primary key is hashed to generate the partition key, and that it is used to partition data among the nodes. The clustering keys are the remaining components, and the documentation says they sort data within a partition. A query that names the partition key goes straight to the node or nodes that hold it, and a range over the clustering key reads a contiguous slice of already sorted rows.
The architecture page of the Cassandra documentation adds the distribution side. It says Cassandra achieves horizontal scalability by partitioning all the data in the system using a hash function, and that each keyspace has a replication factor, the number of copies of each partition. DynamoDB follows the same plan under different names, a partition key and a sort key, so the habits learnt on this page carry over to it.
The layout on Postgres
Cassandra was not installed for this course, so this lesson shows the same layout on Postgres, where the primary key (conversation_id, sent_at) plays the same role as a partition key and a clustering key: all the messages of a conversation sit together and in time order. The script builds a messages table of 4,000 invented messages over 40 conversations and asks for the newest three messages of one conversation.
ts
const db = new PGlite()
await db.exec("SET TIME ZONE 'Asia/Kolkata'")
await db.exec(`
CREATETABLE messages_by_conversation (
conversation_id text NOT NULL,
sent_at timestamptz NOT NULL,
sender text NOT NULL,
body text NOT NULL,
PRIMARY KEY (conversation_id, sent_at)
);
INSERT INTO messages_by_conversation (conversation_id, sent_at, sender,
body)
SELECT'c' || (1 + i % 40),
TIMESTAMPTZ '2026-06-01 09:00+05:30' + i * INTERVAL '1 minute',
(ARRAY['asha','ravi','meena'])[1 + i % 3], 'message ' || i
FROM generate_series(1, 4000) AS i;
ANALYZE messages_by_conversation;`)
ts
console.log(
'-- the designed query: newest 3 messages in one conversation'
)
const newest = `SELECT sent_at::text AS sent, sender
FROM messages_by_conversation WHERE conversation_id = 'c7'
ORDER BY sent_at DESC LIMIT 3`
show((await db.query(newest)).rows)
await plan(db, newest)
console.log(
'-- a query it was not designed for: everything one person sent'
)
const bySender = `SELECT count(*)::int AS sent
FROM messages_by_conversation WHERE sender = 'asha'`
show((await db.query(bySender)).rows)
await plan(db, bySender)
text
sent | sender
--------------------------+-------
2026-06-0403:06:00+05:30 | asha
2026-06-0402:26:00+05:30 | meena
2026-06-0401:46:00+05:30 | ravi
(3 rows)
EXPLAIN SELECT sent_at::text AS sent, sender FROM
messages_by_conversation WHERE conversation_id = 'c7' ORDER BY
sent_at DESC LIMIT 3
Limit
-> Index Scan Backward using messages_by_conversation_pkey on
messages_by_conversation
Index Cond: (conversation_id = 'c7'::text)
-- a query it was not designed for: everything one person sent
sent
----
1333
(1 row)
EXPLAIN SELECT count(*)::int AS sent FROM messages_by_conversation WHERE
sender = 'asha'
Aggregate
-> Seq Scan on messages_by_conversation
Filter: (sender = 'asha'::text)
The designed query is an index scan backwards over the primary key, with no sort step: the rows are already stored in the right order, so the newest three are the last three of the conversation's range. The second query, everything one person sent, has no help from the key. The plan is a sequential scan over the whole table and the answer is 1,333 messages. In a wide-column store the same situation is worse, because the data is spread across nodes by conversation and nothing indicates which nodes hold a given sender.
The answer is another table
The wide-column answer is a second table, keyed by sender, that holds the same messages. The application writes each message twice, once to each table. This is called denormalisation, and the Cassandra documentation presents it as the normal way to work: duplicating data to serve each query.
ts
console.log('-- the wide-column answer: a second table, written too')
await db.exec(`
CREATETABLE messages_by_sender (
sender text NOT NULL, sent_at timestamptz NOT NULL,
conversation_id text NOT NULL, body text NOT NULL,
PRIMARY KEY (sender, sent_at));
INSERT INTO messages_by_sender (sender, sent_at, conversation_id, body)
SELECT sender, sent_at, conversation_id, body
FROM messages_by_conversation;`)
const q2 = `SELECT conversation_id FROM messages_by_sender
WHERE sender = 'asha'
AND sent_at >= TIMESTAMPTZ '2026-06-02 00:00+05:30'
ORDER BY sent_at LIMIT 2`
await plan(db, q2)
console.log(
'-- which of three partitions does each conversation id land on?'
)
show(
['c1', 'c2', 'c3', 'c4', 'c5', 'c6'].map((c) => ({
partition_key: c,
partition: shardOf(c, 3),
}))
)
await db.close()
text
EXPLAIN SELECT conversation_id FROM messages_by_sender WHERE sender =
'asha' AND sent_at >= TIMESTAMPTZ '2026-06-02 00:00+05:30' ORDER BY
sent_at LIMIT 2
Limit
-> Index Scan using messages_by_sender_pkey on messages_by_sender
Index Cond: ((sender = 'asha'::text) AND (sent_at >= '2026-06-0200:00:00+05:30'::timestamp with time zone))
-- which of three partitions does each conversation id land on?
partition_key | partition
--------------+----------
c1 | 2
c2 | 2
c3 | 1
c4 | 2
c5 | 1
c6 | 1
(6 rows)
The query by sender now uses messages_by_sender_pkey as an index scan, with the sender as the partition and time as the clustering order. The last output shows how six conversation ids would spread over three partitions with the same hash used in the sharding chapter: c3, c5 and c6 land on partition 1 and c1, c2 and c4 on partition 2, so partition 0 has none of these six. A larger sample would fill it, but the point is that the key alone decides where a row lives.
Animated sceneA partition key picks one partition0:19
Conversation c3 hashes to partition 1, so only that partition is asked
Read it as steps
From the run: conversation c3 hashes to partition 1, c1 to partition 2, c5 to partition 1.
The scene replays that placement. A request for conversation c3 hashes to partition 1 and a request for c1 hashes to partition 2, each request touching exactly one partition. Nothing in the model lets a request ask all partitions a question cheaply, which is the price of this design.
Check yourself
In a Cassandra-style primary key, what do the partition key and the clustering keys do?
The partition key is hashed to choose where the row is stored.
The clustering keys sort the rows inside a partition.
Why did the run's query by sender need a second table?
The first table's key is the conversation, so a sender's messages are spread across every partition.
A second table keyed by sender, written alongside the first, makes that query a single-partition read.
What does the data modelling documentation say about joins and duplicated data?
Joins are not supported, so all fields a query needs are grouped in one table.
Duplicating data across tables, called denormalisation, is how each query gets its own table.
Part 5 · Graph stores: nodes, edges and traversals
Nodes and relationships
A graph database stores data as nodes, relationships and properties. The Neo4j documentation defines nodes as the entities, which can carry labels for their roles, and relationships as named, directed connections that always have a start node, an end node and exactly one type. Both can hold properties, which are key-value pairs.
The questions a graph database is built for are about how things connect: who is a friend of a friend, which route links two places, which accounts are linked to a flagged account. The same documentation says graph databases do not use joins, and that relationships are stored natively alongside the nodes, which it presents as what makes traversals through large graphs efficient. This course did not run a graph database, so it makes no measurement of that claim.
A graph is stored in tables as two relations: a table of nodes and a table of edges, where each edge row names its two ends. A directed edge such as "follows" has an order, so an edge from Asha to Ravi is not an edge from Ravi to Asha. The primary key on the pair of columns makes lookups by the first column fast, which is the direction a traversal walks. Walking the other way, who follows Asha, would need its own index on the second column, in the same way that a composite index serves only a prefix of its columns.
Friends of friends in SQL
The recursive query from the sequencing chapter walks edges, which makes friends-of-friends a question Postgres can answer. The script below creates eight invented people and nine follow edges, then asks for people exactly two hops from Asha who she does not already follow.
ts
const db = new PGlite()
await db.exec(`
CREATETABLE people (person text PRIMARY KEY);
CREATETABLE follows (person text NOT NULL REFERENCES people,
friend text NOT NULL REFERENCES people, PRIMARY KEY (person, friend));
INSERT INTO people (person)
VALUES ('asha'),('ravi'),('meena'),('kiran'),('divya'),
('farhan'),('latha'),('omkar');
INSERT INTO follows (person, friend) VALUES
('asha','ravi'),('asha','meena'),('ravi','kiran'),
('meena','kiran'),('meena','divya'),('kiran','farhan'),
('divya','latha'),('latha','asha'),('farhan','omkar');`)
ts
console.log('-- friends of friends of asha (two hops, not yet friends)')
show(
(
await db.query(
`
WITH RECURSIVE reach (person, hops, path) AS (
SELECT friend, 1, ARRAY[person, friend] FROM follows WHERE person = $1
UNION ALL
SELECT f.friend, r.hops + 1, r.path || f.friend
FROM reach r JOIN follows f ON f.person = r.person
WHERE r.hops < 2 AND NOT f.friend = ANY (r.path)
)
SELECT DISTINCT person FROM reach WHERE hops = 2
AND person NOT IN (SELECT friend FROM follows WHERE person = $1)
ORDER BY person`,
['asha']
)
).rows
)
text
person
------
divya
kiran
(2 rows)
Asha follows Ravi and Meena. Ravi follows Kiran, and Meena follows Kiran and Divya, so the two-hop people are Divya and Kiran. The recursive term extends each path by one follower step, keeps an array of the path so far, and refuses to step onto a person already in the path, which stops a cycle from running forever. The outer query keeps the rows at exactly two hops and removes anyone Asha already follows.
Reachability and cycles
The same query shape answers how far a person is from everyone else. The next part reports the shortest hop count to each reachable person within four hops, and then runs a version with no path check on the same graph, which contains a cycle from Asha through Meena, Divya and Latha back to Asha.
ts
console.log(
'-- everyone reachable within four hops, with the number of hops'
)
show(
(
await db.query(
`
WITH RECURSIVE reach (person, hops, path) AS (
SELECT friend, 1, ARRAY[person, friend] FROM follows WHERE person = $1
UNION ALL
SELECT f.friend, r.hops + 1, r.path || f.friend
FROM reach r JOIN follows f ON f.person = r.person
WHERE r.hops < 4 AND NOT f.friend = ANY (r.path)
)
SELECT person, min(hops) AS hops FROM reach GROUP BY person
ORDER BY hops, person`,
['asha']
)
).rows
)
ts
console.log(
'-- no path check, with a cycle: only the hop limit stops it'
)
show(
(
await db.query(
`
WITH RECURSIVE reach (person, hops) AS (
SELECT friend, 1FROM follows WHERE person = $1
UNION ALL
SELECT f.friend, r.hops + 1FROM reach r JOIN follows f
ON f.person = r.person WHERE r.hops < 6
)
SELECT count(*)::int AS rows_produced FROM reach`,
['asha']
)
).rows
)
await db.close()
text
person | hops
-------+-----
meena | 1
ravi | 1
divya | 2
kiran | 2
farhan | 3
latha | 3
omkar | 4
(7 rows)
-- no path check, with a cycle: only the hop limit stops it
rows_produced
-------------
16
(1 row)
Omkar is four hops away, through Meena, Kiran and Farhan. Without the path check the query still stopped, but only because of the hop limit of six: the cycle made it produce 16 rows instead of walking each person once. A recursive query with no limit and a cycle would never end, so a hop limit or a path check is part of every such query.
How a walk grows with the hops
The graph above had eight people. The next script builds a larger one: 2,000 people, each following up to six others chosen by a hash, about 12,000 edges. It runs the same recursive walk from person 1 with a hop limit from 1 to 6 and no path check, and counts two things: the paths the walk produced, and the distinct people those paths ended on. A last query uses UNION in place of UNION ALL. The PostgreSQL documentation says that UNION discards a row that duplicates any earlier result row, so the walk ends by itself once it stops finding new people.
ts
const db = new PGlite()
await db.exec(`
CREATETABLE follows (person int NOT NULL, friend int NOT NULL,
PRIMARY KEY (person, friend));
INSERT INTO follows (person, friend)
SELECT p, 1 + ('x' || substr(md5(p || '-' || k), 1, 7))::bit(28)::int
% 2000FROM generate_series(1, 2000) AS p, generate_series(1, 6) AS k
ON CONFLICT DO NOTHING;
DELETEFROM follows WHERE person = friend;
ANALYZE follows;`)
show(
(
await db.query(
`SELECT count(*)::int AS people_with_follows,
sum(n)::int AS edges, max(n)::int AS max_per_person
FROM (SELECT person, count(*) AS n FROM follows
GROUP BY person) t`
)
).rows
)
ts
const out: Record<string, unknown>[] = []
for (const hops of [1, 2, 3, 4, 5, 6]) {
const r = await db.query<{ paths: number; people: number }>(
`WITH RECURSIVE walk (person, hops) AS (
SELECT friend, 1FROM follows WHERE person = 1
UNION ALL
SELECT f.friend, w.hops + 1FROM walk w JOIN follows f ON f.person = w.person
WHERE w.hops < $1)
SELECT count(*)::int AS paths,
count(DISTINCT person)::int AS people FROM walk`,
[hops]
)
out.push({ hops, ...r.rows[0] })
}
show(out)
ts
const all = await db.query(
`WITH RECURSIVE walk (person) AS (
SELECT friend FROM follows WHERE person = 1
UNION
SELECT f.friend FROM walk w JOIN follows f ON f.person = w.person)
SELECT count(*)::int AS reachable FROM walk`
)
show(all.rows)
await db.close()
Each extra hop multiplies the paths by about six: 6, 42, 258, 1,551, 9,296 and 55,699. The distinct people grow more slowly and then flatten: 6, 41, 234, 1,000, 1,895 and 1,992 of the 2,000, because most people are reached by many routes. A walk that keeps every route pays for all of them, which is why six hops produced 55,699 rows to find 1,992 people. The UNION form found 1,994 people reachable in all by adding each person once. The Neo4j page says a graph database stores relationships alongside the nodes and does not use joins. This course ran no graph database and measured no comparison, but the run shows where the cost of the relational version lives: in the number of routes. A question that needs distinct people should say so, with UNION or a visited check. A question that needs the routes themselves, such as every path between two accounts, gets expensive quickly, because the number of routes is what grows.
Where a graph database does better
Postgres handled this small case, and many real graph questions of this shape fit in a relational database. The cases where a dedicated graph store is worth considering are the ones the Neo4j documentation describes: very large graphs, traversals of many hops in both depth and breadth, and a model where relationships carry as much meaning as entities, and where changing the shape of the graph is common. In that setting every extra hop of the relational version is another join step inside the recursion, and the property graph model and its query language are written for exactly this walk. If the questions are one or two hops deep on data that is mostly ordinary tables, extra infrastructure is hard to justify. Whichever way you lean, write down the three or four traversal questions the product needs, with the number of hops each one goes, before comparing tools: the depth of the questions is what decides whether a relational join per hop stays affordable.
Check yourself
A six-hop recursive walk with UNION ALL produced 55,699 rows but reached only 1,992 people. Why, and what changes if you only need the people?
Most people are reached by many different routes, and UNION ALL keeps a row for every route.
UNION discards rows that duplicate an earlier result, so each person is added once and the walk ends by itself.
Why did the recursive query keep the path array, and what happened without it?
The path array refuses to revisit a person already on the path, which stops cycles.
Without it, the cycle made the query produce 16 rows and only the hop limit stopped it.
When is a relational database enough for a graph-shaped question?
When the traversals are short, such as two hops, over data that is mostly ordinary tables.
A recursive query with a hop limit or path check can answer them.
Part 6 · Consistency trade-offs: CAP, PACELC and tunable consistency
CAP stated precisely
When data is copied to several machines, a read can reach a copy that has not seen the latest write. The CAP theorem is the best known statement of what a system can promise about this. Its three properties are usually defined as consistency, meaning every read sees the latest write, availability, meaning every request gets an answer, and partition tolerance, meaning the system keeps working when the network splits nodes into groups that cannot talk to each other.
The slogan "pick two of three" is the version most often repeated, and Eric Brewer wrote a paper called CAP twelve years later that revisits it. He wrote that the two-of-three formulation was always misleading because it tended to oversimplify the tensions among the properties. His points were that partitions are rare, so a system can offer both consistency and availability most of the time; that when a partition does occur, designers still have to choose between consistency and availability; and that all three properties are more continuous than binary. A system should also initiate recovery when communication is restored.
Read this way, CAP is narrow. It is about what a system does during a network partition, not a label that says a database is "CP" or "AP" for all time.
PACELC
Daniel Abadi pointed out that CAP says nothing about the time when there is no partition, which is almost all the time. He wrote that ignoring the consistency and latency trade-off of replicated systems is a major oversight, because it is present at all times during operation, whereas CAP is only relevant in the arguably rare case of a network partition. His formulation, PACELC, reads: if there is a partition (P), how does the system trade off availability and consistency (A and C); else (E), when the system is running normally, how does it trade off latency (L) and consistency (C).
So each system is described by two choices. In his paper the default versions of Dynamo, Cassandra and Riak are PA/EL: during a partition they give up consistency for availability, and in normal operation they give up consistency for lower latency. Fully ACID systems such as VoltDB and Megastore are PC/EC. These are the paper's classifications of the systems as they were then, and the paper adds that systems like Dynamo and Cassandra have user-adjustable settings that move them along the latency and consistency line.
The replication chapter showed the second choice in Postgres: a commit that waits for a standby is slower and gives consistent reads, and a commit that does not wait is faster and risks stale reads.
Tunable consistency with quorums
Systems that replicate each item to N nodes let the caller choose how many replicas must respond to each operation. The Cassandra documentation lists the levels: ONE means a single replica must respond, QUORUM means a majority, n/2 + 1, of the replicas, and ALL means every replica. It states the overlap rule as W + R > RF, where W is the number of replicas that acknowledge a write, R the number that answer a read and RF the replication factor. When the rule holds, every read set contains at least one replica that took the acknowledged write.
The replication chapter ran that rule by enumeration for three replicas and counted the reads that miss a write, 6 of 9 with R = 1 and W = 1, so this page does not repeat it. What it adds is the price side. The script prints, for replication factors 3 and 5, how many replicas each level needs and how many may be down while it still works, and then four common pairs of write level and read level. In the pairs table the last column is the number of replicas that can be down while both the write and the read still succeed. The figures are computed from the documented definitions. They were not run against Cassandra, which was not installed for this course.
ts
const need = (level: string, rf: number) =>
level === 'ONE' ? 1 : level === 'QUORUM' ? Math.floor(rf / 2) + 1 : rf
console.log('RF | level | must answer | can be down')
for (const rf of [3, 5])
for (const level of ['ONE', 'QUORUM', 'ALL'])
console.log(
`${rf} | ${level.padEnd(6)} | ${need(level, rf)} | ` +
`${rf - need(level, rf)}`
)
ts
console.log('-- pairs of (write level, read level)')
console.log('RF | write | read | W+R | W+R > RF | can be down')
for (const rf of [3, 5])
for (const [wl, rl] of [
['ONE', 'ONE'],
['ONE', 'ALL'],
['QUORUM', 'QUORUM'],
['ALL', 'ONE'],
]) {
const w = need(wl, rf),
r = need(rl, rf)
console.log(
`${rf} | ${wl.padEnd(6)} | ${rl.padEnd(6)} | ${w + r} | ` +
`${(w + r > rf ? 'yes' : 'no').padEnd(8)} | ` +
`${rf - Math.max(w, r)}`
)
}
text
RF | level | must answer | can be down
3 | ONE | 1 | 23 | QUORUM | 2 | 13 | ALL | 3 | 05 | ONE | 1 | 45 | QUORUM | 3 | 25 | ALL | 5 | 0
-- pairs of (write level, read level)
RF | write | read | W+R | W+R > RF | can be down
3 | ONE | ONE | 2 | no | 23 | ONE | ALL | 4 | yes | 03 | QUORUM | QUORUM | 4 | yes | 13 | ALL | ONE | 4 | yes | 05 | ONE | ONE | 2 | no | 45 | ONE | ALL | 6 | yes | 05 | QUORUM | QUORUM | 6 | yes | 25 | ALL | ONE | 6 | yes | 0
At RF = 3, QUORUM needs 2 replicas and tolerates one down; at RF = 5 it needs 3 and tolerates two. ALL tolerates none: a single dead replica makes every ALL operation fail, which is the availability that this strength costs. The pairs ONE write with ALL read, and ALL write with ONE read, both satisfy W + R > RF, but they move the cost to opposite sides: the first makes writes cheap and reads fragile, the second the reverse, and neither survives a replica being down. QUORUM for both gives the same overlap and keeps both operations working with 1 of 3 or 2 of 5 replicas down, which is why it is the documentation's own example. ONE with ONE has W + R of 2, below RF at both sizes, so a read can miss the write. As the Abadi paper notes, even an overlapping pair does not give full consistency in the formal CAP sense.
DynamoDB and strongly consistent reads
Managed stores expose the same choice as a flag on a read. The DynamoDB developer guide says that tables and local secondary indexes offer two options, eventually consistent reads, which are the default, and strongly consistent reads. All reads from global secondary indexes and streams are eventually consistent. Setting the ConsistentRead parameter on GetItem, Query or Scan returns a response that reflects all prior successful writes, and the guide says eventually consistent reads cost half as much as strongly consistent ones.
A local test cannot show the difference. The DynamoDB documentation says the downloadable version also performs eventually consistent reads, but that because of the speed of a program on your own computer, most reads appear strongly consistent. This course therefore does not show an eventually consistent read returning an old value from a real store.
The practical rule is the one that runs through this chapter. Pick the weakest consistency that the feature can tolerate, and pay for strength only where a stale answer would be wrong: a balance, a booking, a stock count. A feed of recent messages, a like counter or a search suggestion can usually live with an answer that is a moment old.
Check yourself
What did Brewer say was misleading about "pick two of three" in CAP?
It oversimplifies the tensions: partitions are rare, and consistency and availability are more continuous than binary.
During a partition designers still choose between consistency and availability.
What does the second half of PACELC, "else latency or consistency", add to CAP?
It describes the trade-off in normal running, when there is no partition, which is almost all the time.
Replicated systems pay latency for consistency even when nothing has failed.
With RF = 3, compare ONE for both write and read against QUORUM for both. Which satisfies W + R > RF, and how many replicas can be down for each?
QUORUM with QUORUM: 2 + 2 is 4, above 3, so reads overlap the write, and one replica can be down.
ONE with ONE: 1 + 1 is 2, so a read can miss the write, although two replicas can be down.