Topic: databases

Reading: 29 min, plus 1 in closed details. A map of where an application keeps its data: the families of data stores and what each makes cheap, one write followed through the whole stack, the eight ideas a from-zero reader needs, how to choose, and the child page that owns each part. Sources are linked inline; data as of October 2026.

The idea in one screen

A database keeps an application's data safe, correct and quick to find while many people use it at once; each kind of database buys that for one access pattern by choosing what it stores together, so start with one Postgres and add another store only when a measured problem needs what it makes cheap.

The running example is the one the Topic: swe-and-system-design page uses: a chat assistant powered by a large language model (LLM). People sign up (users), open conversations (chats), send and receive messages, and spend prepaid credits. Every child page of this topic measures the same product, so their numbers line up. The figure shows where its data lives at three moments; each store added later is a second copy of some fact, with its own lag, and a child page owns it.

  1. Day 1: one file, 1 user (you). The API server reads chats.json at start-up and writes the whole file back after every message. Section 1 shows the three ways that breaks.
  2. Year 1: one Postgres, thousands of users. The API servers send SQL to one database holding users, chats, messages and credits: the source of truth, sections 1 to 4.
  3. Year 3: a fleet, millions of users. Redis beside the API servers holds the cached chat list and rate limits; a vector index answers search by meaning; a column store (Parquet files and DuckDB, or ClickHouse) answers analytics. Each is fed from Postgres, a second copy with its own lag.
  4. Each store has an owner. Postgres and its engine are SQL and data modelling, Transactions and concurrency, Storage engines and indexes, Query planning and performance and Running Postgres in production; Redis is Caching and NoSQL in practice; the vector index is Search and vector databases; the column store is Analytics; outgrowing one machine is Scaling a database.

You need: nothing; the page starts from zero and defines each term where it first appears. The system around the database (servers, queues, failure) is Topic: swe-and-system-design; the page cache and fsync under it are Storage and file systems.

New terms (each defined again where it is used):

Table, row, column, key: one table per kind of thing, one row per thing; a primary key names a row, a foreign key points to another row.
SQL: the declarative language of relational databases: say what you want, the database decides how.
Transaction, isolation level: changes that happen all together or not at all; how much concurrent transactions may see of each other.
Page, WAL, index: the 8 KB block data is read in; the log written before pages so a commit survives a crash; a sorted structure that finds rows without reading all of them.
OLTP, OLAP: many small reads and writes of whole rows (the app); few big scans of a few columns (analytics).
Replica, shard: a full copy of the database on another machine; one slice of the data on its own machine.
Cache, TTL: a fast copy of answers already computed; how long a copy lives before it expires.
Embedding, ANN: a list of numbers a model produces so similar meanings land close together; approximate nearest-neighbour search over them.

Three tools on this page span several children: the SQL playground runs real SQL on the chat tables in your browser (the SQL lessons, then the credit transfer the transactions page reuses), Query plans shows how Postgres executed eight real queries on a 10-million-message table (indexes, joins, estimates, rows against columns, caches), and the Database atlas compares every family and its main products.

The map: what each kind of store keeps together, what that makes cheap, and its price

A family is a data model plus a storage layout tuned for one access pattern: whatever one planned question reads is stored side by side, so that question is cheap and the questions nobody planned become scans. Read across a row; the price column is the part that only shows when the families are side by side. Postgres does a passable version of several rows through extensions (jsonb, full text, pgvector, partitions), which is why it stays the default until a measurement says otherwise.

