RecapsKayavak

Kayavak / Recaps / Databases

Recaps · Volume 4

Databases

The revision sheet of every chapter, on one page: the key ideas, the numbers worth knowing, the pitfalls and the words. Use it before an interview, after a chapter, or to find which chapter to reread. Each title opens its chapter; below each sheet are its exercises, companion and TiffinBox stage, and the misconceptions the companion corrects.

Open the volume

55

The Relational Model

Key ideas

  • Relational model (Codd, 1970): data as relations (sets of tuples) with typed attributes; data independence from physical storage; declarative queries.
  • Keys: candidate keys, the chosen primary key, surrogate vs natural keys, composite keys; UNIQUE for alternate keys.
  • Relationships: one-to-many (foreign key on the many side), many-to-many (junction table), one-to-one.
  • Integrity: NOT NULL, UNIQUE, CHECK, FOREIGN KEY with referential actions (RESTRICT, NO ACTION, CASCADE, SET NULL, SET DEFAULT), exclusion constraints, deferrable constraints.
  • NULL: unknown, three-valued logic; IS [NOT] DISTINCT FROM; aggregates skip NULLs; NOT IN pitfall.
  • Normal forms: 1NF (atomic values), 2NF (no partial dependency on a composite key), 3NF/BCNF (every determinant is a key), 4NF/5NF (multi-valued and join dependencies); anomalies as the motivation.
  • Denormalisation: deliberate redundancy (snapshots like order-time prices, caches, read models, materialised views) with a mechanism to keep it correct.
  • Types: integers for counts and ids (bigint for growth), numeric or integer minor units for money, timestamptz for instants, text with checks, uuid (prefer v7), jsonb for genuinely schemaless parts, enums vs lookup tables.

Numbers to remember

  • Lab: one NULL made NOT IN return nothing; a million float additions of 0.10 drifted by 3×10⁻⁷; an unindexed foreign key made a cascading delete 47× slower; UUIDv4 keys loaded about 2× slower than a monotonic UUIDv7 with a 26% larger index.
  • int max ≈ 2.1 billion; row header 23 bytes; uuid 16 bytes, bigint 8.

Pitfalls

  • Spreadsheet-shaped tables; comma-separated lists in a column; entity-attribute-value designs.
  • Natural keys that change; missing UNIQUE on real-world identifiers.
  • Nullable columns by default; NOT IN with nullable subqueries.
  • Floats for money; timestamp without time zone for events; int ids that overflow.
  • Foreign keys without indexes; ON DELETE CASCADE on large or important hierarchies.
  • Denormalising without a plan to keep copies consistent.

Glossary

  • Relation / tuple / attribute: table / row / column, in the model's terms.
  • Functional dependency: A → B when A's value determines B's.
  • Candidate key: a minimal set of attributes that uniquely identifies rows.
  • Junction table: a table representing a many-to-many relationship.
  • Referential action: what happens to children when a parent is deleted or updated.
  • Three-valued logic: true, false and unknown.

56

SQL from SELECT to Window Functions

Key ideas

  • Declarative: describe the result; the planner chooses the method. Logical evaluation order: FROM/JOIN → WHERE → GROUP BY → HAVING → SELECT (window functions) → DISTINCT → ORDER BY → LIMIT/OFFSET.
  • Joins: inner, left/right/full outer, cross, self, semi (EXISTS, IN), anti (NOT EXISTS), LATERAL; ON vs WHERE conditions for outer joins; USING and NATURAL (avoid the latter).
  • Aggregation: count(*) vs count(col) vs count(DISTINCT col), FILTER (WHERE …), GROUPING SETS, ROLLUP, CUBE; fan-out from joining several one-to-many relationships.
  • Subqueries and CTEs: scalar, correlated, derived tables; CTEs (inlined by default since PostgreSQL 12, MATERIALIZED to force); recursive CTEs for trees and graphs.
  • Window functions: PARTITION BY, ORDER BY, frames (ROWS/RANGE/GROUPS), ranking (row_number, rank, dense_rank), offset (lag, lead, first_value), running aggregates.
  • Set operations: UNION (dedupes) vs UNION ALL, INTERSECT, EXCEPT.
  • Modifying data: INSERT … ON CONFLICT (upsert), MERGE, UPDATE … FROM, DELETE … USING, RETURNING.
  • PostgreSQL extras: DISTINCT ON, arrays, jsonb operators, generate_series, FILTER, full-text search.

