Do we need an index on pg_constraint.confrelid?
Do we need an index on pg_constraint.confrelid?
I received an internal request to look into "slow pg_upgrade", with
the only information being a list of catalog table row estimates and
table sizes. I used AI to create the attached script to
reverse-engineer a schema with catalog tables that size (I ended up
trimming table counts a bit so it wasn't excessively slow).
I discovered that the slow part is the restoring of the objects into
the target instance:
pg_upgrade -d pgdata -D pgdata_new/ -b ~/pg/bin -B ~/pg/bin | ts
'[%Y-%m-%d %H:%M:%S]'
[2026-10-24 19:38:01] Restoring global objects in the new cluster
ok
[2026-10-24 20:18:05] Restoring database schemas in the new cluster
ok (40 mins 4 sec)
Looking at perf top on the new instance, I see:
27.14% postgres [.] XidInMVCCSnapshot
22.07% postgres [.] nocachegetattr
8.93% postgres [.] HeapTupleSatisfiesMVCC.isra.0
7.43% postgres [.] heap_getattr
That's coming from CloneFkReferenced()'s seq scan on pg_constraint.
It's searching for records with the given confrelid, which isn't
indexed.
I did get the time down to 28 mins by doing "VACUUM (FREEZE,
SKIP_DATABASE_STATS) pg_constraint;" every 3 seconds during the
restore to avoid those slow visibility checks. Autovacuum doesn't run
in binary upgrade mode at all. (Perhaps it's safe to run it on catalog
tables as those are not being upgraded from the old instance.)
I then tried out patching Postgres to add an index on
pg_constraint(confrelid). The times I got were:
[2026-10-24 22:18:40] Restoring global objects in the new cluster
ok
[2026-10-24 22:21:13] Restoring database schemas in the new cluster
ok (2 mins 33 secs) 15.7x master.
Given that pg_constraint now stores NOT NULL constraint details, I
feel this problem must be worse than it was previously.
A few schema details from the schema created by the script:
postgres=# select count(*) from pg_class where relpartbound is not null;
count
-------
32300
postgres=# select count(*) from pg_class where relkind = 'p';
count
-------
323
postgres=# select contype,count(*) from pg_constraint group by rollup
(1) order by 2 desc;
contype | count
---------+--------
| 957311
n | 859329
p | 32686
c | 32625
f | 32623
u | 48
I'm told there have been multiple reports of slow pg_upgrades, but I
don't have details on any of the others.
I've included the patch to add the index, but that's only to allow
people to try this for themselves. I'm not seeking reviews on the
patch itself. I'm only interested in discussion here, as there are
obviously trade-offs to adding an index.
David
Re: Do we need an index on pg_constraint.confrelid?
От:
Álvaro Herrera <alvherre@kurilemu.de>
Дата:
On 2026-Oct-24, David Rowley wrote: > I then tried out patching Postgres to add an index on > pg_constraint(confrelid). The times I got were: Yeah, we have a patch to add this already; see the thread at https://postgr.es/m/trinity-08d3329b-f6b2-4c11-91d7-2198e50bf4fc-1790681922354@trinity-msg-rest-gmx-gmx-live-58cc8f554d-c56lm Feel free to grab that for commit if you have the time and inclination, with my thanks. Regards -- Álvaro Herrera Breisgau, Deutschland — https://www.EnterpriseDB.com/
Re: Do we need an index on pg_constraint.confrelid?
Hi David, On Sat, Oct 24, 2026 at 5:35 PM Álvaro Herrera wrote: > Yeah, we have a patch to add this already; see the thread at > https://postgr.es/m/trinity-08d3329b-f6b2-4c11-91d7-2198e50bf4fc-1790681922354@trinity-msg-rest-gmx-gmx-live-58cc8f554d-c56lm That is CF 7365, which started from Bernhard Wonisch's report of ATTACH PARTITION slowing down as pg_constraint grows. v6 is attached, rebased on master dfd7ede529f; 0001 has the same code as the version posted in that thread. It adds a non-unique btree index on confrelid, like the one on contypid, and uses it in the four places that look up foreign keys by referenced relation. Three of them are the ones your patch changes. The fourth is heap_truncate_find_FKs(), used by TRUNCATE and by ON COMMIT DELETE ROWS at commit. It takes a list of relations, so it does one range scan of the index from the lowest to the highest OID in the list instead of one probe per relation. With 95,759 constraints: - 100 TRUNCATEs of a referenced table: master does 100 seq scans of pg_constraint (9.6M rows read) and 2.9G instructions; v6 does no seq scan and 0.20G. - 100 commits that touch an ON COMMIT DELETE ROWS temp table with a trigger: 2.8G instructions on master, 0.084G on v6 (0.081G for the same table without a trigger, which skips the lookup). Your repro with v6, at 1/10 of its scale (3,200 partitions, 95,756 constraints), old cluster on master, three upgrades per side: - master: 3,200 seq scans of pg_constraint in the restored database, one per ATTACH PARTITION; 187.7G instructions for all of pg_upgrade. - v6: no seq scan, 3,200 scans of the new index; 100.1G instructions. At 2/10 it is 556.2G against 206.6G: from 1/10 to 2/10 master grows 2.96x and v6 2.06x. After each v6 upgrade, from master or from 18.6, amcheck with heapallindexed is clean on all pg_constraint indexes. I have not re-timed it, so there is no wall-clock number yet. On the trade-offs: - Write cost: creating a NOT NULL constraint takes about 7.6k more instructions, +5%. WAL when creating constraints grows 1-4%, about 120 bytes per pg_constraint row (measured on 15 Oct). - Size: 16 kB per database after initdb; 6.3-6.8 MB next to a 342 MB pg_constraint with about 1M constraints (15 Oct). - Rows that are not foreign keys go in the index under zero, as with contypid. None of the four lookups visits them, since they all ask for a nonzero confrelid. 0001 stands alone. 0002 is optional: a check in stats.sql that each of the four lookups adds a scan of the new index. Reverting any one call site to a heap scan fails exactly its own check. The OID (9370) is in the development range for renumbering at commit, and catversion is left to the committer. Regards, Manu
Re: Do we need an index on pg_constraint.confrelid?
От:
Álvaro Herrera <alvherre@kurilemu.de>
Дата:
On 2026-Oct-26, Manu wrote: > + /* > + * Look this up through the index on confrelid rather than seqscanning all > + * of pg_constraint. That scan grew expensive once not-null constraints > + * started to have pg_constraint rows, making its cost scale with the > + * total number of constraints in the database. Only foreign keys set > + * confrelid, so filtering on contype in the loop is just > + * belt-and-suspenders. > + */ > + scan = systable_beginscan(pg_constraint, ConstraintConfRelidIndexId, true, > + NULL, 1, key); This comment is not useful. Other catalog indexscans elsewhere in the code base don't explain what happened before the index was created. You could just say "...the index on confrelid, which is only set nonzero by FK constraints. Filtering on contype is ..." -- Álvaro Herrera 48°01'N 7°57'E — https://www.EnterpriseDB.com/ "You don't solve a bad join with SELECT DISTINCT" #CupsOfFail https://twitter.com/connor_mc_d/status/1431240081726115845
Re: Do we need an index on pg_constraint.confrelid?
От:
Álvaro Herrera <alvherre@kurilemu.de>
Дата:
On 2026-Oct-26, Manu wrote: > @@ -3830,16 +3830,28 @@ heap_truncate_find_FKs(List *relationIds) > List *parent_cons; > ListCell *cell; > ScanKeyData key; > + ScanKeyData rangekey[2]; > + Oid minoid; > + Oid maxoid; > Relation fkeyRel; > SysScanDesc fkeyScan; > HeapTuple tuple; > bool restart; > > + if (relationIds == NIL) > + return NIL; > + > oids = list_copy(relationIds); > > /* > - * Must scan pg_constraint. Right now, it is a seqscan because there is > - * no available index on confrelid. > + * Must scan pg_constraint. We do a single range scan of the index on > + * confrelid, from the smallest to the largest OID in our list. Only > + * foreign keys have a nonzero confrelid, so the rows of all other > + * constraints sort before the range and are never visited; foreign keys > + * that fall inside the range but reference a relation not in our list are > + * skipped below. Each pass costs one index probe for a single relation, > + * and never more than visiting each foreign key once however long the > + * list is. I'm unconvinced that this min/max optimization strategy is really very useful; if you have a table built early in your app development it initially works very well, but if you add a new FK months later which lands at the other end of the Oid range, it'll now be very slow. Can we use bloomfilter.c or something else that doesn't degrade as badly, instead? -- Álvaro Herrera 48°01'N 7°57'E — https://www.EnterpriseDB.com/ Maybe there's lots of data loss but the records of data loss are also lost. (Lincoln Yeoh)
Re: Do we need an index on pg_constraint.confrelid?
Hi Álvaro, On Mon, Oct 26, 2026 at 9:40 PM Álvaro Herrera wrote: > This comment is not useful. Other catalog indexscans elsewhere in the > code base don't explain what happened before the index was created. You > could just say "...the index on confrelid, which is only set nonzero by > FK constraints. Filtering on contype is ..." Done; v9 uses your wording, and GetParentedForeignKeyRefs() now has the same comment. On Mon, Oct 26, 2026 at 10:17 PM Álvaro Herrera wrote: > I'm unconvinced that this min/max optimization strategy is really very > useful; if you have a table built early in your app development it > initially works very well, but if you add a new FK months later which > lands at the other end of the Oid range, it'll now be very slow. > > Can we use bloomfilter.c or something else that doesn't degrade as > badly, instead? Agreed. With 100,000 foreign keys between an old table and a new one, the v7 range scan costs more than master's seqscan (62M vs 26M instructions per TRUNCATE). v9 drops the range and probes the index once per relation in the list, so it only reads the foreign keys that point at the list: that case goes down to 1.0M, whatever the number of keys in between. bloomfilter.c wouldn't help here: it only makes the membership test cheaper, and the range scan would still visit the same rows. Two side effects. TRUNCATE ... CASCADE now looks up only the relations added in the previous round, since otherwise every level would probe the whole list again; there is a new test where the cascade loops back. And the fixed cost per probe shows in a nearly empty database: a commit with 1,000 ON COMMIT DELETE ROWS temp tables is 26% slower than master with 194 constraints, even at about 1,200, and twice as fast at 10,400. Details in the attached measurements.txt. I split the patch: 0001 is the index and the lookups that need nothing else, so it doesn't have to wait on 0002, which is the heap_truncate_find_FKs change. Regards, Manu
Re: Do we need an index on pg_constraint.confrelid?
Hi David, On Sat, Oct 24, 2026 at 11:21 PM David Rowley wrote: > I'm only interested in discussion here, as there are > obviously trade-offs to adding an index. On your schema at full scale, pg_upgrade takes 1121 s on master and about two minutes with the index, from v10 or from your patch alike: both use it in the same three lookups. The price is on writes, since every constraint gets an index entry, under zero if it is not a foreign key: creating 1,000 tables with 100 NOT NULL columns each takes 4.5% more instructions and 5.3% more WAL. v10, attached, is just the plain index Tom suggested in [1]. heap_truncate_find_FKs() keeps its seqscan: v9-0002 probed the index once per relation, and that made a commit with 1,000 ON COMMIT DELETE ROWS tables 14-24% slower on a fresh database. The stats.sql check now reads this backend's own counter inside a transaction, so a parallel test can't hide a revert. catversion is not bumped. Details and scripts attached. [1] https://www.postgresql.org/message-id/1298334.1790896057%40sss.pgh.pa.us Regards, Manu
Re: Do we need an index on pg_constraint.confrelid?
От:
Álvaro Herrera <alvherre@kurilemu.de>
Дата:
On 2026-Nov-04, Manu wrote: > v10, attached, is just the plain index Tom suggested in [1]. > heap_truncate_find_FKs() keeps its seqscan: v9-0002 probed the index > once per relation, and that made a commit with 1,000 ON COMMIT DELETE > ROWS tables 14-24% slower on a fresh database. The stats.sql check > now reads this backend's own counter inside a transaction, so a > parallel test can't hide a revert. catversion is not bumped. > Details and scripts attached. I have pushed this with a catversion bump, but omitted the new stats.sql test. (I also renamed the new index.) I think the case in heap_truncate_check_FKs() could be made faster by using a ScalarArrayOpExpr (SK_SEARCHARRAY in nbtree), but I think we don't have any precedent where we manufacture that kind of thing for DDL use. Thanks -- Álvaro Herrera 48°01'N 7°57'E — https://www.EnterpriseDB.com/ "The ability of users to misuse tools is, of course, legendary" (David Steele) https://postgr.es/m/11b38a96-6ded-4668-b772-40f992132797@pgmasters.net
Re: Do we need an index on pg_constraint.confrelid?
От:
Manu <manuelreyesbravo@gmail.com>
Дата:
Hi Álvaro, On Thu, Nov 12, 2026 at 3:29 PM Álvaro Herrera wrote: > I have pushed this with a catversion bump, but omitted the new > stats.sql test. (I also renamed the new index.) Thanks for pushing it, b0496e30830, and for the review along the way. Thanks too to Tom for suggesting the plain index, and to David and Bernhard for the reports this started from. I'll add an XXX note to the commit message when I leave a catversion bump out, as you suggested. Regards, Manu
Re: Do we need an index on pg_constraint.confrelid?
От:
Manu <manuelreyesbravo@gmail.com>
Дата:
Вложения:
Hi Álvaro,
On Thu, Nov 12, 2026 at 3:29 PM Álvaro Herrera
wrote:
> I think the case in heap_truncate_check_FKs() could be made faster by
> using a ScalarArrayOpExpr (SK_SEARCHARRAY in nbtree), but I think we
> don't have any precedent where we manufacture that kind of thing for
> DDL use.
The attached patches do that, on top of master (77bba54, after your
b0496e30830). heap_truncate_check_FKs() does its lookups through
heap_truncate_find_FKs(), so that is the function they change.
0001 stands alone: TRUNCATE ... CASCADE passed heap_truncate_find_FKs()
the whole, growing list at every level, so a chain of N tables made N
lookups of up to N relations. It now passes only the relations added
at the previous level; each level adds the same relations in the same
order.
0002 lets systable_beginscan() take SK_SEARCHARRAY keys. nbtree
already handles them on the index path. On the heap path, used with
ignore_system_indexes or while reindexing, the heap scan would compare
the column with the array datum itself and return wrong rows, so 0002
keeps those keys out of it and checks them in systable_getnext(). An
index without amsearcharray raises an error. It is in genam.c rather
than a seqscan fallback in the caller because systable_beginscan()
makes that decision, and the caller would have to duplicate it.
0003 makes heap_truncate_find_FKs() do one confrelid = ANY scan instead
of the seqscan. Its test is in unsafe_tests, since it reconnects with
ignore_system_indexes; it fails if the genam.c part of 0002 is
reverted.
On precedent: no DDL code builds such keys today; outside nbtree only
nodeIndexscan.c does. The simpler alternative, one index probe per
relation, needs no genam.c change, so I measured it in the same cells
("probes" in measurements.txt). It gets the same gains in large
catalogs, but in a fresh database a commit with 1,000 ON COMMIT DELETE
ROWS tables that have triggers costs 21.8% more than master, against
2.7% with 0003: every probe sets up an index scan.
CPU instructions, master vs patched, median of 3 (measurements.txt
and the scripts that produced it are attached too):
- TRUNCATE of two PK/FK pairs in a catalog with 100,000 other FKs,
net of a TRUNCATE of four plain tables: 26.45M -> 1.02M
- whole commit with those 1,000 temp tables, in that catalog:
557.21M -> 34.91M
- TRUNCATE ... CASCADE down a chain of 1,000 tables: 3990.78M ->
1486.45M with 0001 alone, 637.02M with all three
The price, in a fresh database: that commit costs 2.7% more (33.90M ->
34.83M, under 1M instructions), 1.0% with 100 tables, and a TRUNCATE
of 1,000 tables in one statement 0.3% more. With 1,000 FKs in the
catalog the commit is already 11.0% cheaper. The other cells are
within run-to-run variation (measurements.txt, section 5).
The scripts count instructions, so they need builds without
assertions, as build.sh makes them.
Regards,
Manu