Family (examples)Kept togetherCheapHard, and the priceIn the chat productOwner
Relational row store (Postgres, MySQL, SQLite)A whole row in an 8 KB page; indexes sorted by keyPoint reads and writes, joins, transactions across rows, questions nobody plannedScans of a few columns over everything; writes beyond one machineUsers, chats, messages, credits: the source of truthSQL and data modelling, Transactions and concurrency, Storage engines and indexes, Query planning and performance, Running Postgres in production
Key-value (Redis, Valkey, DynamoDB)One value per keyGet and set by key: microseconds in memory (Redis), any scale if every access names its key (DynamoDB)Any question not by key; Redis copies to replicas asynchronously, so a failover can lose writes it already acknowledgedThe cached chat list, rate-limit counters, sessionsNoSQL in practice (sections 3, 4); Caching
Document (MongoDB, Firestore; Postgres jsonb)One nested record, read and written wholeRecords whose shape varies and are always read as one unitJoins and multi-document rules are weaker or slower; "no schema" becomes many schemasTool-call payloads of varied shape, usually a jsonb column insteadNoSQL in practice (section 5)
Wide-column (Cassandra, ScyllaDB, Bigtable)Rows sharing a partition key, sorted inside it, on the machines that key maps toWrite volume beyond one machine, many regions, queries known in advanceNo joins; a new question needs a new table; the partition key is permanentMessages, at a scale few products reachNoSQL in practice (section 6)
Search (Elasticsearch, OpenSearch; Postgres full text)An inverted index: each word with the documents that contain itWords, phrases, typos, facets, ranking with BM25Another copy, refreshed about a second behind, that must be rebuildable from the source of truthSearch over chat history by wordsSearch and vector databases (sections 1 to 6, 13)
Vector stores (pgvector, Qdrant, Milvus, Pinecone, Turbopuffer)Embeddings in an approximate nearest-neighbour index (HNSW, IVF)Nearest neighbours by meaning, in millisecondsApproximate by design; indexes large and slow to build; filters can starve the resultRAG retrieval, semantic cache, deduplicationSearch and vector databases (sections 7 to 12; Turbopuffer and the other dedicated stores against Postgres in section 12); index internals: Vector indexes from the inside
Time-series (TimescaleDB, InfluxDB, Prometheus)Time-sliced chunks, compressed, dropped on a scheduleSteady appends and "last hour" ranges; retention by dropping whole chunksAnything that is not a time range; a column store often does the same jobLatency and tokens per second for every requestNoSQL in practice (section 7); Observability
Graph (Neo4j, Memgraph, Kuzu)Each node with its edgesPaths and patterns of unknown depth (fraud rings, inherited permissions)Another system, and no faster at counting: up to three hops Postgres joins wonRarely neededNoSQL in practice (section 8); GraphRAG and structured retrieval
Column store and lakehouse (DuckDB, ClickHouse, BigQuery, Snowflake, Redshift; Parquet with Iceberg or Delta)Each column's values, compressed, with min and max per blockScans and aggregates of a few columns over millions of rows (section 5: about 94 times fewer bytes)Updating single rows; a second copy that is always somewhat behindTokens per model per day; training data, eval results, logsAnalytics: columnar engines, DuckDB and the lakehouse
Embedded (SQLite, DuckDB)A library inside your program and one local fileNo server, no network: phones, desktop apps, tests, notebooks, one-machine jobs (SQLite is likely the most deployed database of all, over a trillion in use, sqlite.org)One machine; SQLite allows one writer at a timeHistory cached on the phone; analysis in a notebookNoSQL in practice (closed Depth); Analytics (section 6, DuckDB)
Distributed SQL (CockroachDB, Spanner, TiDB, YugabyteDB)Ranges of rows, each copied to several machines that agree on every change (Raft or Paxos)SQL and transactions beyond one machine, or surviving the loss of a regionEvery write waits for a quorum (more latency across regions); transactions spanning ranges are slower; more to pay and runOnly at very large scaleScaling a database (sections 11, 12)

Two things are roles, not families. A cache is any fast store (usually Redis) holding copies of answers already computed: Caching owns every layer of it. Object storage (S3 and its equivalents) holds files and the Parquet files a lakehouse is made of: Analytics owns it as table storage. And two subjects are split between pages: pools (how many connections give the most throughput is Query planning and performance section 8; PgBouncer's modes and traps are Running Postgres in production section 7; sizing a pool with Little's law is Capacity planning and performance), and the lock queue (which ALTER TABLE takes which lock is SQL and data modelling section 11; finding the blocker on a live server is Running Postgres in production section 8).

One write through the whole stack, and which page owns each step

Ben sends a message that costs one credit. Following that one write from his request to the copies it feeds touches every child of this topic, in this order. Predict before it plays: of the eleven steps, how many happen before the database says "committed"?

