A team that picks a database by fashion usually pays for it later. The choice is easier when you answer a short list of questions about the workload first, and let the answers point to a model.
Six questions do most of the work.
What are the access patterns? List the reads and writes, with how often each runs. The DynamoDB developer guide says that in a relational database data can be queried flexibly, while in DynamoDB it can be queried efficiently in a limited number of ways, and that queries outside those ways are expensive and slow.
How consistent must reads be? A balance or a seat booking must never show a stale value. A feed of recent messages can usually show a value that is a moment old.
How much is written, and how much is read? Write volume decides whether one server's disk and log are enough. Read volume can often be served by copies.
How flexible must queries be? If analysts or new features keep asking questions nobody planned, a model that answers only designed questions will be expensive to live with.
What shape is the data? Rows with fixed columns, nested documents, time-ordered events, and densely connected entities lean in different directions.
Who runs it, and what do they know? A database the team cannot operate at three in the morning is a risk, however well it fits on paper.
A decision table
The table below does not name a winner. It states which way each answer leans, using what the earlier chapters showed.
If the workload has...
It leans toward
Because
Many different questions, joins, reports
Relational
SQL answers questions that were not planned, and the planner chooses a route to the data
Strict rules between records, such as money
Relational
Constraints, transactions and isolation levels are built in and were shown in earlier chapters
One known access pattern at very high volume
Key-value or wide-column
Keys let the data be spread so each request touches one partition
Records that vary in shape and are read whole
Document store or jsonb
Data accessed together is stored together, as MongoDB's modelling page puts it
Cached or short-lived values
Key-value with a time to live
A lookup by key, and expiry done by the store
Many-hop questions over connections
Graph, or a recursive query for short hops
Relationships are first-class, as the graph lesson described
Text search
Postgres full-text search first, a search engine when it is outgrown
The next lesson measures how far Postgres goes
Two rows deserve emphasis. The first is that relational is not the default out of habit: it is the default because a surprising number of workloads have changing questions. The second is that "very high volume" is a number, not a feeling, and the number is cheap to find out.
One sizing query
The easiest way to test whether a workload needs a scale-out store is to size it. The script below creates 1 lakh invented orders in PostgreSQL 18.6 through PGlite, with a primary key index, and asks how big the table and its index are, per row and extrapolated to 10 crore rows. Results are printed with the helper from the SQL chapter.
ts
const db = new PGlite()
await db.exec(`
CREATETABLE orders (order_id bigint PRIMARY KEY,
customer_id int NOT NULL, placed_on date NOT NULL, status text
NOT NULL, total numeric(10,2) NOT NULL);
INSERT INTO orders (order_id, customer_id, placed_on, status, total)
SELECT i, 1 + (i * 7919) % 20000, DATE '2026-01-01' + (i % 300),
(ARRAY['placed','delivered','cancelled'])[1 + i % 3],
100 + (i * 37) % 900FROM generate_series(1, 100000) AS i;
ANALYZE orders;`)
show(
(
await db.query(`
SELECT count(*)::int AS rows,
pg_size_pretty(pg_table_size('orders')) AS table_size,
pg_size_pretty(pg_indexes_size('orders')) AS index_size,
(pg_total_relation_size('orders') / count(*))::int
AS bytes_per_row
FROM orders`)
).rows
)
ts
show(
(
await db.query(`
SELECT pg_size_pretty(
(pg_total_relation_size('orders') / count(*)) * 100000000)
AS size_at_10_crore_rows
FROM orders`)
).rows
)
await db.close()
The 1 lakh rows took 5,920 kB of table and 2,208 kB of primary key index, which is 83 bytes a row for both together. Scaled linearly to 10 crore rows, that is about 7,915 MB, a little under 8 GB. The sharding chapter quoted the PostgreSQL documentation's rule of thumb that a table starts to benefit from partitioning when it is larger than the physical memory of the server. Compare a number like this with the memory of the server you actually run before reaching for partitioning, or for a second store.
Treat the extrapolation with care. It assumes row size stays the same and indexes stay the same, and a real table with text columns and more indexes will be bigger. But the habit is the useful part. Before reaching for a second database for volume, put a number on the data: rows, bytes per row, growth per month. If the result is a few gigabytes, the problem is not size.
Check yourself
Name three questions that decide which database fits a workload.
Access patterns, consistency needs and how flexible the queries must be.
Also write and read volume, data shape, and who will operate it.
According to the DynamoDB developer guide, how do relational and NoSQL stores differ in how data is queried?
Relational data can be queried flexibly, but queries can be expensive at high traffic.
NoSQL data can be queried efficiently in a limited number of ways, and other queries are expensive and slow.
What did the sizing query show, and what are its limits?
83 bytes per row for table plus index, so about 7,915 MB at 10 crore rows.
It assumes rows and indexes stay the same size, so real tables with more columns and indexes will be larger.
Part 2 · How far Postgres alone goes
One store before two
Every extra database adds a system to deploy, secure, back up, upgrade and learn, and a copy of the data that can fall out of step with the first. So the first question after "do we need NoSQL" is whether the database you already have can do the job. Postgres goes further than many teams expect, and the earlier chapters of this course showed several of the reasons.
Need
What Postgres offers
Shown in
Documents with flexible fields
jsonb columns with containment queries and GIN indexes
The NoSQL chapter
Time-ordered data that ages out
Declarative partitioning with cheap drops of old partitions
The sharding chapter
More read capacity
Streaming standbys as read replicas
The replication chapter
Keys and ordering like a wide-column store
A composite primary key and an index range scan
The NoSQL chapter
Short graph traversals
Recursive queries
The NoSQL chapter
Searching text
Full-text search with a GIN index
This lesson
That is a long list for one engine, and each item has a limit. jsonb does not give a document store's distribution across machines. Partitions share one server. Replicas lag. The point is to know where the limits are before adding a second store, not to stay on one engine whatever happens.
Full-text search in two steps
The PostgreSQL documentation defines full text search as the capability to identify natural-language documents that satisfy a query and optionally sort them by relevance. A document is the unit of searching, usually a text column or several columns joined together. To search, each document is reduced to a tsvector, a form in which words are normalised into lexemes: the documentation says normalisation folds upper case to lower case and often removes suffixes, so different forms of a word become alike. A query becomes a tsquery, and the match operator @@ returns true when a document matches it.
The script below loads six invented sweets, shows what the parser stores for one description, and ranks the matches for a search.
ts
const db = new PGlite()
await db.exec(`
CREATETABLE sweets (sweet_id int PRIMARY KEY, name text NOT NULL,
description text NOT NULL);
INSERT INTO sweets (sweet_id, name, description) VALUES
(1, 'Ghee laddu',
'Round laddu made with roasted gram flour, ghee and cardamom'),
(2, 'Motichoor laddu',
'Tiny fried pearls of gram flour pressed into a laddu, in syrup'),
(3, 'Kaju katli',
'Thin diamonds of cashew paste and sugar, with edible silver'),
(4, 'Rasgulla', 'Soft cheese balls cooked in light sugar syrup'),
(5, 'Mysore pak',
'Gram flour, ghee and sugar cooked into a porous block'),
(6, 'Jalebi',
'Fried spirals of batter dipped in saffron sugar syrup');`)
console.log('-- what the parser stores for one description')
show(
(
await db.query(
`SELECT unnest(string_to_array(
to_tsvector('english', description)::text, ' ')) AS lexeme
FROM sweets WHERE sweet_id = 1`
)
).rows
)
ts
console.log('-- a search, ranked')
show(
(
await db.query(
`
SELECT name, round(ts_rank(to_tsvector('english',
name || ' ' || description), q)::numeric, 4) AS rank
FROM sweets, websearch_to_tsquery('english', $1) AS q
WHERE to_tsvector('english', name || ' ' || description) @@ q
ORDER BY rank DESC, name`,
['laddu or ghee']
)
).rows
)
console.log(
'-- stemming: frying finds fried, a spelling variant finds nothing'
)
for (const term of ['frying', 'laddoo']) {
const r = await db.query(
`SELECT count(*)::int AS hits FROM sweets
WHERE to_tsvector('english',
description) @@ plainto_tsquery('english', $1)`,
[term]
)
console.log(`${term}: ${r.rows[0].hits} hits`)
}
The parser turned the description into eight lexemes, each with the position of the word: roast stands for roasted, made stays as it is, and the order of the words is kept as positions. The search laddu or ghee used websearch_to_tsquery, a function that reads a query the way a search box would, and ts_rank scored the three matching rows: Ghee laddu first at 0.0760, which matches both words, then Motichoor laddu and Mysore pak, which match one word each. The two small checks at the end show the limits. Searching for "frying" found two descriptions that say "fried", because both normalise to the same lexeme, and a different spelling, "laddoo", found nothing, because full-text search does not know that it means laddu. Spelling tolerance needs a different tool.
An index for text search
Without an index a text search reads every row. The documentation says GIN indexes are the preferred type for text search, and describes why: a GIN index is an inverted index with an entry for each word and a compressed list of matching locations, so a multi-word search can find the first match and use the index to remove rows that lack the other words. The index needs a column of type tsvector, which the second part of the script stores as a generated column.
ts
console.log('-- 30,000 rows, with and without a GIN index')
await db.exec(`
CREATETABLE catalogue (item_id int PRIMARY KEY,
description text NOT NULL);
INSERT INTO catalogue (item_id, description)
SELECT i, 'sweet number ' || i || ' '
|| (ARRAY['ghee','cardamom','saffron','cashew','jaggery',
'coconut'])[1 + i % 6] || ' '
|| (ARRAY['laddu','burfi','halwa','peda','jalebi'])
[1 + (i * 7) % 5]
FROM generate_series(1, 30000) AS i;
ALTER TABLE catalogue ADD COLUMN doc tsvector GENERATED ALWAYS
AS (to_tsvector('english', description)) STORED;
ANALYZE catalogue;`)
const q = `SELECT count(*)::int AS hits FROM catalogue
WHERE doc @@ to_tsquery('english', 'saffron & halwa')`
show((await db.query(q)).rows)
await plan(db, q)
await db.exec(
`CREATE INDEX catalogue_doc_gin ON catalogue USING gin (doc)`
)
await plan(db, q)
show((await db.query(q)).rows)
await db.close()
text
hits
----
1000
(1 row)
EXPLAIN SELECT count(*)::int AS hits FROM catalogue WHERE doc @@
to_tsquery('english', 'saffron & halwa')
Aggregate
-> Seq Scan on catalogue
Filter: (doc @@ '''saffron'' & ''halwa'''::tsquery)
EXPLAIN SELECT count(*)::int AS hits FROM catalogue WHERE doc @@
to_tsquery('english', 'saffron & halwa')
Aggregate
-> Bitmap Heap Scan on catalogue
Recheck Cond: (doc @@ '''saffron'' & ''halwa'''::tsquery)
-> Bitmap Index Scan on catalogue_doc_gin
Index Cond: (doc @@ '''saffron'' & ''halwa'''::tsquery)
hits
----
1000
(1 row)
The query for rows that mention both saffron and halwa returned 1,000 of 30,000 rows. The first plan is a sequential scan with a filter on every row. After the GIN index was created the plan became a bitmap heap scan driven by a bitmap index scan on catalogue_doc_gin, and the count did not change. This run says what the plan became, not how much faster it is: the data is small and PGlite timings are not representative.
When Postgres is no longer enough
The limits of in-database search are the reason search engines exist. Ranking beyond ts_rank, typo tolerance, faceted counts over huge catalogues and per-language analysis are the usual reasons to add one. The same logic applies to every row of the decision table: you add a second store when you can name a requirement the first cannot meet, and you can say how the two will be kept in step.
That second part is the subject of the last lesson of this chapter, and it is the part teams underestimate. Adding a search index does not just add a server. It adds a pipeline from the source of truth to the index, a way to rebuild the index, and a new way for data to be wrong.
Check yourself
What does the tsvector preprocessing do to a description, as the run showed?
It reduces words to normalised lexemes with positions, so roasted becomes roast.
Searching for one form of a word matches other forms that normalise the same way.
Which did the plan use after the GIN index was added, and did the answer change?
A bitmap index scan on the GIN index, followed by a bitmap heap scan.
The count stayed 1,000, only the way it was found changed.
Give two reasons a team might add a search engine despite Postgres full-text search.
Typo tolerance and ranking beyond ts_rank.
Faceted counts and per-language analysis over very large catalogues.
Part 3 · A worked choice: a payments ledger
Requirements first
A wallet app lets customers hold balances and send money to each other. List what must be true. A transfer must take money from one account and add the same amount to another, or do neither. No account may go below zero. Every movement must leave a record that can be audited later, and the records must add up.
Read against the table of the first lesson, almost every row points the same way. The access patterns include questions that change, such as a customer's statement for any date range and an auditor's totals. The consistency need is strict, because a stale or half-applied balance is a bug. Volume matters, but correctness comes first. That points to a relational database with transactions, and the earlier chapters on transactions, isolation and locking give the tools.
The design
The model is double-entry bookkeeping: every transaction is a set of entries that sum to zero, one negative and one positive for a transfer. An accounts table holds the current balance with a check that it never goes below zero. An entries table holds one row per movement. A deferred constraint trigger checks at commit that the entries of each transaction add up.
ts
const db = new PGlite()
const err = (e: unknown) => {
const x = e as { code?: string; message: string }
return`ERROR ${x.code} ${x.message}`
}
await db.exec(`
CREATETABLE accounts (account_id int PRIMARY KEY, holder text NOT NULL,
balance numeric(12,2) NOT NULL CHECK (balance >= 0));
CREATETABLE entries (
entry_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
txn_id text NOT NULL,
account_id int NOT NULL REFERENCES accounts,
amount numeric(12,2) NOT NULL CHECK (amount <> 0)
);
CREATE FUNCTION check_txn_balanced() RETURNS trigger LANGUAGE plpgsql
AS $$
BEGIN
IF (SELECT sum(amount) FROM entries
WHERE txn_id = NEW.txn_id) <> 0 THEN
RAISE EXCEPTION 'transaction % does not balance', NEW.txn_id
USING ERRCODE = '23514';
END IF;
RETURN NULL;
END $$;
CREATE CONSTRAINT TRIGGER entries_balanced AFTER INSERT ON entries
DEFERRABLE INITIALLY DEFERRED FOR EACH ROW
EXECUTE FUNCTION check_txn_balanced();
INSERT INTO accounts (account_id, holder, balance) VALUES (1, 'Asha',
5000), (2, 'Ravi', 1200);`)
The trigger is INITIALLY DEFERRED, so it runs at commit, after all the rows of the transaction are in place. If it ran after each row, the first entry of every transfer would look unbalanced.
Running transfers and a bad write
The script defines a transfer that updates both balances and inserts both entries in one transaction, then tries three things: a valid transfer, an overdraft, and a one-sided entry written directly.
await transfer('t1', 1, 2, 800)
await transfer('t2', 2, 1, 5000) // Ravi has 2000 by now: overdraft
console.log('-- a one-sided entry is refused at commit')
try {
await db.transaction(async (tx) => {
await tx.query(
`INSERT INTO entries (txn_id, account_id, amount) VALUES ($1, $2,
$3)`,
['t3', 1, -100]
)
})
} catch (e) {
console.log('t3: ' + err(e))
}
text
t1: committed
t2: ERROR 23514 new row for relation "accounts" violates check
constraint "accounts_balance_check"
-- a one-sided entry is refused at commit
t3: ERROR 23514 transaction t3 does not balance
The first transfer of 800 committed. The second, moving 5,000 from Ravi who held 2,000 by then, was refused with SQLSTATE 23514 by the balance check, and the whole transaction rolled back: neither balance nor entries changed. The third wrote a single entry of minus 100 and failed at commit with the error message from the trigger, transaction t3 does not balance. A rule that lives in the database holds even when application code has a bug or another service writes to the table.
Reading it back
The audit queries show the state after those attempts.
ts
console.log(
'-- balances, and the audit that every transaction sums to zero'
)
show(
(
await db.query(
`SELECT account_id, holder, balance FROM accounts
ORDER BY account_id`
)
).rows
)
show(
(
await db.query(
`SELECT txn_id, sum(amount) AS net, count(*)::int AS lines
FROM entries GROUP BY txn_id ORDER BY txn_id`
)
).rows
)
show(
(
await db.query(`
SELECT a.account_id, a.balance AS stored_balance,
(CASE a.account_id WHEN 1 THEN 5000 ELSE 1200 END)
+ coalesce(sum(e.amount), 0) AS opening_plus_entries
FROM accounts a LEFT JOIN entries e USING (account_id)
GROUP BY a.account_id, a.balance ORDER BY 1`)
).rows
)
Asha's balance is 4,200 and Ravi's is 2,000, and only t1 exists, with a net of 0.00 over two lines. The last query reconciles the stored balances against the opening balances plus the sum of entries, and both match. That reconciliation is the reason to keep the entries: the balance column is a convenience, and the entries are the record.
That script ran on PGlite, which has one connection, so it cannot show two transfers at the same moment. The next two pages use a real server with two sessions.
Two transfers at once, with the balance read first
The server here comes from the embedded PostgreSQL package, started on a port of its own, with two client sessions, A and B. The accounts table has the same check that a balance never goes below zero. Account 1 holds 1,000, and each session tries to send 800 out of it, which only one of them can be allowed to do. The first version does what a first draft often does: it reads the balance in the application, subtracts 800 there, and writes the new value back, in the default READ COMMITTED isolation level.
ts
const [a] = await startShards([56350])
const b = new pg.Client({
host: '127.0.0.1',
port: 56350,
user: 'postgres',
password: 'pw',
database: 'postgres',
})
await b.connect()
const pause = (ms: number) => new Promise((r) => setTimeout(r, ms))
const err = (e: unknown) => {
const x = e as { code?: string; message: string }
return`${x.code} ${x.message}`
}
const balance = async () =>
(await a.query('SELECT balance FROM accounts WHERE account_id = 1'))
.rows[0].balance
console.log('-- read the balance, then write the new value')
await reset()
await a.query('BEGIN')
await b.query('BEGIN')
const seenA = (
await a.query('SELECT balance FROM accounts WHERE account_id = 1')
).rows[0].balance
const seenB = (
await b.query('SELECT balance FROM accounts WHERE account_id = 1')
).rows[0].balance
await a.query(
'UPDATE accounts SET balance = $1 WHERE account_id = 1',
[seenA - 800]
)
await a.query('COMMIT')
await b.query(
'UPDATE accounts SET balance = $1 WHERE account_id = 1',
[seenB - 800]
)
await b.query('COMMIT')
console.log(
`both transfers of 800 accepted, balance ${await balance()}`
)
text
both transfers of 800 accepted, balance 200.00
Both transfers were accepted, and the balance is 200.00. Each session read 1,000, saw that 800 was available, and wrote back 200. The check only ever saw 200, never a negative number, so it had nothing to refuse. Together the two sessions sent 1,600 out of an account that held 1,000, and the stored balance shows one debit. The database did what it was asked: it was asked to store a number, not to subtract one.
One statement that subtracts
The remedy is to let the database do the arithmetic in a single statement, SET balance = balance - 800, and let the check judge the result. The loop below runs the second attempt under two isolation levels, READ COMMITTED, which is PostgreSQL's default, and REPEATABLE READ. In each, both sessions start a transaction and run SELECT 1, so that a transaction has begun its snapshot. Session A subtracts first. Session B's identical statement is started without waiting for it, the script asks pg_stat_activity how many sessions wait for a lock, and then A commits.
ts
for (const level of ['READ COMMITTED', 'REPEATABLE READ']) {
console.log(`one UPDATE that subtracts, under ${level}`)
await reset()
await a.query(`BEGIN ISOLATION LEVEL ${level}`)
await b.query(`BEGIN ISOLATION LEVEL ${level}`)
await a.query('SELECT 1')
await b.query('SELECT 1')
const sub =
'UPDATE accounts SET balance = balance - 800 WHERE account_id = 1'await a.query(sub)
const second = b.query(sub).then(
() => 'accepted',
(e) => `refused: ${err(e)}`
)
await pause(500)
const waiting = await a.query(
`SELECT count(*)::int AS n FROM pg_stat_activity
WHERE wait_event_type = 'Lock' AND datname = 'postgres'`
)
console.log(
`sessions waiting for the row lock: ${waiting.rows[0].n}`
)
await a.query('COMMIT')
console.log(`second transfer ${await second}`)
await b.query('ROLLBACK')
console.log(`balance ${await balance()}`)
}
text
one UPDATE that subtracts, under READ COMMITTED
sessions waiting for the row lock: 1
second transfer refused: 23514 new row for relation "accounts" violates
check constraint "accounts_balance_check"
balance 200.00
one UPDATE that subtracts, under REPEATABLE READ
sessions waiting for the row lock: 1
second transfer refused: 40001 could not serialize access due to
concurrent update
balance 200.00
B's statement waited for A's row lock: one session was waiting. Under READ COMMITTED, the documentation says the waiting updater re-reads the row after the first transaction commits and carries on with the new version. That meant 200 minus 800 for B, and the check refused it with 23514, so the balance stayed 200 and exactly one transfer went through. Under REPEATABLE READ the same wait ended in 40001, could not serialize access due to concurrent update, an error that the application answers by retrying the whole transaction, as the transactions chapter showed. Either way the ledger refused the overdraft without any lock taken by the application. What made it work is that the subtraction and the check happened at the row, under its lock, in one statement. The first run shows the cost of reading first and deciding later. A transfer that changes two accounts must also take its locks in a consistent order, which the transactions chapter showed with its deadlock.
Could a key-value store do it
It could, with more work. The DynamoDB developer guide describes TransactWriteItems, which groups up to 100 actions in one all-or-nothing operation, and conditional writes, which fail when a condition on the current item is false. A transfer could be one transaction with a conditional update on each balance. But every rule the database enforced here, the non-negative balance, the balanced entries and the audit, would have to be written into the application's transactions and kept correct by every service that ever writes. A new question, such as a statement for any date range across accounts, would need a new key design or index. For a ledger the number of questions grows over time, which is why the relational fit is strong.
Check yourself
Why does a ledger point to a relational database in the decision table?
It needs transactions and constraints, and the questions asked of it, such as statements and audits, change over time.
A stale or half-applied balance is a bug, so strict consistency comes first.
What happened to the overdraft transfer in the run?
The balance check failed with 23514 and the whole transaction rolled back.
Neither the balances nor the entries changed.
Why is the balance trigger declared INITIALLY DEFERRED?
It must run at commit, once all entries of the transaction are present.
Run per row, the first entry of every transfer would look unbalanced.
Part 4 · A worked choice: chat messages at scale
Requirements and patterns
A chat app stores every message and must show the latest messages of any conversation quickly. Messages are written constantly and almost never changed. Reads are overwhelmingly one of two kinds: open a conversation, which reads the newest messages, and scroll back, which reads older ones. A stale read of a few messages costs nothing important.
Compare that with the ledger. The access patterns are few, known and stable. Consistency needs are mild. Volume is the pressure, because the table grows with every message and every user. These are the signs that point to a key-value or wide-column design: the partition key is the conversation and the sort key is the time.
The keys
In the DynamoDB-style design from the previous chapter, a message item has partition key CONV#<id> and sort key MSG#<timestamp>#<number>. The details of a conversation sit in the same partition under the sort key META. The patterns become key conditions: newest messages are a reverse Query with a limit, older messages continue from the last key returned, and a time window is a range on the sort key.
That chapter ran on an in-memory model of DynamoDB's documented behaviour, not on DynamoDB, and so does this one. It is the same model, with the same rules.
ts
const chat = new Table({
pk: 'pk',
sk: 'sk',
indexes: [
{ name: 'by-user', pk: 'gsi1pk', sk: 'gsi1sk', project: 'ALL' },
],
})
const stamp = (i: number) =>
new Date(Date.UTC(2026, 5, 4, 3, 30) + i * 60_000).toISOString()
for (let c = 1; c <= 3; c++) {
chat.put({
pk: `CONV#c${c}`,
sk: 'META',
title: ['Flat 4B', 'Cricket Sunday', 'Pongal plans'][c - 1],
})
for (let i = 1; i <= 40; i++)
chat.put({
pk: `CONV#c${c}`,
sk: `MSG#${stamp(i)}#${String(i).padStart(4, '0')}`,
sender: i % 2 ? 'asha' : 'ravi',
text: `message ${i} in c${c}`,
})
}
ts
console.log('-- open a conversation: the newest 5 messages')
console.log(
chat
.query({
pk: 'CONV#c2',
sk: { op: 'begins_with', v: 'MSG#' },
forward: false,
limit: 5,
})
.items.map((i) => `${i.sk} ${i.text}`)
)
console.log(
'-- scroll up: the next 5 older ones, starting after the last key'
)
const first = chat.query({
pk: 'CONV#c2',
sk: { op: 'begins_with', v: 'MSG#' },
forward: false,
limit: 5,
})
[
'MSG#2026-06-04T04:10:00.000Z#0040 message 40 in c2',
'MSG#2026-06-04T04:09:00.000Z#0039 message 39 in c2',
'MSG#2026-06-04T04:08:00.000Z#0038 message 38 in c2',
'MSG#2026-06-04T04:07:00.000Z#0037 message 37 in c2',
'MSG#2026-06-04T04:06:00.000Z#0036 message 36 in c2'
]
-- scroll up: the next 5 older ones, starting after the last key
[
'MSG#2026-06-04T04:05:00.000Z#0035',
'MSG#2026-06-04T04:04:00.000Z#0034',
'MSG#2026-06-04T04:03:00.000Z#0033',
'MSG#2026-06-04T04:02:00.000Z#0032',
'MSG#2026-06-04T04:01:00.000Z#0031'
]
Opening a conversation returned the five newest messages, 40 down to 36, and the key of the last one read. Scrolling up passed that key back as the start key and returned the next five, 35 down to 31. Each request reads only the five messages it returns, so the cost of opening a conversation does not depend on how many conversations exist, or how long this one is.
What it gives up
The same script jumps to a time and then measures one design pitfall, keeping a whole conversation in one item.
ts
console.log('-- jump to a time: messages from 04:08 onwards, first 3')
console.log(
chat
.query({
pk: 'CONV#c2',
sk: { op: '>=', v: 'MSG#2026-06-04T04:08' },
limit: 3,
})
.items.map((i) => i.sk)
)
console.log(
'-- all of a conversation in one item would hit the item size limit'
)
const one = sizeOf({
pk: 'CONV#c1',
sk: 'MSG#x',
sender: 'asha',
text: 'message 1 in c1',
})
console.log(
`a message here is ${one} bytes; 400 KB is ${400 * 1024} bytes, ` +
`so ${Math.floor((400 * 1024) / one)} messages fill one item`
)
text
[
'MSG#2026-06-04T04:08:00.000Z#0038',
'MSG#2026-06-04T04:09:00.000Z#0039',
'MSG#2026-06-04T04:10:00.000Z#0040'
]
-- all of a conversation in one item would hit the item size limit
a message here is 70 bytes; 400 KB is 409600 bytes, so 5851 messages
fill one item
A range from 04:08 returned the first three messages at or after that time. The last line works out what happens if a conversation were stored as one item holding all its messages: with each message at 70 bytes by the model's count of its JSON text, 400 KB, the item size limit in the DynamoDB developer guide, is reached after about 5,851 messages. The service counts attribute names and values by its own rules, so its figure would differ, but the shape of the result would not: a busy group would hit the limit and writes would start to fail. Messages belong in separate items with the conversation as the partition key.
What the design gives up is the flexibility the ledger kept. A question outside the keys, such as every message a person sent, needs a second index or table, or becomes a scan. Reporting across all conversations is awkward. There is no join between a message and a user profile, so the sender's display name is either copied into each message or fetched separately.
One case needs care. A single conversation that receives far more writes than one partition can take, such as a broadcast channel, is the hot key problem of the previous chapter, and its answer, write sharding with a suffix, trades simple reads for a merge. The design is not free of work at scale; it moves the work from the database to the keys.
Not a verdict
Notice that the NoSQL chapter ran the same query on Postgres. A messages table with the primary key (conversation_id, sent_at) answered "newest five of a conversation" with an index scan backwards over the key and no sort. So the question is not whether Postgres can do it. It can, and at moderate volume it is a good answer, with all the flexibility that comes with it.
The choice moves toward a key-based store when write volume or data size passes what a single primary can carry, when the team needs the store to spread data and absorb load without the shard routing code of the sharding chapter, or when the access patterns really are this narrow. The decision is a judgement about scale, operations and team, not about what is possible.
Check yourself
What are the partition key and sort key for messages in this design, and what does each serve?
The partition key is the conversation, so a conversation's messages are together.
The sort key is the time, so the newest messages and time windows are key ranges.
Why should a conversation not be stored as one item holding all its messages?
An item has a size limit of 400 KB; at 70 bytes a message here that is about 5,851 messages.
A busy group would hit the limit and writes would fail.
Name one thing this design makes hard.
Questions outside the keys, such as all messages from one person, which need another index or table.
Joins with user profiles, so sender details are copied or fetched separately.
Part 5 · Several stores, and keeping them in step
The dual-write problem
Real systems often end up with more than one store. Postgres holds orders as the source of truth, a search index serves the catalogue search box, and a cache serves hot product pages. Each is the right tool for its job. The difficulty is that one business event, a new order, now has to reach all of them.
The obvious code writes to the database and then to each of the others. Consider what happens when it fails halfway. If the process dies after the database commit and before the index write, the order exists but the search index never hears about it. Reversing the order does not help: the index then knows about an order that was never committed. A write to two systems cannot be made atomic by running them one after the other, and there is no transaction that spans both.
The outbox pattern
The usual remedy is the outbox pattern, which the transactions chapter introduced as the simpler alternative to a distributed transaction. The order and a description of the event are written to the same database in the same transaction: the order goes in orders and the event goes in an outbox table. Atomicity of that one transaction guarantees that either both rows exist or neither does. A separate process, the relay, reads unsent events from the outbox, delivers them to the other stores, and marks them sent.
Animated sceneAn order, an outbox row and a relay0:20
Watch for the order and its event being committed together
Read it as steps
From the run: events are delivered at least once, so the consumer skips repeats.
The scene shows the happy path and then the failure that matters, a relay that crashes after delivering an event and before marking it. The event is delivered again on the next run, so delivery is at least once, and every consumer has to cope with duplicates. This lesson runs the pattern, then gives it bad inputs.
The outbox in a run
The script builds the two tables, with two extra columns on outbox, attempts and parked_at, that the later runs use. It places three orders and shows that a failed order writes no event.
ts
const db = new PGlite()
await db.exec(`
CREATETABLE orders (order_id int PRIMARY KEY, customer text NOT NULL,
item text NOT NULL, status text NOT NULL);
CREATETABLE outbox (
event_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
topic text NOT NULL,
payload jsonb NOT NULL,
attempts int NOT NULL DEFAULT 0,
sent_at timestamptz,
parked_at timestamptz
);`)
ts
// the source of truth and the event are written in one transactionconst place = (id: number, customer: string, item: string) =>
db.transaction(async (tx) => {
await tx.query(
`INSERT INTO orders (order_id, customer, item, status) VALUES ($1,
$2, $3, 'placed')`,
[id, customer, item]
)
await tx.query(
`INSERT INTO outbox (topic, payload) VALUES ('order.placed', $1)`,
[JSON.stringify({ order_id: id, customer, item })]
)
})
await place(1, 'Asha', 'ghee laddu')
await place(2, 'Ravi', 'kaju katli')
await place(3, 'Meena', 'jalebi')
console.log('-- an order that fails also writes no event')
try {
await place(1, 'Asha', 'duplicate')
} catch (e) {
console.log('ERROR ' + (e as { code: string }).code)
}
ts
const outbox = async () =>
show(
(
await db.query(
`SELECT event_id, payload->>'order_id' AS order_id,
attempts, sent_at IS NOT NULL AS sent,
parked_at IS NOT NULL AS parked
FROM outbox ORDER BY event_id`
)
).rows
)
await outbox()
The duplicate order id failed with SQLSTATE 23505, and the outbox holds exactly three events, one for each committed order, all unsent. The failed attempt left nothing behind, because its event row was part of the transaction that rolled back.
The consumer and the relay
The consumer keeps a search index and a cache. An obvious version keeps a list of the event ids it has applied, but that list lives in the consumer's memory, so a restarted consumer would apply an old event a second time. This version keeps no list. Each entry in the index and the cache remembers the id of the event that wrote it, and an event that is not newer than the entry is skipped. Event ids come from the identity column of outbox, so a larger id is a later event.
ts
// two derived stores. Each entry remembers the id of the event that// wrote it, so an event that is not newer than the entry is skippedtype Doc = { event_id: number; text: string }
type Order = { order_id: number; customer: string; item: string }
const searchIndex = new Map<number, Doc>()
const cache = new Map<number, Doc>()
const apply = (eventId: number, p: Order) => {
if (!p.item) thrownew Error(`event ${eventId} has no item`)
const have = searchIndex.get(p.order_id)
if (have && have.event_id >= eventId) {
console.log(` event ${eventId}: already applied, skipped`)
return
}
const doc = { event_id: eventId, text: `${p.customer} ${p.item}` }
searchIndex.set(p.order_id, doc)
cache.set(p.order_id, doc)
console.log(` event ${eventId}: applied order ${p.order_id}`)
}
The relay locks a batch of unsent events with FOR UPDATE SKIP LOCKED, which the locking chapter showed lets several relays work without waiting for each other. It delivers each event in turn and marks the good ones sent in the same transaction. A bad event counts an attempt against itself, and after three attempts it is parked, which means the relay stops selecting it.
ts
// the relay: lock a batch, deliver each event, mark the good ones sent.// A bad event counts an attempt and is parked after threeconst MAX_ATTEMPTS = 3const relay = async (batch: number, crashAfterDelivery = false) => {
await db.transaction(async (tx) => {
const r = await tx.query<{ event_id: number; payload: Order }>(
`SELECT event_id, payload FROM outbox
WHERE sent_at IS NULL AND parked_at IS NULL
ORDER BY event_id LIMIT $1 FOR UPDATE SKIP LOCKED`,
[batch]
)
const done: number[] = []
for (const e of r.rows) {
try {
apply(Number(e.event_id), e.payload)
done.push(e.event_id)
} catch (err) {
console.log(` ${(err as Error).message}`)
await tx.query(
`UPDATE outbox SET attempts = attempts + 1,
parked_at = CASE WHEN attempts + 1 >= $2
THEN now() END
WHERE event_id = $1`,
[e.event_id, MAX_ATTEMPTS]
)
}
}
ts
if (crashAfterDelivery)
thrownew Error('relay crashed before marking the batch sent')
if (done.length)
await tx.query(
`UPDATE outbox SET sent_at = now()
WHERE event_id = ANY($1::bigint[])`,
[done]
)
})
}
Crashing twice, then recovering
The first two relay runs are told to crash after delivering two events and before marking them sent. The third run is normal.
ts
const unsent = async () =>
show(
(
await db.query(
`SELECT count(*)::int AS unsent FROM outbox
WHERE sent_at IS NULL AND parked_at IS NULL`
)
).rows
)
for (const n of [1, 2]) {
console.log(
`-- relay run ${n} delivers two events, dies before marking them`
)
try {
await relay(2, true)
} catch (e) {
console.log(' ' + (e as Error).message)
}
await unsent()
}
console.log('-- relay run 3 repeats those two, then does the third')
await relay(10)
await unsent()
text
event 1: applied order 1
event 2: applied order 2
relay crashed before marking the batch sent
unsent
------
3
(1 row)
-- relay run 2 delivers two events, dies before marking them
event 1: already applied, skipped
event 2: already applied, skipped
relay crashed before marking the batch sent
unsent
------
3
(1 row)
-- relay run 3 repeats those two, then does the third
event 1: already applied, skipped
event 2: already applied, skipped
event 3: applied order 3
unsent
------
0
(1 row)
Run 1 applied events 1 and 2 and then failed; the transaction rolled back, so all three events were still unsent. Run 2 picked up the same two events, the consumer answered already applied, skipped for both, and it crashed again with the same outcome. Run 3 repeated the two once more, applied event 3 and marked all three sent. The stores end up holding each order once: the crashes cost repeated deliveries, never a missing or a doubled order. This output is from this run. A different number of relays or a different crash point would change the order of the lines, but not the final state.
A bad event, and an old one again
The first version of the relay did all its work in one transaction and let an error from the consumer escape. Given three events, the second of which could never be applied, it delivered event 1 again on each of three runs, never reached event 3, and left all three events unsent, so one bad event blocked everything behind it. The version above catches the error per event. The next lines place order 4 with an empty item, which the consumer refuses, and order 5, which is fine, and run the relay three times.
ts
console.log('-- an event with no item, then a good one')
await place(4, 'Kiran', '')
await place(5, 'Divya', 'rasgulla')
for (let run = 1; run <= 3; run++) {
console.log(`-- relay run ${3 + run}`)
await relay(10)
}
await outbox()
text
-- relay run 4
event 4 has no item
event 5: applied order 5
-- relay run 5
event 4 has no item
-- relay run 6
event 4 has no item
event_id | order_id | attempts | sent | parked
---------+----------+----------+-------+-------
1 | 1 | 0 | true | false
2 | 2 | 0 | true | false
3 | 3 | 0 | true | false
4 | 4 | 3 | false | true
5 | 5 | 0 | true | false
(5 rows)
Event 5 was applied on the first run, in spite of the failing event ahead of it. Event 4 failed on each run, counted an attempt each time, and after the third it was parked: the outbox table shows its parked flag set and sent still false. A parked event needs a person or a separate job, because the relay will not touch it again. The last lines deliver event 1 once more.
ts
console.log('-- an old event delivered again is skipped')
apply(1, { order_id: 1, customer: 'Asha', item: 'ghee laddu' })
console.log(
[...searchIndex].map(
([k, v]) => `${k}: ${v.text} (event ${v.event_id})`
)
)
console.log(cache.size, 'cache entries')
await db.close()
The old event was skipped, and the index shows each order once, tagged with the event that wrote it. A consumer that keeps its dedupe information inside the data it updates survives a restart, which an in-memory list of ids does not. With several relays batches can finish in a different order from the one they started in, and the rule above, an event no newer than the stored one is ignored, makes a late older event harmless.
Two related ideas appear in real systems. Change data capture reads the database's own change log instead of an outbox table, and the replication chapter listed it among the uses of logical replication in Postgres. Every extra store also needs a way to be rebuilt from the source of truth. The cost of several stores is real: more systems to run, a pipeline to monitor, and a delay between a write and its appearance everywhere. Pay it for a named need.
Check yourself
Why can't an application safely write to the database and then to a search index in two steps?
A crash between the two writes leaves one store without the change, and there is no transaction across both.
Writing in the other order leaves the index knowing about a change that never committed.
What does the outbox pattern guarantee, and what does it not?
The order and its event are committed together, so neither exists without the other.
Delivery is at least once, so consumers must tolerate duplicates.
One event in the outbox can never be applied. What did the first relay do, and what does the final one do?
The first relay rolled back its whole batch on every run, so the events behind the bad one were never delivered.
The final relay counts an attempt against the bad event, parks it after three, and keeps delivering the others.