Sub topic 10
Write Cost, Size, and Maintenance
This chapter assumes you know basic SELECT, WHERE, ORDER BY, table creation, and common PostgreSQL types. It also assumes you can read a simple query plan. The goal is to measure an index’s cost and maintain indexes safely on a busy database.
Every index has a write cost
An index speeds up some reads by storing an additional searchable structure. PostgreSQL must also update that structure when a row is inserted, deleted, or changes an indexed column.
For example, inserting one row into a table with four indexes may require changes to the table and to all four indexes. Updates can cost even more because PostgreSQL may need to remove old index entries and add new ones.
Indexes also consume disk space and memory. More indexes can cause:
- Slower
INSERT,UPDATE, andDELETEoperations. - More WAL, or write-ahead log, activity for replication and recovery.
- Longer backups and restores.
- More work for
VACUUMand autovacuum. - More choices for the query planner.
An index is usually worthwhile when it supports an important query, constraint, or ordering operation. An index that is never useful still costs money on every write.
Check index size and usage
The pg_stat_user_indexes view contains statistics for indexes on user tables. idx_scan counts index scans since the statistics were reset or the server restarted, depending on the statistics system and configuration.
SELECT
schemaname,
relname AS table_name,
indexrelname AS index_name,
idx_scan,
pg_size_pretty(pg_relation_size(indexrelid)) AS index_size
FROM pg_stat_user_indexes
WHERE relname = 'orders'
ORDER BY idx_scan, indexrelname;An index with a low idx_scan value deserves investigation, but that value is not proof that the index is unnecessary. The measurement period may be short. The index may support a rarely used but critical report. A primary key or unique index may enforce a constraint even when it is not used for ordinary searches.
The index size also needs context. A large index can still be valuable if it prevents expensive table scans. Compare its size and write cost with the latency it saves.
You can inspect all indexes on a table with pg_indexes:
SELECT indexname, indexdef
FROM pg_indexes
WHERE tablename = 'orders';Build an index without blocking writes
A normal CREATE INDEX can block writes to the table while the index is built. CREATE INDEX CONCURRENTLY takes longer and performs more work, but it allows ordinary inserts, updates, and deletes to continue.
CREATE INDEX CONCURRENTLY orders_status_idx
ON orders (status);CREATE INDEX CONCURRENTLY has important rules:
- It cannot run inside a transaction block.
- It may take much longer than a regular index build.
- It performs multiple table scans.
- It still uses CPU, disk bandwidth, and I/O.
- It can wait for transactions that started before the build.
- If it fails, PostgreSQL may leave an invalid index that must be removed or repaired.
Check for invalid indexes with this query:
SELECT
n.nspname AS schema_name,
c.relname AS index_name,
i.indisvalid,
i.indisready
FROM pg_class AS c
JOIN pg_namespace AS n ON n.oid = c.relnamespace
JOIN pg_index AS i ON i.indexrelid = c.oid
WHERE c.relkind = 'i'
AND NOT i.indisvalid;If a concurrent build fails, remove the invalid index with DROP INDEX CONCURRENTLY, then try again. Do not use DROP INDEX CONCURRENTLY inside a transaction either.
DROP INDEX CONCURRENTLY IF EXISTS orders_status_idx;A concurrent build is safer for production availability, but it is not free. Schedule it when the server has enough I/O capacity.
Vacuum, statistics, and rebuilding
Updates and deletes can leave dead row versions. VACUUM reclaims space for reuse and helps maintain index health. Autovacuum normally performs this work automatically. Large write-heavy tables may need carefully tuned autovacuum settings.
ANALYZE updates table statistics. These statistics help the planner estimate how many rows a query will return. Run it after a large data change if a plan seems wrong.
ANALYZE orders;When an index becomes bloated or needs a change in structure, REINDEX rebuilds it. REINDEX CONCURRENTLY reduces blocking, but it needs extra disk space and takes longer.
REINDEX INDEX CONCURRENTLY orders_customer_created_idx;Do not rebuild indexes simply because they exist. First confirm a problem with size measurements, query latency, write performance, or maintenance behavior.
A maintenance workflow
Use this process before adding an index:
- Identify the query that needs improvement.
- Use
EXPLAIN (ANALYZE, BUFFERS)to measure its current behavior. - Choose an index that matches the query operators and row order.
- Estimate the index’s storage and write cost.
- Build it concurrently when production writes must continue.
- Re-run the query and inspect usage over a representative period.
- Remove redundant indexes only after checking constraints and workload history.
The best index is not the one that makes one query fast at any cost. It is the one whose read benefit justifies its storage, write, and maintenance work.
Exercise
A new index has idx_scan = 0 after one hour, but the application runs an important monthly report. Should you drop the index immediately?
Show answer
No. The observation period is too short. Check the index’s constraints and wait for a representative workload window before deciding.