The symptom#
A lookup takes a fraction of a millisecond when you paste it into psql with literal values. From the application it is fast for a few calls after each connection opens, then slow for the rest of the connection's life, and nothing about the data changed.
The difference is that psql sent literals and the application sent a prepared statement. Drivers that cache prepared statements per connection, as Rust's sqlx does by default, execute the same statement many times on one connection, and that is where the plan cache changes its choice.
How the plan cache chooses#
The PREPARE documentation states the rule. With plan_cache_mode at its default of auto, the first five executions use custom plans, built for the actual parameter values. PostgreSQL then builds a generic plan, valid for any values, and compares its estimated cost with the average of the custom plans. If the generic plan is not much more expensive, every later execution uses it and skips planning.
The comparison is between estimates. A generic plan is estimated without knowing which organization, repository or subject the call asks about, so the planner falls back to average selectivity from the statistics it keeps per column. For a condition like org_id = $1 AND subject_kind = $2 AND subject_id = $3, it multiplies three small average fractions and gets an estimate below one row, which it rounds up to one. A query that touches 34,000 rows for one busy subject is planned as if every subject had one row. The estimate looks cheap, so the plan cache keeps it.
The lab#
The lab needs Docker and takes about a minute. It builds a table with a unique key on seven columns and a second index on the first three.
docker run -d --rm --name pl-a-generic-plan -e POSTGRES_PASSWORD=x postgres:18
docker exec -it pl-a-generic-plan psql -U postgres
CREATE TABLE decisions (
id bigserial,
org_id int NOT NULL, subject_kind text NOT NULL, subject_id int NOT NULL,
part text NOT NULL, name text NOT NULL, version int NOT NULL, attempt text NOT NULL,
verdict text,
CONSTRAINT decisions_identity_key
UNIQUE (org_id, subject_kind, subject_id, part, name, version, attempt)
);
CREATE INDEX decisions_subject_idx ON decisions (org_id, subject_kind, subject_id);
-- 600,000 decisions over 190 organizations, four per subject.
INSERT INTO decisions (org_id, subject_kind, subject_id, part, name, version, attempt, verdict)
SELECT g % 190, 'review', g / 4, 'p' || g % 4, 'addressed', 1, 'a1', 'yes'
FROM generate_series(1, 600000) g;
-- One busy subject with 34,000 decisions.
INSERT INTO decisions (org_id, subject_kind, subject_id, part, name, version, attempt, verdict)
SELECT 7, 'evaluation', 1, 'p' || g, 'addressed', 1, 'a1', 'yes'
FROM generate_series(1, 34000) g;
VACUUM ANALYZE decisions;
PREPARE stored(int, text, int, text, text, int, text) AS
SELECT verdict FROM decisions
WHERE org_id = $1 AND subject_kind = $2 AND subject_id = $3
AND part = $4 AND name = $5 AND version = $6 AND attempt = $7;
Run EXPLAIN (ANALYZE, BUFFERS) EXECUTE stored(7, 'evaluation', 1, 'p33000', 'addressed', 1, 'a1'); first, then plain EXECUTE with the same values four times, then the EXPLAIN again. On PostgreSQL 18.7 the first execution uses the unique key:
Index Scan using decisions_identity_key on decisions (cost=0.42..8.46 rows=1 width=4)
Index Cond: ((org_id = 7) AND (subject_kind = 'evaluation'::text) AND ... (attempt = 'a1'::text))
Buffers: shared hit=4
Execution Time: 0.100 ms
The sixth uses the narrower index and filters the subject's rows:
Index Scan using decisions_subject_idx on decisions (cost=0.42..8.46 rows=1 width=4)
Index Cond: ((org_id = $1) AND (subject_kind = $2) AND (subject_id = $3))
Filter: ((part = $4) AND (name = $5) AND (version = $6) AND (attempt = $7))
Rows Removed by Filter: 33999
Buffers: shared hit=406
Execution Time: 8.859 ms
The $1 placeholders mark the plan as generic. SELECT name, generic_plans, custom_plans FROM pg_prepared_statements; returns stored | 1 | 5: five custom plans, then the switch.
Why the narrower index wins a tie#
Both plans above have the same estimated cost, 0.42..8.46 for one row. Without parameter values, the generic estimate for the three-column prefix and for the seven-column key both clamp to one row, so the planner sees two indexes that each return one row. The narrower index is smaller (24 MB against 63 MB in the lab), and the planner picks it. The rows it removes by filter are invisible to the estimate.
A tie like this needs two indexes with the same leading columns. Deciding whether the narrower one should exist at all is the subject of dropping a redundant index.
The production cases#
The same switch produced three slow statements in one application database within two weeks.
- A webhook handler read the open pull requests of a repository and, for each one, its latest review. The custom plan used an index by pull request: 720 buffers, 2.6 ms. The generic plan used an index on organization and repository instead, read 17,363 reviews for each of 82 pull requests and removed 1,423,718 rows by join filter: 1,447,273 buffers, 1,283 ms, inside the webhook's transaction. The slow-statement log held 190 lines for it in one day, with a median of 1.63 seconds and a maximum of 16 seconds.
- A feedback query cost 245 ms with a custom plan and ran past a 40-second statement timeout with the generic one. The planner priced the generic plan at 63 and the custom plan at 81,005, so the cache kept the generic plan. The statement accounted for 983 calls and 611 seconds of database time in 12 hours.
- A lookup by a seven-column unique key tied with a three-column prefix index, as in the lab. The generic plan removed 33,969 rows by filter over 17,252 buffers, 25 to 31 ms with a warm cache and about 10 seconds from disk. The custom plan read 5 buffers in 0.15 to 0.19 ms.
Fix it for one statement#
You have three choices, and they can be combined.
Plan that statement per call. Set plan_cache_mode to force_custom_plan for the transaction that runs it. It is read at each execution, so it works on a statement prepared earlier:
BEGIN;
SET LOCAL plan_cache_mode = force_custom_plan;
EXECUTE stored(7, 'evaluation', 1, 'p33000', 'addressed', 1, 'a1');
COMMIT;
In the lab the forced custom plan reads 4 buffers in 0.03 ms on a warm cache. The cost is planning on every call, about 4 ms per execution for the webhook query above. Drivers offer the same effect by not caching the statement: sqlx has .persistent(false) on its runtime queries, and other drivers have a per-statement or per-connection switch.
Remove the tie. If a narrower index is a prefix of a unique key and serves no read better than the key, drop it. In the lab, DROP INDEX decisions_subject_idx; leaves the generic plan nothing else to choose, and it becomes a seven-column lookup on the key: 4 buffers, 0.07 ms, with $1 placeholders.
Give the generic plan a shape it cannot misread. When a join's generic plan walks a range of an index, a CROSS JOIN LATERAL (... LIMIT 1) over the whole key turns each lookup into a single descent. In a rehearsal with the production index set, this took one join's generic plan from a 734-buffer walk to 12 buffers for three rows. A unique key makes the LIMIT 1 drop no row.
Setting plan_cache_mode for a whole server or role trades one bad plan for planning cost everywhere.
Confirm which plan you are getting#
Run the statement both ways in one session:
SET plan_cache_mode = force_custom_plan;
EXPLAIN (ANALYZE, BUFFERS) EXECUTE stored(...);
SET plan_cache_mode = force_generic_plan;
EXPLAIN (ANALYZE, BUFFERS) EXECUTE stored(...);
Use the values of a slow call, not a typical one. A large gap in buffers between the two runs is the evidence. PostgreSQL 19 adds generic_plan_calls and custom_plan_calls to pg_stat_statements, which shows how often production uses each. On PostgreSQL 18 and earlier, pg_prepared_statements shows the counts only for your own session.
If both plans are slow, the plan cache is not the cause. Compare the plan with an earlier one and with the rows read instead.
Where this came from#
Proofline found these statements in its own control plane and shipped the fixes in its production releases of 21 November, 24 November and 1 December 2026. The plans and counts in The production cases are that database's readings before each change. Proofline reviews GitHub pull requests; new organizations get one calendar month of hosted code review without a cloud connection. Start a free GitHub review ยท Eligibility and fair-use terms
Questions#
Why is my query fast in psql but slow from the application?
psql sends the literal values, so every run gets a custom plan. The application usually prepares the statement once per connection, and after five executions PostgreSQL may switch it to a generic plan built without the values.
Does force_custom_plan slow down every query?
Only the statements it applies to, and only by their planning time, often a few milliseconds. Set it with SET LOCAL in the transaction that needs it, or turn off statement caching for that one query.
Can ANALYZE fix a bad generic plan?
Not when the cause is an estimate made without parameter values. Fresh statistics change the average the generic plan uses, not the fact that it cannot see which subject a call asks about.