Sub topic 11
Telling the planner about your storage
The planner chooses between plans by comparing estimated costs. Those costs are unitless numbers built from a few constants, and some of those constants describe your storage. If they describe the wrong hardware, the planner can pick a sequential scan when an index scan would be faster. This chapter covers the cost settings that matter most, how to test a change, and how to apply it safely. It assumes you can read a basic EXPLAIN plan, run queries in psql, and edit postgresql.conf. It also assumes you know that effective_cache_size is covered in an earlier chapter.
How the planner prices I/O
Every plan node gets a cost made of I/O and CPU parts. The I/O parts use two settings:
seq_page_costis the cost of reading one 8 kB page as part of a sequential read. The default is 1.0.random_page_costis the cost of reading one page that is not next to the previous one. The default is 4.0.
The CPU parts use cpu_tuple_cost (0.01), cpu_index_tuple_cost (0.005), and cpu_operator_cost (0.0025). Only the ratios between these values matter. Doubling all of them changes no plan choice. The defaults treat seq_page_cost = 1.0 as the unit and express everything else relative to it.
Roughly, a sequential scan costs pages * seq_page_cost plus a CPU charge per row. An index scan costs index page reads and heap page reads at random_page_cost, plus CPU charges. A higher random_page_cost makes index scans, bitmap scans, and nested-loop joins on indexes look more expensive. That pushes the planner toward sequential scans and hash joins.
Why 4.0 is often wrong today
The default of 4.0 reflects spinning disks, where a random read needs a head seek and is many times slower than a sequential read. On SSD and NVMe storage, a random read is only slightly slower than a sequential one. Using 4.0 on such storage makes the planner avoid indexes that would have been faster.
Typical starting values:
| Storage | random_page_cost starting point |
|---|---|
| Spinning disks | 4.0 (default) |
| SATA or SAS SSD | 1.1 to 1.5 |
| Local NVMe | 1.1 |
| Network block storage (cloud volumes) | 1.1 to 2.0 |
These are starting points, not measurements. Network storage can have high latency even when throughput is good, so test it.
The default of 4.0 also quietly compensates for something else. Real random reads often hit memory, because hot index pages stay in shared_buffers or the OS page cache. A cached random read is cheap, far below the on-disk cost of 4.0. If most of your working set is cached, a lower value can be correct even on spinning disks. If your data is far larger than RAM and mostly cold, a value close to the hardware reality is better.
Inspecting the current values
SELECT name, setting, unit, context, source
FROM pg_settings
WHERE name IN ('seq_page_cost', 'random_page_cost',
'cpu_tuple_cost', 'cpu_index_tuple_cost',
'cpu_operator_cost', 'effective_cache_size');The context column shows user for these settings. That means any session can change them with SET, and a server restart is never required. The source column tells you whether a value comes from the default, the config file, or a database or role override.
Testing a change in one session
Never change a cost constant globally on a guess. Change it in your own session and compare plans first. The table and index below are only for the example.
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id integer NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
total numeric(10,2) NOT NULL
);
INSERT INTO orders (customer_id, created_at, total)
SELECT (random() * 50000)::int,
now() - (random() * 365) * interval '1 day',
(random() * 500)::numeric(10,2)
FROM generate_series(1, 2000000);
CREATE INDEX orders_customer_idx ON orders (customer_id);
ANALYZE orders;Now compare the plan under the default cost and a lower cost. SET lasts until the session ends, and RESET restores the previous value.
SET random_page_cost = 4.0;
EXPLAIN SELECT * FROM orders WHERE customer_id BETWEEN 100 AND 1500;
SET random_page_cost = 1.1;
EXPLAIN SELECT * FROM orders WHERE customer_id BETWEEN 100 AND 1500;
RESET random_page_cost;If the plan changes between the two runs (for example from Seq Scan to Bitmap Heap Scan or Index Scan), the setting affects this query. The EXPLAIN output only shows what the planner believes. To find out whether the new plan is actually faster, run both with timing and buffer counts:
SET random_page_cost = 4.0;
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders WHERE customer_id BETWEEN 100 AND 1500;
SET random_page_cost = 1.1;
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders WHERE customer_id BETWEEN 100 AND 1500;
RESET random_page_cost;Compare Execution Time and the Buffers: shared hit=... read=... lines. If the lower setting produces a faster plan across your real queries, the new value matches your storage. If it produces a slower plan, the planner's picture was already close, or your data is too cold or too large for the index plan to win.
Applying the setting
Once you have evidence, choose the narrowest scope that fits.
For the whole server, use ALTER SYSTEM and reload. No restart is needed.
ALTER SYSTEM SET random_page_cost = 1.1;
SELECT pg_reload_conf();
SHOW random_page_cost;For a single database or role, use per-object overrides. These take effect for new sessions.
ALTER DATABASE appdb SET random_page_cost = 1.1;
ALTER ROLE reporting SET random_page_cost = 1.5;For mixed storage, set the cost on the tablespace. This is the most accurate option when some tables live on fast disks and others on slow ones.
ALTER TABLESPACE fast_nvme SET (random_page_cost = 1.1, seq_page_cost = 1.0);
ALTER TABLESPACE archive_hdd SET (random_page_cost = 4.0, seq_page_cost = 1.0);A tablespace setting applies to tables and indexes stored in that tablespace and overrides the server-wide value for them.
Edge cases and mistakes
- Setting
random_page_costbelowseq_page_cost. This tells the planner that scattered reads are cheaper than contiguous ones, which is never true. Keep the ratio at 1.0 or higher. Values of 1.0 to 1.1 are the practical floor for storage that has no seek penalty. - Tuning for one query. A value that fixes one slow report can push dozens of other queries toward index scans on large result sets. Test a sample of your real workload.
- Ignoring statistics. If the row estimates are wrong, no cost constant will repair the plan. Run
ANALYZEand check estimated versus actual rows inEXPLAIN (ANALYZE)before touching the cost constants. - Forgetting
effective_cache_size. This setting tells the planner how much data is likely cached, and the planner lowers its estimated cost for repeated index page reads when it is large enough. If it is too small, index plans look worse than they are. Check it together withrandom_page_cost. - Changing
seq_page_costinstead. Raising or lowering the unit changes the ratio the same way, but the convention is to leaveseq_page_costat 1.0 and moverandom_page_cost. The exception is the tablespace case above, where both are given per tablespace.
Exercise
Exercise
Your server uses local NVMe storage and most of your index scans on large tables are being replaced by sequential scans. The server still has the default randompagecost of 4.0. Describe how you would test and roll out a lower value, and name one check that would tell you to stop.
Show answer
First confirm that row estimates are accurate with EXPLAIN (ANALYZE) and run ANALYZE if they are not. Then, in a single session, run SET randompagecost = 1.1 and compare EXPLAIN (ANALYZE, BUFFERS) output for a sample of real queries against the default, using warm cache for both. If the index plans are faster, apply ALTER SYSTEM SET randompagecost = 1.1 followed by SELECT pgreloadconf(). No restart is needed because the setting has context user. You should stop and revert if the new value makes other queries slower, for example if queries that return a large fraction of a table now use an index scan and take longer than their sequential scan did.