Numbers to remember

  • Lab: a misplaced WHERE dropped 1,000 of 10,000 customers; double fan-out inflated revenue 3.3×; a correlated running total was 748× slower than a window function; LATERAL with an index was 4× faster for latest-per-group.

Pitfalls

  • Filtering the optional side of an outer join in WHERE.
  • Summing parent values after joining children (fan-out); count(*) after outer joins.
  • NOT IN with NULLs; = NULL instead of IS NULL.
  • SELECT * in application queries; ORDER BY missing for LIMIT or pagination.
  • Correlated subqueries where joins or windows would do; UNION where UNION ALL is meant.
  • Gaps in time series from grouping only existing values.

Glossary

  • Join predicate: the condition pairing rows from two tables.
  • Fan-out: row multiplication from joining a one-to-many relationship.
  • Semi-join / anti-join: keep rows with / without a match, without duplicating them.
  • Window frame: the rows around the current row a window function uses.
  • CTE: common table expression, a named subquery.
  • LATERAL: a subquery that can reference columns from earlier tables in the FROM clause.

57

PostgreSQL in Depth

Key ideas

  • Architecture: postmaster, one backend process per connection, background processes (checkpointer, background writer, WAL writer, autovacuum, WAL sender/receiver), shared buffers plus the OS page cache, per-backend work_mem.
  • Logical layout: cluster → databases → schemas (search_path) → tables; roles with privileges and default privileges; row-level security policies; extensions.
  • Planner: statistics from ANALYZE (pg_stats: null fraction, distinct values, most common values, histograms, correlation), extended statistics, cost parameters; EXPLAIN (ANALYZE, BUFFERS).
  • MVCC: tuple versions with xmin/xmax, snapshots, dead tuples; HOT updates and fill factor; VACUUM (dead space, visibility map, freezing), autovacuum tuning; transaction ID wraparound and anti-wraparound vacuums.
  • WAL: write-ahead logging, checkpoints (checkpoint_timeout, max_wal_size), full-page writes, synchronous_commit levels, crash recovery.
  • Replication: physical streaming (async, sync, remote_apply), replication slots, hot standby conflicts; logical replication (publications, subscriptions) for upgrades and selective sync.
  • Partitioning: declarative range/list/hash, partition pruning, detaching for retention.
  • Versions: 17 (incremental backup, vacuum memory), 18 (async I/O, skip scan, uuidv7(), temporal constraints, OAuth, checksums default), 19 (in release candidate, GA planned 19 November 2026: REPACK, parallel autovacuum index vacuuming, EXPLAIN (IO), WAIT FOR LSN).

Numbers to remember

  • Lab: four full updates grew a table from 27 MB to 135 MB; an open snapshot left 200,000 dead tuples unremovable; fill factor 70 made 100% of non-indexed updates HOT; synchronous_commit=off gave 1.8× TPS; a new connection per transaction cut read throughput 95×; an async replica returned stale data for 199 of 200 immediate reads.
  • Defaults: shared_buffers 128 MB, max_connections 100, page 8 KB, autovacuum_vacuum_scale_factor 0.2.

Pitfalls

  • Long-running or idle-in-transaction sessions; abandoned replication slots (WAL fills the disk).
  • Too many direct connections; no pooler.
  • Default autovacuum settings on large, hot tables; VACUUM FULL as routine maintenance.
  • Indexing frequently updated columns needlessly; ignoring HOT ratios.
  • Reading from replicas without read-your-writes handling.
  • Ignoring wraparound warnings; skipping ANALYZE after bulk loads.

Glossary

  • Backend: the server process serving one connection.
  • Tuple / row version: one physical version of a row.
  • Dead tuple: a version no snapshot can see any more.
  • HOT update: an update that stays on the same page and skips index maintenance.
  • LSN: log sequence number, a position in the WAL.
  • Replication slot: a server-side record that retains WAL until a consumer has received it.

58

Storage Engine Internals

