PostgreSQL Index TuningUnder Production Load
PostgreSQL index tuning under production load: find the queries that matter, cut write amplification, earn index-only scans and rebuild without downtime.
The short answer
Index tuning under production load is not a search for missing indexes. It is a budget. Every index you add is paid for on every write to the rows it covers, and on a table that is updated hard, the write cost of the index you added last month can be larger than the read cost of the query you added it for.
So the order of work matters. Measure which queries actually consume the database, in total time rather than in worst case. Count the indexes on your hottest tables and delete the ones nothing reads. Only then add, and when you add, aim for an index that serves several query shapes rather than one that serves a single dashboard.
Two things have changed recently enough to be worth re-checking your assumptions against. PostgreSQL 18, released on 25 September 2025, added skip scans for multicolumn B-tree indexes, which quietly makes some composite indexes useful in cases where they previously were not. PostgreSQL 19, whose general availability is planned for 19 November 2026, adds REPACK with a CONCURRENTLY option, parallel autovacuum of table indexes, and a plan advice module. If you are still on PostgreSQL 14, note that it reached end of life on 12 November 2026, so the version question has already answered itself.
Measure the workload before you touch an index
The first thing to install is pg_stat_statements, and the thing to know about it is that the defaults are conservative. It must be listed in shared_preload_libraries in postgresql.conf, which means a restart, and it needs compute_query_id set to on or auto for query identifiers to be computed. Its own defaults are pg_stat_statements.max at 5000 tracked statements, pg_stat_statements.track at top, so statements nested inside functions are not counted separately, and pg_stat_statements.track_planning at off, because the documentation warns it can carry a noticeable performance penalty under contention.
Sort by total_exec_time, not by mean_exec_time. The query that takes four hundred milliseconds and runs eleven times an hour is a curiosity. The query that takes nine milliseconds and runs eight thousand times a minute is your database. Read shared_blks_hit against shared_blks_read on the same rows to see whether a statement is expensive because it reads from disk or because it reads an enormous number of buffers out of cache, which is a different problem with a different fix.
For the plan itself, EXPLAIN got materially better in the last two releases. PostgreSQL 18 made BUFFERS output automatic in EXPLAIN ANALYZE, reports fractional row counts, marks disabled nodes, and reports the number of index lookups used per index scan node, which is what tells you a nested loop is hammering an index rather than merely choosing one. PostgreSQL 19 adds an IO option for asynchronous I/O activity, WAL full page write bytes under the WAL option, and Memoize cache and lookup estimates. Use auto_explain to capture slow plans from real traffic rather than from your laptop.
Before you add anything, look at what you already have. pg_stat_all_indexes gives you idx_scan per index, and an index with zero scans on a table with real traffic is a write tax you are paying for nothing. The honest caveat is that idx_scan counts since the last statistics reset, and until recently there was no per-index record of when that was; PostgreSQL 19 adds a stats_reset column to pg_stat_all_indexes and pg_stat_all_tables, which finally makes that number interpretable. Also look for redundant prefixes: an index on (tenant_id) is usually dead weight next to an index on (tenant_id, created_at), because a B-tree on the composite can serve the leading column on its own.
Every index is a write tax, and updates are where you pay it
The mechanism worth internalising is this: PostgreSQL's B-tree implementation documentation states that changing one indexed column in an UPDATE always necessitates a new set of index tuples, one for each and every index on the table. Not one for the index containing the changed column. One for all of them. The heap-only tuple optimisation avoids that, but HOT applies only when no indexed column changed and the new row version fits on the same heap page.
That gives you two levers that are cheaper than anything clever. First, stop indexing columns that are updated frequently unless a query genuinely needs them, because each such column converts every update on the table into index writes across the board. Second, leave room on the page with the fillfactor storage parameter on update-heavy tables, so the new version has somewhere local to go. You can watch the result directly: pg_stat_all_tables carries n_tup_upd and n_tup_hot_upd, and current versions add n_tup_newpage_upd for updates that had to move to a new page. A hot update ratio that collapses after a schema change is usually the schema change.
PostgreSQL has two mitigations here and both are easy to misread. Deduplication, on by default since version 13, merges groups of duplicate tuples into a single posting list tuple so the key value is stored once followed by a sorted array of TIDs. It is skipped wherever equal values are not interchangeable, and the exclusion list is longer than most teams expect: numeric, because display scale must be preserved; jsonb, because its operator class uses numeric internally; float4 and float8, because minus zero and zero are distinct representations that compare equal; character, because trailing spaces must be preserved; text and varchar under a nondeterministic collation; and container types such as composites, arrays and ranges. Indexes with an INCLUDE clause never deduplicate at all, and safety is decided when CREATE INDEX or REINDEX runs.
Bottom-up index deletion, added in version 14, removes version churn tuples in reaction to an anticipated page split. Read its precondition carefully, because it is the part teams miss: the documentation says this only happens with indexes that are not logically modified by the UPDATE statements in question. The index on the column your application rewrites every few seconds is precisely the index that does not get this help. That is an argument for fewer indexes on churning columns, not for trusting the engine to clean up after you.
Composite order, partial indexes, and what skip scan changed in 18
The classic rule for a multicolumn B-tree is to put equality predicates first, then one range predicate, then any columns you only need for ordering or output. It is still the right default, and the reason is mechanical rather than stylistic: the index is sorted by the leading column, so a scan can only narrow on later columns inside a contiguous range established by the earlier ones.
PostgreSQL 18 loosened this. Peter Geoghegan's skip scan work means multicolumn B-tree indexes can now be used in more cases where there is no restriction on the first or early indexed columns, or only a non-equality one, but there is a useful restriction on a later column. In practice this rescues the situation where an index on (status, updated_at) exists and a query filters only on updated_at, particularly when the leading column has few distinct values. Treat it as a safety net, not as a design principle. An index whose leading column is low cardinality and unconstrained is still doing more work than an index designed for the query.
Partial indexes remain the most underused tool in the box and the one with the best ratio of benefit to cost. If nearly all rows in a jobs table sit in a terminal state and every query you care about reads the ones that do not, then an index declared with a WHERE status in ('queued','running') predicate is a fraction of the size, stays in cache, and skips the write cost entirely for rows outside the predicate. The catch is that the planner must prove your query's predicate implies the index predicate, which means writing the condition in a matching form and checking with EXPLAIN rather than assuming.
Expression indexes demand the same discipline. An index on lower(email) serves a query filtering on lower(email) and not one filtering on email, and no amount of wishing changes that. The same trap appears with casts: if the column is bigint and your ORM sends a numeric literal, or the column is timestamptz and the comparison is against a date, you can get a sequential scan sitting next to a perfectly good index.
Index-only scans are a visibility map feature, not an index feature
Teams add covering indexes and then wonder why the plan still visits the heap. The reason is that visibility information lives only in heap entries. PostgreSQL's index-only scans documentation describes the sequence: after finding a candidate index entry, the scan checks the visibility map bit for the corresponding heap page, and if the bit is not set the heap entry must be visited anyway, with no advantage over a standard index scan. Its conclusion is blunt, that an index-only scan will be a win only if a significant fraction of the table's heap pages have their all-visible map bits set.
Which means an index-only scan is as much a vacuum outcome as an index design outcome. On a table under constant write pressure where autovacuum is behind, the all-visible bits are not set, and the covering index you built buys you a larger index and nothing else. PostgreSQL 19 improves this in a way that matters: query table scans can now set pages all-visible in the visibility map, where previously only VACUUM and COPY with FREEZE did. It also adds parallel autovacuum of table indexes, via autovacuum_max_parallel_workers and the per-table autovacuum_parallel_workers, with one behaviour change to read first: leaders and workers now share the cost-based delay budget set by vacuum_cost_limit rather than each holding their own, so a parallel vacuum with cost delay enabled can run slower than before.
When you do build a covering index, prefer the INCLUDE clause over trailing key columns, and know what differs. With an index on (x) INCLUDE (y), a uniqueness condition applies to x alone and not to the combination, the included column does not have to be of a type the index can handle, and the documentation notes that declaring payload columns as non-key reliably keeps tuples in the upper levels of the B-tree small. Only B-tree, GiST and SP-GiST support included columns, and expressions are not currently supported as included columns.
The honest counterweight, which the same documentation supplies, is that there is little point including payload columns unless the table changes slowly enough that an index-only scan is likely to not need to access the heap, because if the heap tuple must be visited anyway it costs nothing more to read the column from there. So covering indexes belong on reference and reporting tables, and are usually a mistake on your busiest write target. Note too that B-tree always supports index-only scans, GiST and SP-GiST support them for some operator classes and not others, and GIN cannot support them at all, because a GIN entry typically holds only part of the original value.
Rebuilding, repacking and the last resort
Adding an index to a live table means CREATE INDEX CONCURRENTLY, and it is worth knowing what you are signing up for. The documentation is explicit: PostgreSQL performs two scans of the table and must wait for all existing transactions that could modify or use the index to terminate, and after the second scan it waits for any transaction holding a snapshot predating that scan, including transactions used by concurrent index builds on other tables. It cannot run inside a transaction block. One long-running analytics query or a forgotten idle transaction stalls the build indefinitely, so check pg_stat_activity for the oldest transaction before you start, not after.
The failure mode deserves its own line in your runbook. If the build hits a deadlock or a uniqueness violation, the command fails and leaves an index marked INVALID, which is ignored for querying but still consumes update overhead, so you keep paying the write cost and get none of the read benefit. The recommended recovery is to drop it and run the concurrent build again. Unique indexes add a wrinkle: uniqueness is enforced against other transactions from the second scan onward, so violations can surface in unrelated queries before the index is usable, and an invalid index left by a failed second scan keeps enforcing it. Check for invalid indexes in deploy verification, not during an incident.
For bloat, REINDEX INDEX CONCURRENTLY handles indexes on supported versions. Table bloat was the harder problem, because VACUUM FULL and CLUSTER both take an ACCESS EXCLUSIVE lock for their whole duration, which is why so many teams run pg_repack. PostgreSQL 19 brings that in-tree: REPACK replaces VACUUM FULL and CLUSTER, which are retained for compatibility, and REPACK with CONCURRENTLY does the bulk of the rewrite under a SHARE UPDATE EXCLUSIVE lock, captures concurrent changes with logical decoding, and takes ACCESS EXCLUSIVE only for the final file swap.
Read its restrictions before you plan around it. It needs the MAINTAIN privilege, a primary key or index-based replica identity, a free slot within max_repack_replication_slots, and free disk space of at least the table size plus the index sizes. It is unavailable for partitioned tables, unlogged tables, materialized views, system catalogs, TOAST tables, non-heap access methods and transaction blocks, and it refuses tables with invalid indexes. It is explicitly not MVCC-safe, so transactions holding older snapshots may see the table as empty afterwards, and it fails above roughly 104 million concurrently updated or deleted rows. Progress shows up in pg_stat_progress_repack.
Finally, the new escape hatch, which should stay an escape hatch. PostgreSQL 19 ships pg_plan_advice, a contrib module that captures a plan's shape through EXPLAIN with the PLAN_ADVICE option and replays it by setting pg_plan_advice.advice, in a small language covering scan methods such as INDEX_SCAN and INDEX_ONLY_SCAN, join order, join methods and parallelism. After twenty years of refusing query hints this is genuinely useful for stabilising a plan you know is good, and the documentation's own cautions are the reason to use it sparingly: advice can only steer the planner toward plans it already considered viable, impossible advice yields nodes marked disabled rather than an error and can be worse than no advice at all, aggregation and set operations are not controllable, cached plans may ignore changed advice until you run DISCARD PLANS, and a pinned plan will not adapt when your data distribution does. Reach for it when a query regresses in production and you need a known-good plan today, then go fix the statistics, the index or the query. Advice is a splint, not a repair.
Working with Darvi Labs
This is the kind of work we do. Darvi Labs is a software engineering team in Kathmandu building agentic AI systems and scalable web applications for companies in the US, UK, Europe, Australia and the Gulf. Database performance is usually where we start when we inherit an application that was fast with ten thousand rows and is unpleasant with ten million, because index and vacuum behaviour explains more production slowness than application code does.
If you are weighing an index review, a schema change on a table you cannot lock, or a Postgres major version upgrade, the Contact page is the fastest way to reach us. There is more on how we build and operate these systems on the blogs page, and examples of the work on the portfolio page.
Thinking through a similar decision?
Send us the constraint, the workflow, or the decision that keeps resurfacing. We can help clarify what should change first.
Start a conversation→Keep the decision trail moving.
Three more short reads from DarviLab work across product, systems, and operating constraints.
Nepal's Software Talent Pool: Size, Shape and Limits
Nepal's software talent pool, in figures: how big it really is, where the engineers are trained, what the employability gap means, and who keeps leaving.
Streaming LLM Responses: Proxies, Timeouts, Resumption
Streaming LLM responses breaks in the proxy layer, not the model: response buffering, the four idle-timeout clocks, and what resumption really costs you.
Outsourcing HIPAA and PCI Work to an Offshore Team
Outsourcing HIPAA and PCI work offshore: what the BAA chain must cover, how to keep your developers out of PCI scope, and what DORA adds for EU firms.