@vstlmkh/designing-databases 0.0.0-stage → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,277 @@
1
+ # Indexing
2
+
3
+ Load whenever an index is being added, dropped, reordered, or blamed.
4
+
5
+ ## Contents
6
+
7
+ - What an index costs
8
+ - B+tree mechanics and page splits
9
+ - Composite column order: the ESR rule
10
+ - The leftmost prefix rule, and skip scans
11
+ - Covering indexes and INCLUDE
12
+ - Partial indexes
13
+ - Expression indexes
14
+ - Specialized index types: hash, GIN, BRIN, GiST
15
+ - Finding unused and redundant indexes
16
+ - Index bloat and rebuilding
17
+ - The index maintenance runbook
18
+
19
+ ## What an index costs
20
+
21
+ Every index trades write throughput and memory for read speed. One row insert
22
+ updates *every* index on the table inside the same transaction; one page split
23
+ can write two full pages into the WAL/redo log plus parent modifications. Before
24
+ adding an index, name the query it serves and check whether an existing index can
25
+ be widened instead.
26
+
27
+ Never add an index without checking what it makes redundant, and never drop one
28
+ without checking replica usage.
29
+
30
+ ## B+tree mechanics and page splits
31
+
32
+ Keys live in sorted, fixed-size pages (8 KB PostgreSQL, 16 KB InnoDB). Branch
33
+ pages route; leaf pages hold values plus a row reference, linked horizontally so
34
+ range scans walk sideways without re-descending. With a fanout of ~500, three
35
+ levels address ~125M rows in at most three page reads.
36
+
37
+ The row reference differs by engine, and this is the root of most engine
38
+ divergence:
39
+
40
+ - **InnoDB clustered index**: the leaf page *is* the row. Secondary index leaves
41
+ store the indexed columns followed by the primary key value; a lookup that
42
+ needs other columns does a second descent through the clustered index
43
+ (a "bookmark lookup").
44
+ - **PostgreSQL**: every index is secondary. Leaves store the key plus a 6-byte
45
+ `ctid` (4-byte block number + 2-byte offset) pointing straight at the heap tuple.
46
+
47
+ **Page splits** happen when an insert targets a full leaf page: allocate a page,
48
+ move half the tuples, register the boundary in the parent, and bubble upward if
49
+ the parent is full too. The two costs are write amplification (a 32-byte key can
50
+ force two full pages into the log) and read fragmentation (logically adjacent
51
+ keys end up physically scattered, so range scans do random I/O).
52
+
53
+ Sequential keys avoid this entirely — writes land on the rightmost leaf, which
54
+ fills to 90–99% and is always in cache. `fillfactor` reserves free space per leaf
55
+ page for workloads that update indexed columns in place:
56
+
57
+ ```sql
58
+ CREATE INDEX idx_accounts_balance ON accounts (balance) WITH (fillfactor = 70);
59
+ ```
60
+
61
+ ## Composite column order: the ESR rule
62
+
63
+ Order composite index columns **Equality, Sort, Range**:
64
+
65
+ 1. **Equality** (`=`, `IN` with few values) first — these narrow the tree.
66
+ 2. **Sort** (`ORDER BY`) next — the engine then reads leaves in order and skips
67
+ the sort node entirely.
68
+ 3. **Range** (`<`, `>`, `BETWEEN`) last — tree navigation *stops* at the first
69
+ range column; everything after it is only a filter applied per entry.
70
+
71
+ ```sql
72
+ -- Query
73
+ SELECT id, account_id, created_at, status
74
+ FROM transactions
75
+ WHERE account_id = 9182
76
+ AND status IN ('PENDING','FLAGGED')
77
+ AND created_at >= '2025-01-01'
78
+ ORDER BY created_at DESC;
79
+
80
+ -- Violates ESR: range column first; engine filters account_id row by row
81
+ CREATE INDEX idx_bad ON transactions (created_at, account_id, status);
82
+
83
+ -- ESR: two equality seeks, then a contiguous ordered range read
84
+ CREATE INDEX idx_good ON transactions (account_id, status, created_at DESC);
85
+ ```
86
+
87
+ With `(tenant_id, created_at, status)` the engine seeks `tenant_id`, then reads
88
+ *every* leaf entry from the date boundary onward checking `status` by hand. With
89
+ `(tenant_id, status, created_at)` it descends on both equality columns and reads
90
+ only matching timestamps — zero wasted entries.
91
+
92
+ Direction matters for sorts: a single index can serve `ORDER BY a, b DESC` only
93
+ if it was declared that way (`CREATE INDEX … (a, b DESC)`) or the engine can walk
94
+ it backwards for *all* columns at once.
95
+
96
+ ## The leftmost prefix rule, and skip scans
97
+
98
+ An index on `(org_id, status, amount)` serves:
99
+
100
+ - `WHERE org_id = ?` — full seek
101
+ - `WHERE org_id = ? AND status = ?` — full seek
102
+ - `WHERE org_id = ? AND amount = ?` — seeks `org_id`, then filters every leaf
103
+ entry in that range for `amount` (prefix seek with leaf filter)
104
+ - `WHERE status = ?` — **cannot navigate the tree at all**; sequential scan or
105
+ full index scan
106
+
107
+ MySQL 8.0+ can sometimes use an *index skip scan*: when the leading column has
108
+ very low cardinality, it decomposes the query into one seek per distinct leading
109
+ value. It only pays off for a handful of distinct values; with thousands it is
110
+ worse than a table scan. Do not design for it — design the column order right.
111
+
112
+ ## Covering indexes and INCLUDE
113
+
114
+ A covering index holds every column the query touches (`SELECT`, `WHERE`, `JOIN`,
115
+ `GROUP BY`, `ORDER BY`), so the engine never visits the table. The win is
116
+ avoiding random heap I/O: 200,000 matching rows scattered over a 50 GB table can
117
+ mean 200,000 random page reads even though the index seek took under 1 ms.
118
+
119
+ Do **not** stuff payload columns into the key — key columns live in every branch
120
+ page, lowering fanout and deepening the tree. Use `INCLUDE` (PostgreSQL 11+, SQL
121
+ Server; MySQL gets covering for free because secondary leaves already carry the PK):
122
+
123
+ ```sql
124
+ CREATE INDEX idx_invoices_covering
125
+ ON invoices (customer_id, status) -- navigable, sorted
126
+ INCLUDE (total, issued_at); -- leaf-only payload
127
+
128
+ -- Uniqueness is enforced on key columns only
129
+ CREATE UNIQUE INDEX idx_users_email ON users (email) INCLUDE (first_name, avatar_url);
130
+ ```
131
+
132
+ **PostgreSQL caveat**: an `Index Only Scan` still consults the visibility map.
133
+ If autovacuum has not cleaned a heap page since its last write, the bit is clear
134
+ and the engine reads the heap anyway — visible in the plan as `Heap Fetches`.
135
+ High heap fetches mean "vacuum is behind", not "add another index".
136
+
137
+ ## Partial indexes
138
+
139
+ Index only the rows queries actually touch. On a task queue where 99.5% of rows
140
+ are `COMPLETED`:
141
+
142
+ ```sql
143
+ CREATE INDEX idx_pending_tasks
144
+ ON task_queue (tenant_id, created_at)
145
+ WHERE status IN ('QUEUED','PROCESSING');
146
+ ```
147
+
148
+ Typical effect: 50M rows → 25k entries, ~3.2 GB → ~1.8 MB, and inserts of
149
+ completed rows stop touching the index at all.
150
+
151
+ The planner uses a partial index only when it can **prove** the query predicate
152
+ implies the index predicate:
153
+
154
+ ```sql
155
+ WHERE tenant_id = 14 AND status = 'QUEUED' -- matches
156
+ WHERE tenant_id = 14 -- does NOT match
157
+ WHERE tenant_id = 14 AND status != 'COMPLETED' -- does NOT match ('FAILED' exists)
158
+ ```
159
+
160
+ Also use partial unique indexes for "unique among live rows" and partial indexes
161
+ on nullable flags.
162
+
163
+ ## Expression indexes
164
+
165
+ The B-tree stores raw values, so wrapping the column in a function in the query
166
+ makes the index unusable. Index the expression instead, and call it with the
167
+ identical signature in the query:
168
+
169
+ ```sql
170
+ CREATE INDEX idx_audit_date ON audit_records ((DATE(created_at)));
171
+ CREATE INDEX idx_users_lemail ON users ((LOWER(email)));
172
+ CREATE INDEX idx_orders_tier ON orders (((metadata->'customer'->>'tier')));
173
+ ```
174
+
175
+ Cost: the function runs on every insert and update of that row. Expensive
176
+ expressions (regex, hashes) show up directly as write latency. Prefer fixing the
177
+ query to be sargable (a half-open range instead of `DATE()`), and reach for an
178
+ expression index only when the transformation is genuinely required.
179
+
180
+ ## Specialized index types: hash, GIN, BRIN, GiST
181
+
182
+ | Type | Good for | Cannot do |
183
+ |---|---|---|
184
+ | **B-tree** (default) | equality, ranges, sorting, prefix `LIKE 'abc%'` | containment, full-text, leading wildcards |
185
+ | **Hash** (`USING HASH`) | O(1) equality on long random strings: API keys, session tokens, hashes | ranges, `ORDER BY`, `LIKE`, multi-column |
186
+ | **GIN** | arrays, `JSONB` containment (`@>`), full-text `tsvector`; one row → many leaf entries | ranges; writes are expensive (buffered by `fastupdate=on`) |
187
+ | **BRIN** | huge append-only tables whose physical order matches the column (time series, sequential IDs): ~1.5–10 MB where a B-tree needs 11–25 GB | anything with random physical order — overlapping block ranges degrade it to a full scan |
188
+ | **GiST** | geometry, ranges, `EXCLUDE` constraints, nearest-neighbour | — |
189
+
190
+ ```sql
191
+ CREATE INDEX idx_sessions_token ON user_sessions USING HASH (token);
192
+ CREATE INDEX idx_documents_tags ON documents USING GIN (tags);
193
+ CREATE INDEX idx_telemetry_brin ON telemetry_data USING BRIN (recorded_at);
194
+ ```
195
+
196
+ BRIN stores only min/max per range of 128 blocks (1 MB). It is unbeatable on
197
+ append-only time-series and useless the moment rows arrive out of order.
198
+
199
+ ## Finding unused and redundant indexes
200
+
201
+ ```sql
202
+ -- PostgreSQL: never-scanned, non-unique indexes, largest first
203
+ SELECT schemaname || '.' || relname AS table_name,
204
+ indexrelname AS index_name,
205
+ idx_scan AS scans,
206
+ pg_size_pretty(pg_relation_size(indexrelid)) AS size
207
+ FROM pg_stat_user_indexes
208
+ JOIN pg_index USING (indexrelid)
209
+ WHERE indisunique IS FALSE AND idx_scan = 0
210
+ ORDER BY pg_relation_size(indexrelid) DESC;
211
+ ```
212
+
213
+ ```sql
214
+ -- MySQL (sys schema)
215
+ SELECT * FROM sys.schema_unused_indexes;
216
+ SELECT * FROM sys.schema_redundant_indexes;
217
+ ```
218
+
219
+ Judge "unused" over a full business cycle — 30 to 60 days, so monthly reporting
220
+ is included — and check **read replicas separately**: an index idle on the
221
+ primary may serve every analytics query on a replica.
222
+
223
+ Redundancy follows from the leftmost prefix rule: given
224
+ `idx_1 (company_id)` and `idx_2 (company_id, created_at, status)`, `idx_1` is
225
+ dead weight — `idx_2` serves the same lookups and `idx_1` taxes every insert.
226
+
227
+ ## Index bloat and rebuilding
228
+
229
+ Updates and deletes leave dead slots in leaf pages that are only reusable by keys
230
+ landing in the same gap, so trees grow and deepen over time.
231
+
232
+ ```sql
233
+ CREATE EXTENSION IF NOT EXISTS pgstattuple;
234
+ SELECT tuple_count, dead_tuple_count, free_space, free_percent
235
+ FROM pgstatindex('idx_payments_org_status_amount');
236
+ ```
237
+
238
+ Above ~35–40% free space on a low-update table, rebuild:
239
+
240
+ ```sql
241
+ REINDEX INDEX CONCURRENTLY idx_payments_org_status_amount; -- never plain REINDEX in prod
242
+ ```
243
+
244
+ Plain `REINDEX` takes `ACCESS EXCLUSIVE`. The concurrent form builds a duplicate
245
+ and swaps atomically — budget up to 2x the index size in free disk. In MySQL,
246
+ `OPTIMIZE TABLE payments;` rebuilds the table and its indexes (online in
247
+ InnoDB, but it rewrites everything — treat it as a maintenance-window operation).
248
+
249
+ ## The index maintenance runbook
250
+
251
+ 1. **Capture the workload.** `pg_stat_statements` ordered by `total_exec_time`,
252
+ or the MySQL slow log / `performance_schema`.
253
+ 2. **Get the plan.** `EXPLAIN (ANALYZE, BUFFERS)` on the offender. Look for
254
+ `Seq Scan`, `Rows Removed by Filter`, `Heap Fetches`, and `shared read`.
255
+ 3. **Design the index**: equality columns → sort/range columns → `INCLUDE`
256
+ payload. Prefer widening an existing index over adding a new one.
257
+ 4. **Build it without locking.**
258
+ ```sql
259
+ CREATE INDEX CONCURRENTLY idx_optimized_events
260
+ ON events (org_id, region, created_at) INCLUDE (payload_summary);
261
+ ```
262
+ ```sql
263
+ ALTER TABLE events ADD INDEX idx_optimized_events (org_id, region, created_at),
264
+ ALGORITHM=INPLACE, LOCK=NONE; -- MySQL 8
265
+ ```
266
+ 5. **Verify the build succeeded.** A failed `CONCURRENTLY` build leaves an
267
+ invalid index that still slows writes:
268
+ ```sql
269
+ SELECT relname, indisvalid FROM pg_index i
270
+ JOIN pg_class c ON c.oid = i.indexrelid WHERE relname = 'idx_optimized_events';
271
+ -- indisvalid = false → DROP INDEX CONCURRENTLY and retry
272
+ ```
273
+ 6. **Re-measure.** Same query, same plan command; confirm the node changed and
274
+ buffer reads dropped. Check that the new index did not evict hot data from
275
+ the buffer pool.
276
+ 7. **Prune.** Drop the indexes the new one makes redundant — after confirming
277
+ zero scans on the primary *and* every replica: `DROP INDEX CONCURRENTLY …`.
@@ -0,0 +1,127 @@
1
+ # Working against a live database
2
+
3
+ Load when a database is reachable — local container, staging, replica, or (with
4
+ care) production.
5
+
6
+ ## Contents
7
+
8
+ - Safety rules
9
+ - Finding the connection
10
+ - Opening a read-only session
11
+ - What to collect before advising
12
+ - Reading the snapshot output
13
+ - Capturing a plan for the script
14
+ - Escalating to a write
15
+
16
+ ## Safety rules
17
+
18
+ 1. **Read-only by default.** Open every session read-only and with timeouts
19
+ before running anything.
20
+ 2. **`EXPLAIN ANALYZE` executes the statement.** For `INSERT`/`UPDATE`/`DELETE`,
21
+ wrap it: `BEGIN; EXPLAIN (ANALYZE, BUFFERS) UPDATE …; ROLLBACK;`
22
+ 3. **Nothing that writes, locks or kills runs without explicit approval** — DDL,
23
+ DML, `VACUUM FULL`, `OPTIMIZE TABLE`, index creation,
24
+ `pg_terminate_backend`/`KILL`. Show the exact statement and its lock level,
25
+ then ask.
26
+ 4. **Prefer a replica or a staging copy with production-like volume.** Say which
27
+ one the numbers came from; a plan from a 1000-row dev table proves nothing.
28
+ 5. **Never echo credentials** into the transcript or into a file. Read them from
29
+ the environment, `~/.pgpass`, `~/.my.cnf`, or the project's secret tooling.
30
+ 6. **Bound every query.** `LIMIT` on exploratory selects, `statement_timeout` on
31
+ the session; catalog queries on huge schemas can themselves be slow.
32
+
33
+ ## Finding the connection
34
+
35
+ Look, in order: `.env` / `.env.example`, `docker-compose.yml`, `config/*.php`,
36
+ `settings.py`, `knexfile.ts`, `ormconfig`, `alembic.ini`, CI secrets listings,
37
+ `~/.pgpass`, `~/.my.cnf`. Prefer an existing read-only role if the project has
38
+ one. If the only reachable database is production, say so and get approval for
39
+ the session before connecting.
40
+
41
+ ## Opening a read-only session
42
+
43
+ ```bash
44
+ # PostgreSQL — timeouts and read-only enforced server-side for this session
45
+ psql "$DATABASE_URL" -X -v ON_ERROR_STOP=1 \
46
+ -c "SET default_transaction_read_only = on;
47
+ SET statement_timeout = '30s';
48
+ SET lock_timeout = '2s';
49
+ SET idle_in_transaction_session_timeout = '10s';"
50
+ ```
51
+
52
+ ```bash
53
+ # MySQL
54
+ mysql --defaults-file=~/.my.cnf -e "
55
+ SET SESSION TRANSACTION READ ONLY;
56
+ SET SESSION max_execution_time = 30000;
57
+ SET SESSION lock_wait_timeout = 3;"
58
+ ```
59
+
60
+ For scripted output that is easy to parse: `psql -XAt -F $'\t'` or
61
+ `mysql -N -B`.
62
+
63
+ ## What to collect before advising
64
+
65
+ Run the bundled packs rather than inventing catalog queries:
66
+
67
+ ```bash
68
+ psql "$DATABASE_URL" -X -f assets/pg_snapshot.sql > /tmp/pg_snapshot.txt
69
+ mysql --defaults-file=~/.my.cnf db < assets/mysql_snapshot.sql > /tmp/my_snapshot.txt
70
+ ```
71
+
72
+ Each pack gathers, in one pass: version and key settings, database and table
73
+ sizes, row-count estimates, index inventory with sizes and scan counts, unused
74
+ and redundant indexes, foreign keys missing a child index, dead-tuple / bloat
75
+ indicators, long-running and blocking sessions, and the top statements by total
76
+ time. That is the evidence base for every recommendation that follows.
77
+
78
+ Both packs are read-only and safe on a replica. `pg_stat_statements` and the
79
+ MySQL `sys` schema must be installed; the packs degrade gracefully with a notice
80
+ if they are not.
81
+
82
+ ## Reading the snapshot output
83
+
84
+ - **Settings first.** `shared_buffers`, `work_mem`, `random_page_cost`,
85
+ `effective_cache_size`, `max_connections` (PostgreSQL);
86
+ `innodb_buffer_pool_size`, `innodb_flush_log_at_trx_commit`, `sort_buffer_size`
87
+ (MySQL). A default `random_page_cost = 4` on SSD explains a lot of "the planner
88
+ ignores my index" reports before you look at a single query.
89
+ - **Size before cleverness.** If the working set fits in RAM, I/O-shaped advice
90
+ is noise; if the hot table is 40x the buffer pool, index size *is* the problem.
91
+ - **Statements by total time**, not by worst case — that is where capacity goes.
92
+ - **Dead tuples and the oldest transaction** tell you whether you are looking at
93
+ a query problem or a vacuum problem.
94
+ - **Unused indexes** are write tax; check replicas before proposing a drop.
95
+
96
+ ## Capturing a plan for the script
97
+
98
+ ```bash
99
+ psql "$DATABASE_URL" -X -At -c \
100
+ "EXPLAIN (ANALYZE, BUFFERS, SETTINGS, FORMAT JSON) SELECT …" > /tmp/plan.json
101
+ python3 scripts/explain_audit.py /tmp/plan.json
102
+ ```
103
+
104
+ ```bash
105
+ mysql -N -B -e "EXPLAIN FORMAT=JSON SELECT …" db > /tmp/plan.json
106
+ python3 scripts/explain_audit.py /tmp/plan.json # MySQL subset of checks
107
+ ```
108
+
109
+ Run the query twice and report the second run when you want the warm-cache
110
+ number, or report both — a cold first run and a warm second run answer different
111
+ questions.
112
+
113
+ ## Escalating to a write
114
+
115
+ When a change is actually required, present it as a block the user can approve
116
+ as a unit:
117
+
118
+ ```
119
+ Statement: CREATE INDEX CONCURRENTLY idx_orders_tenant_created ON orders (tenant_id, created_at);
120
+ Lock: ShareUpdateExclusive (writes continue; blocks other DDL on the table)
121
+ Expected: ~4 min on 52M rows; +1.8 GB disk
122
+ Rollback: DROP INDEX CONCURRENTLY idx_orders_tenant_created;
123
+ Risk: build failure leaves an invalid index — verify pg_index.indisvalid after
124
+ ```
125
+
126
+ Then wait for an explicit yes. Apply one change at a time and re-measure after
127
+ each.