Six steps decide whether the write is correct and durable; five more keep its copies in step afterwards

  1. Borrow a connection. The app server takes an open connection from its pool instead of opening one (a new connection per query kept 2% of the throughput when measured). Running Postgres in production section 7; Query planning and performance section 8
  2. Send the SQL. UPDATE credits SET balance = balance - 1 WHERE user_id = 2 AND balance > 0, then INSERT INTO messages; constraints refuse a message for a chat that does not exist. SQL and data modelling sections 6, 10
  3. Isolate it. The conditional update locks Ben's credits row; a second tab sending at the same instant waits, re-checks balance > 0 and changes nothing. Transactions and concurrency sections 1, 6
  4. Plan it. The planner estimates rows from its statistics and chooses the index on user_id rather than reading the whole table. Query planning and performance sections 1 to 6
  5. Change pages in memory. The update writes a new version of Ben's row (the old one stays for readers that started earlier) in a page in the buffer pool; the new message gets an entry in every index on messages, while the credits update can skip its indexes when no indexed column changed (a HOT update). Storage engines and indexes sections 1, 2, 5, 11; Transactions and concurrency section 5
  6. Commit. A record of the change is appended to the write-ahead log and flushed to disk; only then does Postgres answer "committed". Storage engines and indexes section 3; Transactions and concurrency section 2
  7. Replicate. A replica receives the same log records and replays them, a little behind; a read sent there just after the commit may not see it. Running Postgres in production section 3; Scaling a database section 3
  8. Invalidate the cache. The app deletes Ben's cached chat list so the next read rebuilds it, and a slow reader can still put the old copy back unless the cache is filled with leases. Caching sections 3, 4
  9. Feed the other copies. Change data capture or a nightly export carries the new row to the column store and the search index, minutes or a second behind. Analytics section 10; Search and vector databases sections 6, 13
  10. Clean up later. A checkpoint writes the changed page to its file; vacuum removes the old row version once no transaction can see it. Storage engines and indexes sections 3, 4; Running Postgres in production section 5
  11. Outgrow one machine. When writes outgrow the server, the same write goes to the shard that owns Ben's user id, and a question across users must ask every shard. Scaling a database sections 6 to 9

The order of events is Postgres's documented behaviour; the user and the statements are the sample rows of section 1.

The answer to the prediction

Six (steps 1 to 6) happen before "committed"; the commit waits only for the log flush, never for the page itself, the replica, the cache or the copies.

1. Why a database, and the relational model

Day one, the chat app keeps everything in one file, chats.json, read at start-up and written back whole after every message. Three things break it, each at a different size: two requests at once each write the whole file and one message vanishes with no error; a power cut half-way through a write leaves a file that may not even parse; and every question ("user 17's chats") reads the whole file, gigabytes at ten million messages illustrative.

A database (properly a database management system) is a separate program that owns the data; the app sends it requests over a connection. It promises four things a file cannot: durability (once it says "saved", a crash cannot lose it; section 4), safe concurrent access (section 3), queries that find answers without reading everything (sections 2 and 4) and constraints, rules checked on every write ("every message belongs to an existing chat").

Most databases you meet first are relational, after Edgar Codd's 1970 paper (Codd, CACM 1970): data in tables, one per kind of thing, with named columns and one row per thing. A primary key names a row; a foreign key stores another row's key, and that pointer is the "relation". The chat product needs four tables. Click a row: the rows it points to, and the rows that point to it, light up.

