LS·200
Phase 4 — Data
The fourth phase: SQL, PostgreSQL, transactions, indexes, query optimisation, Redis, NoSQL and search, ending with a data-heavy application built and optimised; the order and why, an entry check, step-by-step exit checks mapped to Volume 4, the project with milestones and definitions of done, traps, a time budget, and a lab that takes four slow queries on 2 million rows and fixes each one.
Start here: Phase 4 in one page
Most backend performance problems are data problems: a missing index, a query written so the index can't be used, a page that loads 50,000 rows to show 20, a loop that runs a query per item. Phase 4 makes you fluent in the database you'll use most (PostgreSQL), then adds the other stores you'll meet: Redis for caching and fast state, a document or key-value store, and a search engine.
The sequence
SQL → PostgreSQL → transactions → indexes → query optimisation → Redis → NoSQL → search
SQL is the language; PostgreSQL is how one excellent engine implements it; transactions keep data correct under concurrency; indexes and the planner make it fast; then other stores, each chosen for access patterns the relational model handles less well.
A taste of the project
The lab loaded 2 million orders and fixed four slow queries:
| Query | Before | After | Fix |
|---|---|---|---|
| a customer's 20 most recent orders | 62 ms | 0.12 ms | composite index (customer_id, created DESC) |
| orders on one day | 263 ms | 3.8 ms | range on an indexed column instead of a function on it |
| page 50,000 of all orders | 80 ms | 0.15 ms | keyset pagination instead of OFFSET |
| totals for 100 customers | 16.8 ms | 4.8 ms | one grouped query instead of 100 (N+1) |
Each fix came from reading the query plan and knowing how the engine finds rows, which is exactly what this phase teaches.
How deep to go in Phase 4
Volume 17 defines six mastery levels; Phase 4's exit targets are:
| Topic | Exit level | What that means here |
|---|---|---|
| SQL | L3 | joins, aggregates, window functions, CTEs; reason about results and costs |
| PostgreSQL | L3 | MVCC, VACUUM, WAL, configuration basics |
| transactions | L3 | isolation levels and anomalies; locking |
| indexes and optimisation | L3–L4 | read plans; fix slow queries |
| Redis | L2–L3 | data structures, expiry, persistence trade-offs |
| NoSQL and search | L2–L3 | model by access pattern; inverted indexes, relevance |
The sequence, step by step
| Step | Learn | Read | Exit check |
|---|---|---|---|
| 1 | relational model, normalisation | Vol. 4, Start Here, ch. 55 | design a schema for TiffinBox with keys and constraints |
| 2 | SQL from SELECT to window functions | Vol. 4, ch. 56 | 30 query exercises including window functions |
| 3 | PostgreSQL internals | Vol. 4, ch. 57–58 | explain MVCC and why VACUUM exists |
| 4 | transactions and concurrency | Vol. 4, ch. 59 | reproduce a lost update and a write skew, and fix them |
| 5 | query optimisation | Vol. 4, ch. 60 | fix four slow queries from their plans (the lab) |
| 6 | scaling: replicas, partitioning, pooling | Vol. 4, ch. 61 | explain read-your-writes with replicas |
| 7 | Redis and caching | Vol. 3, ch. 53; Vol. 4, ch. 62 | a cache-aside layer with expiry and a stampede guard |
| 8 | NoSQL models | Vol. 4, ch. 62 | model one feature in a document store and compare |
| 9 | search | Vol. 4, ch. 63 | full-text search with ranking and typo handling |
| 10 | durability and backups | Vol. 4, ch. 64 | restore a backup to a point in time |
Entry check
Phase 3's exit criteria, or at least: a backend application that stores data through an ORM or JDBC, and basic SQL (select, insert, update, simple joins).
The phase project: build and optimise a data-heavy application
Goal. An application whose data is big enough to be slow if done carelessly (millions of rows), made fast and correct.
Milestones. Schema with constraints and migrations → a data generator (millions of realistic rows) → the application's ten most important queries → baseline timings and plans → indexes and rewrites, each justified by a plan → keyset pagination → a Redis cache for one hot read path with a measured hit rate → full-text search for one feature → backups with a timed restore.
Done when. Every important query has a before/after plan and timing; p95 of the main endpoints is under an agreed target (e.g. 50 ms) at the generated data size; a concurrency test shows no anomalies in the money-touching paths; a restore has been timed.
Stretch. Partition the largest table by month and measure maintenance and query effects.
Common traps
- Indexing everything: every index slows writes and costs space; index for real queries.
- Trusting the ORM's SQL without reading it.
OFFSETpagination on large tables.- Caching before measuring, and caching without an invalidation story.
- Choosing NoSQL for "flexibility" without knowing the access patterns.
Exit criteria
- [ ] I can read an
EXPLAIN (ANALYZE, BUFFERS)plan and say why it's slow. - [ ] I can explain each isolation level's anomalies and pick one for a use case.
- [ ] The project's important queries all have measured before/after improvements.
- [ ] I can say when to use Redis, a document store or a search engine, and when not to.
- [ ] I scored at least 80% on 40 questions from Volume 4's quizzes, twice.
Time budget
Volume 4 is about 64,000 words (under 5 hours of reading) plus the caching chapter; with practice, about 20 hours, plus 2–3 weeks for the project: about 6–7 weeks at 8 hours a week.
Lab: four slow queries on 2 million rows
Setup. PostgreSQL 16 on the lab machine; c200 with 50,000 customers and o200 with 2,000,000 orders (random customer, a timestamp within the last year, amount, status), analysed. Each query timed as the mean of 5 runs after a warm-up, data cached in memory.
Experiment 1: the access path
"The 20 most recent orders for customer 4242":
| Indexes | Time | Plan (top node) |
|---|---|---|
| primary key only | 62.04 ms | Limit over a sort of a (parallel) sequential scan of 2 M rows |
(customer_id) |
0.16 ms | index scan, then sort ~40 rows |
(customer_id, created DESC) |
0.12 ms | Limit over an index scan that returns rows already in order |
500× faster with an index that matches the query's filter and its order.
Experiment 2: functions on indexed columns
"How many orders were placed on one day?" with an index on created:
| Predicate | Time |
|---|---|
date_trunc('day', created) = date_trunc('day', now() - interval '3 days') |
262.81 ms |
created >= <day start> AND created < <next day start> |
3.80 ms |
The index holds created, not date_trunc('day', created), so the first form scanned everything. Rewrite as a range (or create an expression index if you must filter on the function).
Experiment 3: deep pagination
| Page (20 rows) | ORDER BY id LIMIT 20 OFFSET n |
keyset: WHERE id > last_id ORDER BY id LIMIT 20 |
|---|---|---|
| 1 | 0.12 ms | 0.12 ms |
| 1,000 | 1.67 ms | 0.10 ms |
| 50,000 | 79.77 ms | 0.15 ms |
OFFSET reads and discards every earlier row, so cost grows with page number; keyset seeks straight to the position. Keyset can't jump to an arbitrary page number, which is usually fine (infinite scroll, "next page", exports).
Experiment 4: N+1
Order count and total for 100 customers:
| Approach | Time |
|---|---|
| 100 queries, one per customer (what a loop over lazy-loaded relations does) | 16.8 ms |
one GROUP BY customer_id … WHERE customer_id = ANY($1) |
4.8 ms |
On one machine the gap is 3.5×; add a 1 ms network round trip per query, typical between an app and a managed database, and the N+1 version becomes ~117 ms against ~6 ms.
Try it yourself
- Run
EXPLAIN (ANALYZE, BUFFERS)for each "before" query and find the line that explains the time. - Create an expression index on
date_trunc('day', created); is it a better fix than the range rewrite? - Add a covering index (
INCLUDE (amount)) for Experiment 1 and check for an index-only scan. - Put 1 ms of latency between the app and database with Toxiproxy and rerun Experiment 4.
Revision sheet: Phase 4, data
Key ideas
- Sequence: SQL → PostgreSQL → transactions → indexes → optimisation → Redis → NoSQL → search.
- Indexes must match the query's filter and order; functions on columns hide indexes.
- Read plans before changing anything; measure before and after.
- Keyset pagination for deep pages; batch or join instead of N+1.
- Other stores are chosen by access pattern, with a consistency and invalidation story.
Numbers to remember
- Lab: 62 ms → 0.12 ms with
(customer_id, created DESC); 263 ms → 3.8 ms with a range; OFFSET page 50,000 80 ms vs keyset 0.15 ms; N+1 16.8 ms vs 4.8 ms. - Budget: ~20 study hours + 2–3 project weeks ≈ 6–7 weeks at 8 h/week.
Pitfalls
- Over-indexing; never reading ORM-generated SQL.
- OFFSET on big tables.
- Caching without invalidation.
- NoSQL for vague "flexibility".
Glossary
- Composite index: an index on several columns in order.
- Expression index: an index on a computed expression.
- Keyset pagination: seeking by the last seen key.
- Covering index: an index containing all columns a query needs.
- Cache-aside: the application reads the cache, falls back to the database and fills the cache.