Sub topic 12
What Indexes Cost on Writes and in Storage
This chapter assumes you can read basic SQL, know what a B-tree index is, and have seen EXPLAIN output. Earlier chapters covered how indexes speed up reads. Here we look at the price. Every index is a second copy of some of your data, and the database must keep that copy correct on every write.
Why an index has to be maintained
A table and its indexes are separate structures. When you change a row, the database changes the table and then updates each index that mentions the changed data. The index must stay in sorted order, because the B-tree only works if it is sorted. Inserting a key means finding the right leaf page, placing the entry there, and sometimes splitting the page when it is full.
The cost per write therefore grows with the number of indexes, not just the number of rows touched.
| Operation | Table work | Index work |
|---|---|---|
| INSERT | Add one row | Add one entry to every index |
| DELETE | Mark the row dead | Index entries stay until cleanup removes them (PostgreSQL) |
| UPDATE of an indexed column | Write a new row version | Add a new entry to affected indexes, and in PostgreSQL usually to all of them |
| UPDATE of a non-indexed column | Write a new row version | Often none, if the engine can skip index changes |
Exact behavior differs between engines. This chapter uses PostgreSQL as the reference and notes where MySQL InnoDB differs.
Write amplification on INSERT
Suppose orders has a primary key plus four secondary indexes. One INSERT touches five B-trees plus the table. Each B-tree insert descends from the root to a leaf, which is O(log n) page reads, and it also writes to the write-ahead log (WAL), the sequential log the database uses to recover after a crash.
You can see the effect directly. This script compares bulk insert time with no extra indexes and with several.
CREATE TABLE orders_bench (
id bigint PRIMARY KEY,
customer_id bigint NOT NULL,
status text NOT NULL,
created_at timestamptz NOT NULL,
total_cents integer NOT NULL
);
\timing on
-- Baseline: primary key only.
INSERT INTO orders_bench
SELECT g, g % 50000, 'open', now() - (g || ' seconds')::interval, g % 10000
FROM generate_series(1, 1000000) AS g;
TRUNCATE orders_bench;
CREATE INDEX ob_customer_idx ON orders_bench (customer_id);
CREATE INDEX ob_status_idx ON orders_bench (status);
CREATE INDEX ob_created_idx ON orders_bench (created_at);
CREATE INDEX ob_total_idx ON orders_bench (total_cents);
-- Same load, now with four extra indexes.
INSERT INTO orders_bench
SELECT g, g % 50000, 'open', now() - (g || ' seconds')::interval, g % 10000
FROM generate_series(1, 1000000) AS g;On typical hardware the second load is several times slower than the first. The exact ratio depends on memory, disk, and data, so measure on your own system.
UPDATE and the HOT optimization
An update changes a row. In PostgreSQL, an update writes a new version of the row rather than editing the old one in place. If any indexed column changed, the new version needs new entries in the indexes. If no indexed column changed, and the new version fits on the same table page, PostgreSQL can use a heap-only tuple (HOT) update. A HOT update skips index changes entirely.
This gives a practical rule: indexing a column that is updated often removes the HOT shortcut for those updates. A last_seen_at column that changes on every request is a poor index candidate, because each update then touches the index.
-- How many updates were HOT versus total, per table.
SELECT relname, n_tup_upd, n_tup_hot_upd
FROM pg_stat_user_tables
WHERE relname = 'orders_bench';A low n_tup_hot_upd relative to n_tup_upd on an update-heavy table suggests too many indexed columns are changing, or that pages are too full. Lowering the table's fillfactor leaves free space on each page so more updates can stay HOT.
Page splits and index shape
Inserts into a B-tree are cheapest when new keys land at the right edge, as with an increasing id or timestamp. Random keys, such as UUID version 4 values, land anywhere in the tree. That touches many different pages, causes more page splits, and leaves pages partly empty. The result is a larger index and more cache misses.
flowchart TDThe diagram below shows the difference between the two patterns.
If you need unique identifiers but want better locality, consider time-ordered identifiers such as UUIDv7, or a bigint sequence.
Storage cost
An index takes disk space and also competes for memory. The database caches hot pages in shared buffers and the operating system cache. A large set of rarely used indexes pushes useful pages out.
Check sizes directly:
SELECT indexrelname,
pg_size_pretty(pg_relation_size(indexrelid)) AS index_size,
idx_scan
FROM pg_stat_user_indexes
WHERE relname = 'orders_bench'
ORDER BY pg_relation_size(indexrelid) DESC;
SELECT pg_size_pretty(pg_relation_size('orders_bench')) AS table_size;Sizes depend on the key width. An index on a text column holding long strings is much larger than one on an integer. A composite index stores every column in every entry. It is common for the indexes on a table to total as much as the table itself, or more.
Note that idx_scan counts how many times each index has been used for scans. An index with idx_scan = 0 over a long, representative period is a candidate for removal. Statistics reset on some operations, so check when they were last reset before you trust a zero.
Costs beyond the obvious
- Locks and contention. Many concurrent inserts into the same rightmost leaf page can contend on that page.
- Replication and backups. Index changes are written to the WAL, so more indexes mean more WAL volume, more network traffic to replicas, and larger backups.
- Maintenance time.
VACUUMmust scan every index to remove entries for dead rows. More indexes make vacuum slower. - Planner time. The planner considers each index. Dozens of indexes on one table add a small cost to planning.
- Lock level during creation. A plain
CREATE INDEXblocks writes to the table while it builds.CREATE INDEX CONCURRENTLYavoids that but takes longer and cannot run inside a transaction block.
-- Build without blocking writes. Cannot be run inside a transaction.
CREATE INDEX CONCURRENTLY orders_status_created_idx
ON orders_bench (status, created_at);A failed concurrent build leaves an invalid index behind. Find and drop it:
SELECT indexrelid::regclass FROM pg_index WHERE NOT indisvalid;InnoDB differences
In MySQL InnoDB, the table itself is stored as a B-tree ordered by the primary key (the clustered index). Every secondary index entry stores the primary key value to locate the row. Two consequences follow. A wide primary key makes every secondary index larger. A random primary key causes page splits in the table itself, not just in an index. InnoDB also buffers some secondary index changes in a change buffer, which softens the cost of writes to indexes that are not in memory.
Reducing the cost
- Drop indexes that are never used, after confirming over a full business cycle.
- Remove redundant indexes. An index on
(customer_id)is usually redundant if(customer_id, created_at)exists, because the composite serves the same leading-column lookups. - Use partial indexes so rows that never match a query are not indexed.
- Keep indexed keys narrow.
- For large one-time loads, drop secondary indexes, load the data, then recreate them. Building an index from sorted data is faster than inserting entries one at a time.
- Avoid indexing columns that change constantly.
-- Find indexes never scanned since statistics were last reset.
SELECT s.indexrelname, s.idx_scan, i.indisunique
FROM pg_stat_user_indexes s
JOIN pg_index i ON i.indexrelid = s.indexrelid
WHERE s.idx_scan = 0
AND NOT i.indisunique
AND NOT i.indisprimary;The filter excludes unique and primary key indexes. They enforce constraints, so they matter even if no query scans them.
Weighing the trade
An index pays off when reads that use it are frequent or expensive, and writes that maintain it are cheap or rare. A read-heavy reporting table can carry many indexes. A write-heavy event log should carry few. Measure both sides: use EXPLAIN (ANALYZE) for the read gain, and time representative writes for the cost.
Exercise
A table events receives 5,000 inserts per second and has a primary key plus six secondary indexes. A query that runs once a day uses one of them. A teammate proposes adding a seventh index on last_seen_at, which is updated on every request. Name two costs this index adds and one way to decide whether the daily query's index should stay.
Show answer
The new index adds an index entry to maintain on every insert, and because last_seen_at changes on every request, it also defeats HOT updates, so each update must write new index entries too. It also adds storage, WAL volume, and vacuum work. To decide on the daily query's index, compare its read benefit (run the query with EXPLAIN (ANALYZE) with and without the index, and check how long it takes) against the write cost it imposes at 5,000 inserts per second. If the query is acceptable without it, or can run on a replica, drop the index.
Exercise
Why can inserting random UUIDv4 primary keys make an index larger than inserting sequential bigint keys, even with the same number of rows?
Show answer
Random keys land on arbitrary leaf pages, so many pages fill up and split at different times. Splits leave pages partly empty, so the index holds the same entries across more pages. Sequential keys fill the rightmost page and then start a new one, leaving pages nearly full.