The price: a server to run, back up and upgrade; a network hop per request (a fraction of a millisecond in one data centre); and a schema you change by deliberate migrations. An embedded database such as SQLite gives the promises without a server, in one file (the map's Embedded row).

Go deeper: designing tables, keys and relationships, and changing them safely, is SQL and data modelling (sections 7 to 11); the API in front of the database is Building a backend API.

The email lives once, in users; a message reaches it through two keys

Click a row to follow its keys.

2. SQL: say what you want, not how to get it

SQL (Structured Query Language) is declarative: you describe the result and the database works out the steps (section 4 shows who chooses). Six clauses cover most of what an app asks:

SELECT id, role, tokens          -- which columns
FROM messages                     -- which table
WHERE chat_id = 11                -- which rows
ORDER BY id DESC LIMIT 50;       -- in what order, how many

JOIN combines rows of two tables whose keys match; GROUP BY collapses rows sharing a value into one row with an aggregate such as count(*) or sum(tokens); INSERT, UPDATE and DELETE change data. A query is written in one order and evaluated in another: FROM and the joins, then WHERE, grouping, the SELECT list, then sorting (the PostgreSQL SELECT reference lists the order).

The schema declares the tables, and each constraint in it (NOT NULL, CHECK (tokens >= 0), REFERENCES chats(id), UNIQUE) is checked on every write, whichever code path sends it. Normalisation is storing each fact once (the email in users, a key everywhere else), so a change is one write rather than an update anomaly where two copies disagree. Copying facts on purpose to skip joins is denormalisation: faster reads, and every copy is yours to keep in step; analytics and wide-column stores do it deliberately, an app's source of truth usually should not.

Go deeper: every query here runs in the SQL playground; joins drawn as pairs, NULL logic, grouping, window functions, recursive queries, upserts, normalisation, constraints and migrations, with 28 graded exercises, are SQL and data modelling.

3. Transactions: when two requests touch the same data

Ben has 1 credit and presses send in two browser tabs at once. Each request reads his balance, sees 1, calls the model, saves the reply and writes 0. Run against a real Postgres for this page, each request inside BEGIN and COMMIT: both messages were saved and the balance ended at 0 measured. That is a lost update: a write based on a value that was already stale.

A transaction groups reads and writes into one unit that commits or rolls back whole. ACID (Haerder and Reuter, 1983, ACM Computing Surveys) names its promises: atomic (all or nothing), consistent (every constraint holds after each commit; business rules beyond constraints stay your code's job), isolated (concurrent transactions do not see each other's half-done work; how much is a setting) and durable (section 4). Ben's run was inside transactions and still lost the update, because the isolation level Postgres uses by default, read committed, lets each statement see whatever was committed before it started. The levels are best read by the anomalies they still allow (Postgres documentation):

Level in PostgresDirty readNon-repeatable readPhantomSerialization anomaly (write skew)
Read committed (default)nopossiblepossiblepossible
Repeatable readnonono in Postgres (the SQL standard allows it)possible
Serializablenononono

Write skew: two transactions each read the same rows, each make a decision valid alone and write different rows, and together they break a rule (two doctors both going off call). Postgres isolates without locking every read through MVCC: an update writes a new row version and readers keep their snapshot, so "reading never blocks writing and writing never blocks reading" (Postgres MVCC).

The three fixes, in the order a professional reaches for them: fold the check into the write (UPDATE ... WHERE balance > 0, and call the model only if one row changed); lock the row you will change (SELECT ... FOR UPDATE); or run serializable and retry on a serialization error, which also catches anomalies you did not think of, such as write skew. The last two were run on Ben's two tabs: one reply sent, balance 0 (serializable aborted the second tab with could not serialize access due to concurrent update) measured. The price: locks make others wait and two waiting on each other is a deadlock; serializable turns conflicts into errors to retry; old row versions pile up until vacuum removes them, and a transaction left open (never across a model call) stops that clean-up.

Go deeper: the eight anomalies at every level on Postgres and MySQL, measured, with MVCC, locks, deadlocks, optimistic concurrency and retries, is Transactions and concurrency; what a forgotten open transaction does to vacuum on a live server is Running Postgres in production (section 5); transactions across machines are Distributed systems fundamentals; idempotency keys for retried requests are Service APIs (section 4).

4. Inside the engine: pages, the log, the index, the planner

On the laptop measured for this page, opening one chat of a 1,000,000-message table (the messages of chat 42000) read 19,349 pages and took 28 ms to return 6 rows measured; with an index it read 12. Four pieces explain that gap and the promise that "saved" survives a power cut; each has a child page.

PieceWhat it isMeasured here (1,000,000 messages)Owner
Page and buffer poolEvery table and index is an array of 8 KB pages, always read whole; pages in use are cached in RAM (shared_buffers, 128 MB by default). Memory answers in about 100 ns, a fast SSD in about 100 µs.The table is 19,235 pages (157 MB), about 52 rows a page; of the scan's 19,349 page reads, 14,435 were found in the buffer pool and 4,914 came from the operating systemStorage engines and indexes (sections 1, 2)
Write-ahead log (WAL)Before a data page changes on disk, the change is appended to a sequential log and flushed with fsync; the commit waits only for that. Pages are written later at a checkpoint; after a crash the log is replayed. The same records keep a replica current and restore a backup to any moment.A small write transaction took 6.3 ms with a real flush against 0.42 ms without one; with real flushes, 148 write transactions a second from 1 client and 2,133 from 32, because one flush covers many commitsStorage engines and indexes (sections 3, 4); Running Postgres in production (sections 1 to 3)
Index (B-tree)A separate tree of pages kept sorted by a column, hundreds of keys a page, so millions of rows sit three or four levels deep. Every write must also update every index.Index on chat_id: 12 pages instead of 19,349 (Buffers: shared hit=12); it takes 9.3 MB, 6% of the tableStorage engines and indexes (sections 5, 9 to 11)
Query plannerChooses how to run a query (scan or index, join order, join method) from cost estimates built on statistics; EXPLAIN shows the plan, EXPLAIN ANALYZE runs it and adds actual rows and times. It goes wrong when its estimates do: compare estimated with actual rows, step by step.Eight real plans on 10,000,000 messages, each before and after its fix, in Query plansQuery planning and performance

An index costs every insert and update and helps only queries that filter or sort on its leading column: index what your queries search by, measure, drop what nobody uses. The B-tree's write-optimised rival, the LSM-tree (Cassandra, RocksDB), trades reads for cheap writes; Storage engines and indexes measures both (section 7).

How these numbers were measured

PostgreSQL 16.2 (the pgserver wheel) and DuckDB 1.5.6 on an Apple M1 Pro laptop, 2026-10-04: 1,000,000 messages over 100,000 chats, generated by src/read/measure_read.py (outputs in src/read/inputs/read_measure.json, checked by src/read/recompute.py). The transaction runs gave Ben's credits row user_id 17 instead of the sample table's 2, which changes nothing; the second session started 0.1 seconds after the first. The transaction rates are the atlas agent's pgbench run with fsync_writethrough, which really flushes the drive cache on macOS. Server SSDs flush far faster than a laptop's; the Numbers to know tab of the system design page has both.

5. Rows and columns: apps and analytics want opposite layouts

OLTP (online transaction processing) is what the app does: many small reads and writes, each of a few whole rows, each in milliseconds. OLAP (online analytical processing) is what analytics does: few large queries reading a few columns of a huge number of rows. A row store such as Postgres keeps each row's values side by side, so one whole row is one page read; a column store keeps each column's values side by side, so a query reads only the columns it names, and values that look alike compress far better.

The same question, "tokens per model", over the same 1,000,000 messages: Postgres read 157.7 MB (19,251 pages) in 70 ms, because every page holds whole rows including the text the question never looks at; DuckDB read the two needed columns of a Parquet file (an open column-oriented format, each column of each block of rows compressed separately with its min and max, Parquet docs), 1.68 MB in 2.6 ms measured. Both returned the same four totals (80,277,256 tokens for mini); the column store read about 94 times fewer bytes. The role column alone shrank from 254,530 bytes to 862. Bytes are the fair comparison; the times come from two engines. At a billion messages the row store would read about 158 GB per question (derived, linear), on the server that is answering users. Query plans case 6 repeats it at 10,000,000 messages: 1.47 GB against 17.3 MB of two Parquet columns, 87 times fewer bytes.

The price: a column store rewrites compressed blocks to change one row, so it is built for appending in bulk; and it is a second copy fed from Postgres (a nightly export or a stream of changes), always somewhat behind. Where it runs: DuckDB inside your program on Parquet files; ClickHouse as a server you run; BigQuery, Snowflake and Redshift as managed services with storage apart from compute; a lakehouse is Parquet on object storage plus a table format (Iceberg, Delta Lake) that adds safe concurrent commits, so several engines share the files.

Go deeper: column chunks, encodings, zone maps, vectorised execution, the Parquet file byte by byte, DuckDB, ClickHouse, warehouses and lakehouse tables are Analytics: columnar engines, DuckDB and the lakehouse; moving changes out of Postgres reliably (the outbox, change streams) is Queues, streams and async work.

Postgres reads every page of whole rows; DuckDB reads only the two columns the question names

Bytes read for "tokens per model" over the same 1,000,000 messages, on a log scale (each gridline is 10 times the last). Top bar: the 19,251 Postgres pages read. Below: the Parquet file's seven columns as stored, compressed; the two the query reads (model and tokens) are coloured and add up to 1.68 MB. The content column, the text of every message, is the largest by far (83.5 MB before compression, 22.4 MB in Parquet), and a row store carries it on every page it reads. Measured for this page (section 4's details).

