what indexes cost
every index is another write, more WAL and fewer HOT updates. finding the ones nobody uses.
- address
- everything.indexes.index_costs
- part
- part 8, indexes, from the outside
- chapter
- chapter 10 of 12
- reading time
- 7 min
an index makes some reads faster and every write slower. each INSERT adds an entry to every index, each entry is another WAL record, and an UPDATE that changes an indexed column can't be a HOT update. six indexes on a table made 10,000 inserts write 6.1x the WAL of no indexes at all. so an index that no query uses is pure cost: find them with pg_stat_user_indexes.idx_scan.
the picture
you know how a textbook's index has to be redone for every new edition? one new paragraph about saffron means updating the index under "saffron", and under "spices", and under "persia". a book with five indexes (by subject, by name, by place, ...) takes five times the work.
here's one row going into a table with a primary key and two more indexes, as the WAL saw it:
| relationname | recordtext | bytesint4 |
|---|---|---|
| people | Heap/INSERT | 82 |
| people_pkey | Btree/INSERT_LEAF | 64 |
| people_email | Btree/INSERT_LEAF | 72 |
| people_city | Btree/INSERT_LEAF | 64 |
| null | Transaction/COMMIT | 34 |
the heap insert is the row. the three Btree/INSERT_LEAF records are the same row going into people_pkey, people_email and people_city, each a change to a different index page that has to be written to disk eventually, each logged first (the WAL). you can watch it yourself:
CREATE TABLE people (id int PRIMARY KEY, email text NOT NULL, city text NOT NULL);
CREATE INDEX people_email ON people (email);
CREATE INDEX people_city ON people (city);
INSERT INTO people VALUES (1, 'maya.chen@example.com', 'San Francisco');
SELECT set_config('my.start', pg_current_wal_insert_lsn()::text, false) IS NOT NULL AS marked;
INSERT INTO people VALUES (42, 'ada@example.com', 'London');
SELECT c.relname AS relation, r.resource_manager || '/' || r.record_type AS record
FROM pg_get_wal_records_info(current_setting('my.start')::pg_lsn, pg_current_wal_insert_lsn()) AS r
LEFT JOIN pg_get_wal_block_info(current_setting('my.start')::pg_lsn, pg_current_wal_insert_lsn()) AS b
ON b.start_lsn = r.start_lsn
LEFT JOIN pg_class AS c ON c.relfilenode = b.relfilenode
ORDER BY r.start_lsn;| markedbool |
|---|
| t |
| relationname | recordtext |
|---|---|
| people | Heap/INSERT |
| people_pkey | Btree/INSERT_LEAF |
| people_email | Btree/INSERT_LEAF |
| people_city | Btree/INSERT_LEAF |
| null | Transaction/COMMIT |
(set_config remembers the WAL position in a session setting, so marking the start doesn't write WAL of its own.)
more indexes, more WAL
scale it up: 10,000 rows into a six-column table, with 0 to 6 single-column indexes on it, measuring the WAL each load produced:
784 KB with no indexes, 4,797 KB with six: every index adds roughly as much WAL as the table itself. one logical write turning into many physical ones has a name, write amplification, and indexes are the biggest multiplier a table has. that WAL is written on every commit, shipped to every replica, archived for every backup. the data files grow too:
with six, the indexes (680 KB) are bigger than the table (512 KB). that's normal for a heavily indexed table, and every page of it competes for the same buffer pool as the data.
UPDATE accounts SET balance = balance + 1 WHERE id = 1;
-- balance is in no indexthe index that turns off HOT
that predict is the expensive part people miss. an index doesn't only cost its own entries: indexing a column that gets updated means no update of that column can be HOT, so every such update writes an entry in every index on the table, not just the one you added.
CREATE TABLE counters (id int PRIMARY KEY, hits int NOT NULL, note text);
INSERT INTO counters SELECT g, 0, 'x' FROM generate_series(1, 100) AS g ORDER BY g;
UPDATE counters SET hits = hits + 1 WHERE id <= 50;
CREATE INDEX counters_hits ON counters (hits);
UPDATE counters SET hits = hits + 1 WHERE id > 50;
SELECT pg_stat_force_next_flush();
SELECT n_tup_upd, n_tup_hot_upd FROM pg_stat_user_tables WHERE relname = 'counters';| pg_stat_force_next_flushvoid |
|---|
| '' |
| n_tup_updint8 | n_tup_hot_updint8 |
|---|---|
| 100 | 50 |
100 updates. the 50 before the index on hits were HOT. the 50 after it can't be: hits is now indexed, and each update had to add an entry to counters_pkey and to counters_hits. the classic case is an updated_at or status column, indexed for one report, on a table that's updated all day.
finding the indexes nobody uses
postgres counts index scans per index. an index with idx_scan = 0 since the statistics were last reset has never been used to answer a query on this server:
CREATE INDEX orders_customer ON orders (customer_id);
CREATE INDEX orders_status ON orders (status);
CREATE INDEX orders_ordered_at ON orders (ordered_at);
SELECT count(*) FROM orders WHERE customer_id = 42;
SELECT id FROM orders ORDER BY ordered_at DESC LIMIT 1;
SELECT pg_stat_force_next_flush();
SELECT s.indexrelname, s.idx_scan, pg_size_pretty(pg_relation_size(s.indexrelid)) AS size
FROM pg_stat_user_indexes AS s
JOIN pg_index AS i ON i.indexrelid = s.indexrelid
WHERE s.relname = 'orders' AND NOT i.indisunique
ORDER BY s.idx_scan, s.indexrelname;| countint8 |
|---|
| 7 |
| idint4 |
|---|
| 10000 |
| pg_stat_force_next_flushvoid |
|---|
| '' |
| indexrelnamename | idx_scanint8 | sizetext |
|---|---|---|
| orders_status | 0 | 88 kB |
| orders_customer | 1 | 136 kB |
| orders_ordered_at | 1 | 240 kB |
orders_status was never scanned. before dropping one like it on a real server, check a few things:
- how long the counters have been counting.
pg_stat_reset()or a restart after a crash zeroes them;stats_resetinpg_stat_databasesays when. a month-end report needs a month of history. - every server. a read replica keeps its own counters. an index unused on the primary may carry all the replica's traffic.
- constraints. unique and primary key indexes enforce rules even when no query reads them (the
NOT indisuniqueabove leaves them out). so do indexes that back a foreign key's lookups on delete (foreign keys). - duplicates and prefixes. an index on
(customer_id)next to one on(customer_id, ordered_at)is usually redundant: the second serves everything the first does (multicolumn indexes).
then DROP INDEX CONCURRENTLY, which doesn't block writes while it waits for running queries to finish with the index.
keylines
- every index is another write per INSERT, and another WAL record.
- six indexes, 6.1x the WAL of none, on the same rows.
- indexing an updated column turns off HOT updates for it.
- idx_scan = 0 over a long window, on every server: a candidate to drop.
- unique indexes and prefixes of other indexes need a second look before dropping.