PostgreSQL 16 retrospective: Compare generic plans on a skewed parameter distribution
Use PostgreSQL 16’s GENERIC_PLAN option on two regions with 9,900 and 100 rows and distinguish an estimated plan from controlled execution evidence.
Archive retrospective · Topic year 2023
In this article
- The 2023 addition for inspecting parameterized plans
- Build a small skewed fixture and inspect its estimate
- Observe both execution modes with the same two values
- Keep plan shape and timing claims conditional
- Understand what automatic selection actually compares
- Leave a reproducible record of the plan inspection
The 2023 addition for inspecting parameterized plans
The PostgreSQL 16 release notes list a GENERIC_PLAN option for EXPLAIN. It displays a plan for a parameterized query without supplying a concrete parameter value. A reporting endpoint can use one SQL statement for many regions. One region may have a few rows while a large hub has most of them. The same SQL can therefore have different costs depending on the chosen value. A generic plan is formed without knowing a specific parameter value. A custom plan can take the value for that execution into account. Neither plan is automatically better for every query. The goal here is to separate a plan estimate from the behavior of controlled executions. A small, skewed data set makes it possible to inspect that distinction without relying on production data.
Build a small skewed fixture and inspect its estimate
Create the temporary delivery_event table in an isolated PostgreSQL 16 session. Of its 10,000 rows, 9,900 are in hub and 100 in remote. Every row has a payload of the same length. Create a region index and run ANALYZE so the planner can use statistics about the sample. The grouped count is a check on the fixture itself. A mistake while generating the data would otherwise undermine any explanation based on the planned row counts. The first EXPLAIN uses the $1 parameter with an explicit text cast. GENERIC_PLAN shows the estimate without binding a concrete region. It gives planned operations and estimated rows, not measured timings or actual row counts. The manual specifies that this option cannot be combined with ANALYZE. For measurements the second block prepares a separate executable statement.
BEGIN;
CREATE TEMP TABLE delivery_event (
event_id integer PRIMARY KEY,
region text NOT NULL,
payload text NOT NULL
);
INSERT INTO delivery_event
SELECT i,
CASE WHEN i <= 9900 THEN 'hub' ELSE 'remote' END,
repeat('x', 80)
FROM generate_series(1, 10000) AS sample(i);
CREATE INDEX delivery_event_region ON delivery_event(region);
ANALYZE delivery_event;
SELECT region, COUNT(*)
FROM delivery_event
GROUP BY region
ORDER BY region;
-- hub | 9900
-- remote | 100
EXPLAIN (GENERIC_PLAN TRUE)
SELECT SUM(length(payload))
FROM delivery_event
WHERE region = $1::text;
Observe both execution modes with the same two values
Continue in the same transaction. PREPARE creates a statement that accepts a text parameter. SET LOCAL changes the plan selection mode just within the transaction. Compare remote and hub with force_custom_plan, then repeat the same values with force_generic_plan. EXPLAIN ANALYZE executes the statement. Here the test is a read of temporary fixture data. A write statement would have real effects and is outside this experiment. Record the plan nodes, estimated row counts, observed rows and loops at scan nodes, and buffer statistics. An aggregate result may show only one row at the top while scanning a much larger set underneath. That is why comparing only the final Aggregate node is insufficient. The expected sums are 8,000 and 792,000 characters. Changing how the query is executed does not alter its logical result.
PREPARE delivered_chars(text) AS
SELECT SUM(length(payload))
FROM delivery_event
WHERE region = $1;
SET LOCAL plan_cache_mode = force_custom_plan;
EXPLAIN (ANALYZE, BUFFERS, TIMING OFF) EXECUTE delivered_chars('remote');
EXPLAIN (ANALYZE, BUFFERS, TIMING OFF) EXECUTE delivered_chars('hub');
SET LOCAL plan_cache_mode = force_generic_plan;
EXPLAIN (ANALYZE, BUFFERS, TIMING OFF) EXECUTE delivered_chars('remote');
EXPLAIN (ANALYZE, BUFFERS, TIMING OFF) EXECUTE delivered_chars('hub');
EXECUTE delivered_chars('remote'); -- 8000
EXECUTE delivered_chars('hub'); -- 792000
DEALLOCATE delivered_chars;
ROLLBACK;
Keep plan shape and timing claims conditional
The two regions select very different amounts of data, which can influence the estimated cost of an index, bitmap or sequential scan. Statistics, data layout and server configuration affect those choices. This fixture does not promise one exact plan node or a speed improvement on every machine. Report the actual nodes and compare estimated and observed rows rather than making a prediction look like a measurement. Execution order also matters. One run can warm buffers used by the next. Temporary relations may be shown using a different buffer category from ordinary tables. To interpret multiple runs, keep configuration and data stable, record the order and compare repeated observations. Meaningful evidence describes the conditions in which a plan appears and how much work it performs, instead of relying on one elapsed time.
Understand what automatic selection actually compares
The PostgreSQL 16 PREPARE documentation describes the auto policy. It estimates the cost of the first five executions using custom plans, then compares that average with the estimated cost of a generic plan. Switching modes depends on the comparison. The rule does not guarantee that each statement begins using a generic plan after five runs. The application driver also affects which statements are prepared, for how long, and on which database connections. A controlled SQL session demonstrates the database behavior independently of those choices. Review the query’s actual parameter frequency and connection lifecycle before making changes outside the lab. When two parameter groups produce different work, compare plan evidence with requests observed in the application rather than treating these ten thousand rows as a performance forecast.
Leave a reproducible record of the plan inspection
Record the fixture size, parameter values, expected outputs, and the options used for each EXPLAIN. Keep the generic estimate distinct from executed measurements. The sample’s 9,900-to-100 distribution is chosen to make the difference easy to see. When creating a fixture based on real data, preserve relevant distributions without copying customer identities or confidential values. The final block deallocates the statement and rolls back the transaction, clearing the temporary setup and local mode setting. Repeat the comparison after a driver, index or database version change and check the result sums again. The expected values remain 8,000 and 792,000. Report the plan nodes and elapsed work as observations tied to the tested environment. That provides a maintenance record others can reproduce.
Reader discussion
Which alternative architecture would you try for the same problem?
No comments yet. Be the first to contribute.
Write a comment