6. The families: escape hatches from the Postgres default

The product grows and some requests stop fitting one relational database well: the chat list rebuilt from the same query thousands of times a minute, search by words and by meaning, a latency measurement every second from every server. There are hundreds of products but about ten families (the map above), each the answer to one such problem. Three measured results show the price of reaching for one too early:

  • A cache is not free speed. A cache holds copies of answers already computed, each usually with a TTL. A Postgres lookup by primary key took 0.067 ms over a local connection, while the Redis documentation's own benchmark example shows about 0.14 ms per request (vendor figure, different conditions): caching a single-row lookup by key buys nothing. Even deleting the copy on every write leaves a race in which a slow reader puts the old value back (Scaling Memcache at Facebook), which is why caches keep an expiry as a backstop.
  • Hybrid search is not always a win. Scored by nDCG@10, vectors alone beat word-plus-vector fusion on Quora questions (0.839 against 0.825) while the fusion won on SciFact (0.714 against 0.645) measured in Search and vector databases.
  • A graph database wins only at depth. On a friends graph Neo4j found a 4-hop shortest path in 5 ms against about 130 ms for a recursive query in Postgres, yet for friends of friends (up to three hops) Postgres joins were the fastest engine tried measured in NoSQL in practice.

What every extra family costs: a second copy of some facts with its own lag, failure modes, backups, upgrades and on-call knowledge. The question is never "is this tool better at X" but "is X now painful enough, measured, to pay for another system". Postgres's full-text ranking (ts_rank) is not BM25, Redis can lose acknowledged writes in a failover, and a partition key decides forever which machine holds a wide-column row: each family's fine print is on its owner page.