Key ideas

  • Pages: fixed-size blocks (8 KB PostgreSQL, 16 KB InnoDB, 4 KB SQLite) with headers, line pointers and tuples; heap (unordered) vs clustered (InnoDB stores rows in the primary-key B-tree); TOAST for large values; alignment and padding.
  • B-trees: sorted, balanced, high fan-out; leaf pages linked for range scans; page splits; deduplication (PostgreSQL 13+); covering indexes (INCLUDE); index-only scans and the visibility map.
  • Other indexes: hash, GIN (inverted: arrays, jsonb, full text, trigrams), GiST/SP-GiST (geometry, ranges, nearest neighbour), BRIN (block ranges), partial and expression indexes.
  • Buffer management: shared buffers plus the OS page cache (double buffering in PostgreSQL), clock-sweep eviction, dirty pages written by the background writer and checkpointer.
  • WAL and recovery: log before data, full-page writes after checkpoints, redo on crash; InnoDB's redo and undo logs and doublewrite buffer.
  • LSM-trees: memtable + WAL, flushes to immutable SSTables, levelled or tiered compaction, Bloom filters, tombstones; read, write and space amplification trade-offs (RUM conjecture).
  • Column stores: column-wise pages, compression, vectorised execution (chapter 62).

Numbers to remember

  • Lab: a B-tree held 10 million keys in 3 levels; interleaved booleans and bigints wasted 28% of a table; a BRIN index was 6,700× smaller than a B-tree but slower than no index on random data; RocksDB took random writes 10× faster than SQLite's B-tree and served point reads 1.7× slower.
  • Row header 23–24 bytes; B-tree fan-out ≈ 300–400 for bigint keys.

