On 24 November 2026, a team running OpenFGA reported that a write pre-check, a single SELECT … FOR UPDATE, went from 13 ms to 43 seconds on their Postgres database1. I rebuilt their schema with data shaped like theirs and replayed the query from Python, with psycopg 3 and its default settings. After a first call that warms the connection, calls 2 to 10 took between 0.6 and 0.8 ms. Call 11 took 974 ms, and every call after that stayed around 90 ms2.
Nothing changed between call 10 and call 11: same connection, same query, same kind of values. What changed is the plan Postgres used to run it.
What happens at call 6
Drivers prepare the queries you run often, so Postgres can skip parsing and planning on each call. psycopg 3 prepares a query from its 6th execution; asyncpg prepares everything; the JDBC driver does it after a few executions. That is why call 11 matters with psycopg: it is the 6th prepared execution.
For the first five executions of a prepared statement, Postgres builds a custom plan, using the actual parameter values. From the sixth, it also builds a generic plan, built once for any value, and compares the two by their estimated cost. If the generic plan does not look more expensive, Postgres keeps it from then on and stops planning.
The estimate is where it goes wrong. On a job queue of 2 million rows with 2,000 pending jobs, the classic "next ten pending jobs" query:
select id from jobs where status = $1 order by created_at limit 10;
Postgres estimates the generic plan at a cost of 1.14 and the custom plan for 'pending' at 254. It believes the generic plan is 200 times cheaper. Run for real, the generic plan takes about 120 ms and the custom plan 0.25 ms3. The generic plan does not know the value is rare, assumes half the rows are pending, and walks the created_at index expecting to find ten of them right away. It reads most of the table instead.
The Postgres maintainers have said, more than once, that this is not a bug: a heuristic that decides on estimates will sometimes be wrong4. They are right. The question is which of your queries it is wrong about.
The usual fix is too broad
The answer you find everywhere is to set plan_cache_mode = force_custom_plan for the whole database or the application's role. It works, because Postgres then plans every call with the real values. But it makes every query pay for planning on every call, including the thousands that never had a problem. In the same lab, a lookup by primary key went from 136 to 139 µs per query, and a 4-table join from 207 to 361 µs: 75% slower5.
So the useful question is not "how do I turn generic plans off" but "which queries fall off this cliff, and how do I fix only those".
Two victims, reproduced
Both tickets are open, and both were rebuilt on their real schema with data shaped like the reports.
| Victim | Data | Calls 2-10 | From call 11 |
|---|---|---|---|
| OpenFGA #3444, write pre-check | 600,000 tuples, 4 groups each reading 100,000 documents | 0.6 to 0.8 ms | 974 ms, then ~90 ms |
Temporal #12791, task cleanup DELETE
|
2,000 queues of 20 tasks, 1 queue of 200,000 | 0.8 to 1.4 ms | 2.2 to 2.3 s |
The shapes differ but the mechanism is the same. In OpenFGA, the generic plan picks idx_user_lookup and reads the 100,000 rows of a whole group to check six tuples, 96 ms; the custom plan uses a partial index and takes 0.07 ms6. Out of 25 prepared executions in auto mode, Postgres used the generic plan 20 times7. In Temporal, one queue holds 83% of the rows, and the generic cleanup scans it on every call8. The Temporal reporter saw an average of 99 ms over 14 million calls in production, with a worst case of 177 seconds9.
Measure, don't estimate
Comparing estimated costs cannot find these queries: the estimate is exactly what is wrong. They have to be run. That is what I built plancliff to do, against a copy of the database with realistic data:
-
Measure. For each parameter, find the column it is compared with, and try the most and the least common value of that column from
pg_stats. Run the query with the generic plan forced, then with the custom plan forced. At least 10× and 5 ms slower is a cliff. - Verify. Prepare the query again and call it 20 times in Postgres's default mode, the way the driver would. The cliff is confirmed only if Postgres actually switches to the generic plan and slows down.
- Prove the fix. Replay the query 20 more times with each targeted fix, and report a fix only if the drop is gone.
Every execution runs in a transaction that is rolled back, so measuring a DELETE deletes nothing. Here is the Temporal ticket's query, as plancliff reports it10:
$ plancliff scan postgresql://localhost/temporal queries.sql
CLIFF 7292.8× generic 116.69 ms, custom 0.02 ms DELETE FROM tasks WHERE range_hash = $1 AND task_queue_id =
triggered by the frequent values: 0, \x00ff, 16, 100
confirmed: Postgres switched to the generic plan at prepared call 6 (15/20 generic); calls 2-5 0.29 ms, calls 7-20 118.52 ms
fix ✓ SET LOCAL plan_cache_mode = force_custom_plan; -- in the same transaction, just before this query
proven: calls 7-20 0.20 ms, 0/20 generic
fix ✓ never prepare this query; with psycopg 3: cursor.execute(query, params, prepare=False)
proven: calls 7-20 0.20 ms
The same scan also reports the rewrite proposed in the Temporal ticket, task_id = ANY(ARRAY(...)), as fine: 1.3× between the two plans. A fix someone suggests can be checked before it ships.
Two fixes that touch one query
Both fixes plancliff proves leave every other query on the plan cache:
# any driver: force the custom plan for this transaction only
with conn.transaction():
conn.execute("SET LOCAL plan_cache_mode = force_custom_plan")
rows = conn.execute("select id from jobs where status = %s order by created_at limit 10", ("pending",)).fetchall()
# psycopg 3: never prepare this one query
cur.execute("select id from jobs where status = %s order by created_at limit 10", ("pending",), prepare=False)
Both make Postgres plan that query on every call. For one query, the cost is lost in the noise: on Temporal's newer task cleanup, a call takes 2.53 ms before the switch, 2.49 ms with SET LOCAL, and 68 ms without a fix11. Applied to every query of an application, it is the 75% above.
What the verification taught me
Forcing the generic plan is not the same as Postgres choosing it, and three things only showed up once plancliff replayed queries the way a driver does.
Some cliffs are latent. On a join where the forced generic plan was more than ten times slower, Postgres kept the custom plan for 20 calls out of 20, because it estimated the generic one as more expensive12. Nothing is wrong today. A new ANALYZE, a table that grows or a column that gains values can move the estimate and open the cliff, so plancliff reports these as latent and does not fail the run on them.
A parameterised LIMIT hides the cliff. Written limit $2, the same job-queue query no longer falls: the generic plan does not know the limit, assumes it is large, looks expensive, and Postgres keeps the custom plan. Temporal's cleanup has a LIMIT $4 and falls anyway. The exact shape of the query decides, and only running it tells.
pg_stat_statements turns constants into parameters. To read the queries an application really runs, plancliff can take them from pg_stat_statements, preferably on production through a read-only connection, and measure them on a copy. But the view stores a limit 10 written in the code as limit $2, which, as above, hides the cliff. So an integer parameter that matches no column is also tried as a constant, and the worse verdict wins, with a note saying so13.
A whole application
On all 94 queries of Temporal 1.31.1, extracted from its Go code, run against its real schema with skewed data, plancliff finds one cliff, confirms it and proves both fixes, in 3.3 seconds. It reports 82 queries as fine and 11 as untestable: inserts that hit an existing key with the value tried, empty tables, and one query the Go code completes at runtime11.
The ticket's own query does not fall on that data, because the synthetic queues are not skewed enough. That is the main limit: plancliff reports the data it is given, so it needs a copy with production's skew. The others are in the README: two values per column, not combinations; one value replayed 20 times, where an application varies them; planning time not measured.
Try it
$ pip install plancliff
$ plancliff scan postgresql://localhost/app_copy --stats-from postgresql://readonly@prod/app
It refuses to scan a database other sessions are connected to, since measuring a write or a FOR UPDATE locks rows while it runs. It exits with 1 on a confirmed cliff, so a CI job can fail on one. It is tested on PostgreSQL 14 to 18. The code, the lab that produced every number on this page and its scripts are at github.com/jrachid/plancliff.
Notes
-
openfga/openfga#3444, "Write pre-check
SELECT … FOR UPDATEbecomes very slow when Postgres switches to a generic plan". The 13 ms and 43 s are from the report. -
labo/openfga/reproduire.pyonschema_donnees.sql: PostgreSQL 17.11, psycopg 3.3.9, run on 26 November 2026. Call 1 includes connection warm-up. -
labo/epreuve_parade.py, oneEXPLAIN ANALYZEper plan, warm cache, three runs: generic 120 to 130 ms, custom 0.23 to 0.28 ms after a first cold run. The estimated costs do not move between runs. - Laurenz Albe on pgsql-bugs, BUG #19076, October 2025; Tom Lane doubted, in March 2025, that tuning the rule would help.
-
labo/epreuve_parade.py, mean over repeated calls through psycopg,autoagainstforce_custom_plan. -
labo/openfga/plans.py,EXPLAIN ANALYZEwith each plan forced: 96.1 ms against 0.073 ms. -
labo/openfga/auto.py, counters frompg_prepared_statementsafter 30 calls. -
labo/temporal/reproduire.pyonschema_donnees.sql, each call deleting and committing 100 tasks, PostgreSQL 17.11. - temporalio/temporal#12791; figures from the report.
- plancliff 0.1.0 on the lab's
temporaldatabase, queries inlabo/temporal/requetes.sql. The forced-plan measure (117 ms) is lower than the replayed calls (2.2 s) because the scan rolls its deletes back while the replay commits them. - plancliff 0.1.0 on the lab's
temporal_fulldatabase, the 94 queries oflabo/temporal-complet/requetes.sql. -
tests/test_verify.py,test_a_join_whose_generic_plan_postgres_never_picks_is_latent_not_a_cliff: 300,000 events joined to 600,000 deliveries. -
tests/test_stats.py,test_a_limit_constant_hidden_as_a_parameter_is_still_caught.
Originally published on my blog, where these notes sit in the margin next to the claim they support.
Top comments (0)