Go deeper: every family and its products, with data model, consistency and limits, is the Database atlas; Redis, DynamoDB, documents, wide-column, time series and graphs measured against Postgres are NoSQL in practice; search and vector stores are Search and vector databases; every cache layer, invalidation and the LLM caches are Caching; distributed SQL is Scaling a database (section 11).

7. Choosing: five questions, and two doors that only open one way

Every vendor's benchmark shows its product winning, and a database is one of the hardest things to change later. So the choice needs a method, applied when a measured limit forces you off the default. Five questions, in this order:

1. What are the access patterns?Which queries run, how often, how fast they must be. Almost any data fits almost any model; each store is fast only at certain queries (a key-value store only if you always know the key).
2. Which rules must hold across rows?If two things must change together (charge a credit and save a reply), you want real transactions inside one store. This rules out most alternatives for business data.
3. How much writing, and how uneven?This page's laptop, flushing every commit for real, ran 2,133 small write transactions a second with 32 clients measured, and a server SSD flushes far faster; hundreds of thousands a second across regions do not fit one server. Plan for the peak and the busiest single key.
4. How much do you know about future questions?If you cannot list tomorrow's queries, a normalised relational schema answers new ones for free; only queries known and frozen justify a store designed around them.
5. What can your team run at 3 a.m.?Backups that have been restored, failover, upgrades, someone on call who understands it (Running Postgres in production).

Applied to the chat product, the answers explain the fleet in the opening picture:

DataAccess patternRules across rowsStore
Users, chats, messages, creditsBy user and chat; new questions every monthYes: credits and replies change togetherPostgres (the source of truth)
Chat list, rate-limit countersSame key read constantly; a little staleness is fineNoRedis, as a cache built from Postgres
Tokens per model per dayScans of two columns over everythingNo; minutes behind is fineColumn store, copied from Postgres
Search history by meaningNearest neighbours of an embeddingMust respect who may see which chatpgvector inside Postgres first (section 8)