Pitfalls

  • Assuming the heap is ordered (it isn't; use ORDER BY).
  • B-tree indexes on everything; BRIN on unordered data.
  • Ignoring padding in wide tables; storing large blobs in hot tables.
  • Random-key inserts into large B-trees (UUIDv4).
  • Choosing an LSM store for read-heavy, latency-sensitive workloads without measuring; ignoring compaction capacity.

Glossary

  • Heap: a table's unordered row storage.
  • Fan-out: the number of children per B-tree page.
  • Page split: dividing a full B-tree page when inserting.
  • Memtable / SSTable: an LSM's in-memory buffer / immutable sorted file.
  • Compaction: merging LSM files and discarding obsolete entries.
  • Write amplification: bytes written to storage per byte written by the application.

59

Transactions and Concurrency Control

Key ideas

  • ACID: atomicity (all or nothing, via WAL/undo), consistency (constraints), isolation (concurrency control), durability (flushed log).
  • Anomalies: dirty read, non-repeatable read, phantom, lost update, read skew, write skew, serialization anomalies.
  • Levels: Read Committed (snapshot per statement; PostgreSQL default), Repeatable Read (snapshot isolation; detects write-write conflicts), Serializable (SSI; detects read-write dependency cycles); MySQL InnoDB defaults to Repeatable Read with gap locks.
  • Mechanisms: two-phase locking, MVCC snapshots, first-committer/updater-wins, SSI predicate (SIREAD) locks, optimistic concurrency with version columns.
  • Locks: row locks (FOR UPDATE, FOR NO KEY UPDATE, FOR SHARE, SKIP LOCKED, NOWAIT), table lock modes (ACCESS SHARE … ACCESS EXCLUSIVE), lock queues, advisory locks, deadlock detection.
  • Practice: atomic updates, consistent lock ordering, short transactions, retries for 40001/40P01, lock_timeout and statement_timeout, idle_in_transaction_session_timeout, safe migrations.
  • Distributed transactions: two-phase commit, sagas (Volume 5).

Numbers to remember

  • Lab: write skew left zero cooks on duty at Read Committed and Repeatable Read, one at Serializable; Serializable retried 8–29% of attempts depending on contention; a deadlock cost about deadlock_timeout (1 s); an ALTER TABLE waiting behind a 2.3 s transaction blocked all readers for 2 s.
  • SQLSTATE: 40001 serialization failure, 40P01 deadlock, 55P03 lock not available.

Pitfalls

  • Read-modify-write in application code without locks or versions.
  • Assuming Repeatable Read prevents write skew.
  • Serializable without retry loops; long transactions under Serializable.
  • Inconsistent lock order; user interaction or remote calls inside transactions.
  • Migrations without lock_timeout; long-running reports on the primary during deploys.

Glossary

  • Snapshot: the set of committed transactions a statement or transaction can see.
  • Write skew: two transactions read overlapping data and write disjoint rows, jointly violating a rule.
  • Serialization failure: an abort raised to preserve the isolation guarantee.
  • Deadlock: a cycle of transactions waiting for each other's locks.
  • Lock queue: waiting lock requests, granted in order.
  • SSI: serializable snapshot isolation.

60

Query Optimisation

Key ideas

  • Cost-based planning: enumerate plans (join orders, access paths, join methods), estimate cardinalities from statistics, choose the cheapest; genetic optimiser beyond geqo_threshold tables.
  • Statistics: per-column null fraction, n_distinct, most common values, histograms, correlation; extended statistics (dependencies, ndistinct, MCV); default_statistics_target; ANALYZE after bulk changes.
  • Access paths: sequential scan, index scan, index-only scan (visibility map), bitmap index/heap scan (combining indexes), TID scans; parallel variants.
  • Join methods: nested loop (indexed inner side), hash join (memory: work_mem, batches), merge join (sorted inputs).
  • Other nodes: sort (in memory or external), hash aggregate vs group aggregate, materialise, memoize, gather.
  • Indexing strategy: equality-then-range composite order, covering (INCLUDE), partial indexes (WHERE status = 'NEW'), expression indexes, operator classes (text_pattern_ops, trigram GIN), avoiding redundant and unused indexes (pg_stat_user_indexes.idx_scan).
  • Workflow: pg_stat_statements, auto_explain, EXPLAIN (ANALYZE, BUFFERS), estimate vs actual, fix, verify; plan stability (prepared statement generic plans).

Numbers to remember

  • Lab: equality-first composite index 16× faster than range-first (23 vs 960 buffers); a numeric literal against a bigint key made a lookup 1,800× slower; independent-columns assumption underestimated by 200×; index-only scan 55× slower with an outdated visibility map; trigram GIN 87× faster for %x%.

Pitfalls

  • Functions or casts on indexed columns; mismatched parameter types from drivers.
  • Wrong composite column order; indexes on low-selectivity columns alone.
  • Stale statistics after bulk loads; correlated predicates without extended statistics.
  • Testing plans on tiny datasets; reading cost as milliseconds.
  • Too many indexes on write-heavy tables; never dropping unused ones.
  • OFFSET pagination and SELECT * defeating index-only scans.

Glossary

  • Cardinality estimate: predicted number of rows from a plan node.
  • Selectivity: fraction of rows a condition keeps.
  • Index-only scan: answering from the index without visiting the heap.
  • Bitmap scan: collecting matching row locations from indexes, then reading heap pages in order.
  • Covering index: an index containing all columns a query needs.
  • Generic plan: a cached plan for a prepared statement that ignores specific parameter values.

61

Scaling Databases

Key ideas

  • Ladder: optimise → scale up → pool → cache → read replicas → partition → split by function → shard; climb only on measured need.
  • Replication: physical streaming (async, sync, quorum), logical replication; lag and read-your-writes; slots and WAL retention.
  • High availability: RPO (how much data you can lose) and RTO (how long you can be down); automated failover (Patroni, cloud managed services), fencing, split-brain, connection routing (VIPs, proxies, DNS).
  • Partitioning: range/list/hash, pruning, per-partition indexes, retention by detach/drop, partition key in unique constraints.
  • Sharding: shard key choice (high cardinality, even distribution, co-location of related data), hash vs range, directory-based placement, consistent hashing and virtual nodes, hot keys, resharding, cross-shard queries and transactions.
  • Systems: Citus, Vitess (MySQL), distributed SQL (CockroachDB, YugabyteDB, TiDB, Spanner), managed scale-out (Aurora, AlloyDB, Neon's separated storage).
  • CQRS and read models: separate read stores fed by events or CDC when read shapes diverge from the write model.

Numbers to remember

  • Lab: dropping a month partition 85 ms vs DELETE 718 ms plus 669,599 dead rows; mod-N resharding moved 80% of keys vs 20% with consistent hashing; one virtual node per shard gave 26× load imbalance; a 1-second replication stall before failover lost 358,000 acknowledged payments.

Pitfalls

  • Sharding before optimising; choosing a shard key that isn't in most queries.
  • Reading from replicas without lag awareness; assuming async replication loses nothing.
  • Replication slots for dead replicas filling disks; replicas without slots falling irrecoverably behind.
  • Failover without fencing; clients pinned to the old primary.
  • Partitioning without a lifecycle need; queries missing the partition key; default partitions.

Glossary

  • RPO / RTO: recovery point / time objective.
  • Fencing: guaranteeing a failed primary can't accept writes.
  • Partition pruning: skipping partitions a query can't need.
  • Shard key: the value deciding which shard holds a row.
  • Virtual node: one of many ring positions per physical shard.
  • Scatter-gather: querying all shards and merging results.

62

NoSQL Data Models and Stores

Key ideas

  • Why NoSQL: access-pattern-shaped data, flexible schemas, horizontal write scaling, specialised operations; each gives up some of joins, cross-entity transactions, enforced schemas or immediate consistency.
  • Key-value: Redis (data structures, TTLs, Lua, streams; persistence via RDB/AOF; replication and cluster with hash slots), Memcached, etcd, RocksDB as an embedded engine.
  • Document: MongoDB (BSON, embedding vs referencing, indexes including multikey, aggregation pipeline, transactions, replica sets, sharding), Couchbase, Firestore; PostgreSQL jsonb.
  • Wide-column: Cassandra/ScyllaDB (partition and clustering keys, query-first tables, tunable consistency, LSM storage, tombstones), Bigtable/HBase.
  • DynamoDB: partition and sort keys, single-table design, GSIs, capacity modes, conditional writes.
  • Search engines as stores: Elasticsearch/OpenSearch (chapter 63), with caution as a system of record.
  • Graph: property graphs (Cypher, GQL), traversals; SQL/PGQ arriving in relational databases.
  • Analytical: column stores (DuckDB, ClickHouse, warehouses), compression, vectorised execution, Parquet and lakehouse formats.
  • Consistency: replication modes, quorum reads/writes, read/write concerns, eventual consistency and its anomalies.

Numbers to remember

  • Lab: one phone change left 500 stale embedded copies; 10% of documents with a string quantity made a report 10% low silently; Redis rank queries 550× faster than SQL count(*); DuckDB 15× faster and 21× smaller than PostgreSQL for an aggregate over 10M rows.

Pitfalls

  • Choosing NoSQL for scale you don't have; losing integrity you needed.
  • Embedding shared, mutable data; unbounded arrays inside documents (16 MB MongoDB limit).
  • No schema validation; silent type drift.
  • Redis as a durable primary store; cache and durable data in one Redis.
  • Cassandra queries without the partition key; large partitions; tombstone build-up.
  • Running analytics on the OLTP row store at scale; point updates in column stores.

Glossary

  • Access pattern: a specific query or write the application performs.
  • Embedding / referencing: storing related data inside a document / by id.
  • Partition key / clustering key: decides the node / the order within a partition.
  • Quorum: a majority of replicas; overlapping read and write quorums give strong reads.
  • OLTP / OLAP: transactional vs analytical workloads.
  • Vectorised execution: processing batches of column values per operation.

63

Search Engines and Hybrid Search

Key ideas

  • Why separate search: fuzzy matching, relevance ranking, text analysis and speed over large text; databases are optimised for exact predicates.
  • Inverted index: terms → postings (document ids, frequencies, positions); immutable segments merged in the background (Lucene); near-real-time refresh.
  • Analysis: tokenisers, lowercasing, ASCII folding, stop words, stemming vs lemmatisation, n-grams and edge n-grams for autocomplete, language-specific analyzers.
  • Ranking: TF-IDF, BM25 (k1, b), field boosts, function scores (recency, popularity), learning to rank.
  • Features: filters (cached, unscored) vs queries (scored), facets/aggregations, autocomplete, fuzzy matching (edit distance), synonyms, highlighting.
  • Engines: Lucene-based Elasticsearch/OpenSearch/Solr, tantivy/Quickwit, Meilisearch, Typesense, Vespa; PostgreSQL tsvector/GIN and pg_trgm.
  • Semantic search: embedding models, cosine/inner-product similarity, chunking; ANN indexes (HNSW, IVF, product quantisation), recall vs latency.
  • Hybrid: lexical + semantic retrieval, fusion (RRF, weighted scores), reranking with cross-encoders.
  • Evaluation: judged query sets, precision/recall@k, nDCG, MRR; online metrics (click-through, zero-result rate).
  • Architecture: search index as a derived copy, kept in sync by indexing pipelines or CDC; reindexing with aliases.

Numbers to remember

  • Lab: mean nDCG@5 lexical 0.71, semantic 0.66, hybrid 0.77; GIN full-text 64× faster than ILIKE on 500,000 documents, tantivy another 10×; HNSW 0.994 recall@10 at 235× the speed of brute force on 200,000 vectors.

Pitfalls

  • LIKE '%term%' as a search engine; no stemming or typo tolerance.
  • Semantic-only search failing on names, codes and exact attributes.
  • Tuning relevance by anecdote instead of a judged query set.
  • Treating the search index as the source of truth; no reindex plan.
  • ANN defaults without measuring recall on your data; embedding-model changes without re-embedding everything.

Glossary

  • Postings list: the documents containing a term.
  • BM25: the standard probabilistic lexical ranking function.
  • Embedding: a vector representation of text capturing meaning.
  • ANN: approximate nearest-neighbour search.
  • RRF: reciprocal rank fusion, combining rankings by summed 1/(k + rank).
  • nDCG: normalised discounted cumulative gain, a ranking quality metric.

64

Durability, Backups and Recovery

Key ideas

  • Threats: hardware failure, human error, software bugs, corruption, malicious action (ransomware, insiders), regional disasters; replicas cover only the first.
  • Objectives: RPO (data loss tolerance) and RTO (downtime tolerance), per dataset; tested, not assumed.
  • Logical backups: pg_dump/pg_dumpall, formats (-Fc, -Fd parallel), consistent snapshot, portable, slow restore; good for migrations and single objects.
  • Physical backups: pg_basebackup, pgBackRest, Barman, WAL-G; full, differential and incremental (PostgreSQL 17 native incremental); WAL archiving; PITR with recovery targets and timelines.
  • Snapshots: storage/EBS snapshots with pg_backup_start/pg_backup_stop or crash-consistent with WAL on the same volume.
  • Protection of backups: 3-2-1 (three copies, two media, one offsite), immutability (object lock, WORM), encryption with managed keys, separate accounts and credentials.
  • Integrity: data checksums (default from PostgreSQL 18), pg_amcheck, pg_checksums, backup verification (pgbackrest verify, pg_verifybackup).
  • Recovery practice: delayed replicas, scratch restores, runbooks, measured restore drills, retention long enough to predate late-discovered corruption.
  • Other stores: MySQL (binlog PITR, XtraBackup), MongoDB (oplog), Redis (RDB/AOF), managed-service snapshots and PITR windows.

Numbers to remember

  • Lab: a 150 MB database dumped in 2.9 s to 14 MB and restored in 3.8 s; PITR restored 2,001,000 rows to just before a mistaken DELETE in 4.2 s; one flipped byte was caught by checksums on read and during backup; a base backup without WAL wouldn't start.

Pitfalls

  • Treating replicas, RAID or snapshots on the same account as backups.
  • Never restoring; unmonitored archive failures; backups without the WAL they need.
  • Backups in the same blast radius as production (same account, same credentials, same region).
  • Checksums off; retention shorter than the time to discover corruption.
  • Querying a restoring server mid-recovery; recovering over the live database instead of to a scratch copy.

Glossary

  • PITR: point-in-time recovery by replaying archived WAL onto a base backup.
  • Base backup: a physical copy of the data directory plus the WAL needed to make it consistent.
  • Timeline: a branch of WAL history created by recovery or promotion.
  • WAL archiving: copying completed WAL segments to durable storage.
  • Immutable backup: a copy that can't be modified or deleted for a retention period.
  • Restore drill: a regular, measured test of restoring and validating a backup.