The two doors that only open one way. Almost every choice can be undone with a migration; two cannot without rewriting every row. When data is split across machines (sharding), the shard key decides where each row lives: shard by user and "all of one user's chats" is fast while "all chats about a topic, across users" asks every machine. In a wide-column store the partition key plays the same role. Choose either from the queries you will run most and check no single key will be too busy. One more decision is cheapest at schema time: how long each kind of data is kept and how it is deleted (a user's right to erasure, where data may live, audit retention); a store with no practical way to delete one user's rows is one you will migrate off.

A rule of thumb, kept as advice (opinion, not a sourced claim): start with Postgres + S3 (object storage for files and Parquet) + Redis, add a column store when analytics queries hurt, add Kafka when more than two systems need the same events. Each addition is a row of the map with its price; Distributed systems fundamentals keeps the same rule.

Go deeper: choosing a shard key on the chat data, and why changing it is a one-way door, is Scaling a database (sections 7 and 9); sharding in general is Distributed systems fundamentals; worked designs that make these choices end to end are System design case studies.

8. The ML and LLM angle

The chat product adds retrieval-augmented generation (RAG): before answering, it finds the passages of a user's documents closest in meaning to the question and puts them in the prompt. Each passage now has an embedding plus the facts any app needs: owner, who may see it, source document, and a way to delete it. The team also trains and evaluates models on chat logs. Four database ideas carry most of this, each owned by a child.

IdeaWhat it means hereOwner
Vectors next to the rows: pgvector firstpgvector adds a vector column and ANN indexes (HNSW, a layered graph walked greedily, Malkov and Yashunin; IVFFlat) to Postgres, trading a little recall (the share of the true nearest neighbours returned) for speed. The passage, its owner, its permissions and its embedding become one row: one transaction writes them, one delete removes them, one backup holds them. Its limits are memory (a 1,536-dimension vector of 4-byte floats is 6,152 bytes as pgvector stores it, about 615 GB per hundred million before any index, derived) and filters applied after the index scan. A dedicated store earns its place when vectors outgrow one server or filtered search dominates; measure recall and latency on your own data rather than trusting a vector count.Search and vector databases (sections 7 to 12); Vector indexes from the inside
Feature stores are two databasesA feature store (Feast, Tecton) is an offline store of feature history for training sets plus an online store of each entity's latest values for serving: a column store (section 5) plus a key-value store (section 6), fed by the same code so training and serving do not drift. Training examples must join features as of their own timestamp (a point-in-time or ASOF join), or labels leak.Analytics: columnar engines, DuckDB and the lakehouse (section 11); ML platforms and workflows
DuckDB on Parquet for datasets and evalsTraining data, eval results and logs are mostly Parquet files; DuckDB queries them in place with SQL and no server (section 5's two columns of a million rows in 2.6 ms).Analytics (sections 5, 6); Storage and loading at scale
A language model that writes query plansA fine-tuned 4-billion-parameter model writing pg_hint_plan hints beat Postgres's planner by 1.40 times geometric mean on the Join Order Benchmark (Rohan Bansal, 2026-09-16), on a set also watched during development, so not a held-out result; executing candidate plans costs far more than planning once, so it pays only for one heavy query run again and again.Query planning and performance (closed block: Learned optimizers)
Go deeper: retrieval quality, chunking and rerankers are Topic: rag-and-retrieval; datasets and Parquet at training scale are Topic: data-curation-and-datasets; serving and data paths for ML are ML system design; the LLM caches (KV, prompt, semantic) are Caching (sections 10 to 12).

Habits that span the children

1. Start with one Postgres and a normalised schema with keys and constraints, so the database refuses bad data whichever code path sends it (sections 1, 2; SQL and data modelling).

2. Put every check-then-change inside one statement or one short transaction: a conditional UPDATE ... WHERE balance > 0 first, a row lock or serializable with a retry when the rule spans rows; never hold a transaction open across a model call (section 3; Transactions and concurrency).

3. Index for the queries you run, and read the plan: EXPLAIN (ANALYZE, BUFFERS), estimated against actual rows, pages read (section 4; Storage engines and indexes, Query planning and performance).

4. Move analytics off the app database into a column store fed from it, and accept that it lags (section 5; Analytics).

5. Add a family only for a measured problem, and write down its price: the copy, its lag, its staleness and who runs it (section 6; NoSQL in practice, Search and vector databases, Caching).

6. Treat the shard key and the partition key as permanent; everything else can be migrated (section 7; Scaling a database).

7. Keep embeddings next to the rows they describe until a measurement says otherwise (section 8; Search and vector databases).

8. Trust, but test: restore a backup on a schedule, and read what independent testers such as Jepsen found about the systems you run (Running Postgres in production; Transactions and concurrency).

The child pages, in reading order

Ten pages on the same chat product, each with its own measurements; in this order each assumes only this page and the ones before it. Times are the reading time each page's header states (core, plus closed details).

1. SQL and data modelling: queries, joins, schema design, normalisation, migrationsChild page, about 48 min, plus 24 in closed details. Sections 1 and 2 in depth: evaluation order and NULL logic, joins, grouping, windows, recursive queries, upserts, keys, modelling shapes, normalisation, constraints, migrations on a live table, checking SQL an ORM or LLM writes; 28 graded exercises.
2. Transactions and concurrency: ACID, MVCC, isolation anomalies, locksChild page, about 43 min, plus 5 in closed details. Section 3 in depth: eight anomalies at every isolation level on Postgres and MySQL, measured; MVCC and snapshots, locks and deadlocks, SSI, optimistic concurrency, retries, long transactions, the outbox.
3. Storage engines and indexes: pages, B-trees, LSM-trees, the WAL, index typesChild page, about 42 min, plus 14 in closed details. Section 4's engine in depth: pages, the buffer pool, the WAL and a real crash recovery, B-trees against LSM-trees with amplification measured, heap against clustered, every Postgres index type and shape, what indexes cost on writes.
4. Query planning and performance: EXPLAIN, statistics, slow queries, tuningChild page, about 45 min, plus 11 in closed details. Section 4's planner in depth: the cost model reproduced, statistics and misestimates, join algorithms, reading EXPLAIN, the slow-query workflow, N+1, pagination and pooling measured, settings, plan regressions.
5. Running Postgres in production: backups, replication, vacuum, upgrades, poolingChild page, about 43 min, plus 17 in closed details. Keeping the default alive: memory and checkpoints, backups and point-in-time recovery, replication and failover, vacuum and wraparound, PgBouncer, safe schema changes and the lock queue, monitoring, upgrades, managed services; an incident lab.
6. Scaling a database: read replicas, sharding Postgres, distributed SQLChild page, about 45 min, plus 8 in closed details. Section 7's one-way door in depth: the ladder from query fixes to replicas, partitioning, functional splits, sharding (the shard key chosen on real data), resharding, distributed SQL and multi-region, with how real companies climbed.
7. Caching: every layer, eviction, invalidation, and the LLM cachesChild page, about 43 min, plus 22 in closed details. Section 6's cache in depth: why caches work, the layers, patterns and invalidation with the stale-set race, consistency windows, Redis eviction on real traffic, hit-rate arithmetic, TTLs and stampedes, CDNs, then the KV, prompt and semantic caches.
8. Analytics: columnar engines, DuckDB and the lakehouseChild page, about 46 min, plus 9 in closed details. Section 5 in depth: column chunks and encodings, zone maps, vectorised execution, the Parquet file byte by byte, DuckDB, ClickHouse, warehouses and billing, Iceberg and Delta, ELT, point-in-time joins for ML.
9. NoSQL in practice: key-value, document, wide-column, time-series, graphChild page, about 46 min, plus 16 in closed details. Section 6's families in depth, each measured against Postgres: Redis and its failover, DynamoDB single-table design, MongoDB beside jsonb, Cassandra's write path, time series, graphs.
10. Search and vector databases: inverted indexes, BM25, ANN, pgvectorChild page, about 33 min, plus 13 in closed details. The search and vector rows in depth: Postgres full text and Lucene engines, BM25 as configured, pgvector's indexes measured for recall and latency, filters, hybrid search in SQL, vector stores compared by design, operating an index.