BUG #19688: pg_dump --schema scans all sequences in PostgreSQL 18, causing severe performance regression
Thread notes
1 note#bug
hackorum-bot#bug
@global #bug
The following bug has been logged on the website:
Bug reference: 19688
Logged by: César García Naranjo
Email address: cesarg9@gmail.com
PostgreSQL version: 18.6
Operating system: Ubuntu 24.04
Description:
I am seeing a severe performance regression in pg_dump --schema after
upgrading from PostgreSQL 16 to PostgreSQL 18.6.
Environment:
* PostgreSQL server: 18.6
* pg_dump: 18.6
* Database uses a schema-per-tenant design
* Total sequences in the database: 142237
* Sequences in the schema being dumped: 329
The command is approximately:
---------------
pg_dump \
-h 127.0.0.1 \
-p 5432 \
-U postgres \
-F c \
-n myschema \
-b \
mydatabase \
-f output.dump
---------------
With PostgreSQL 16, dumping this schema normally took aprox. ~50 seconds.
After upgrading to PostgreSQL 18.6, the same dump takes approximately 5
minutes and half.
Using pg_stat_activity while the dump is running, almost all of the
additional time is spent in this query executed by pg_dump:
---------------
SELECT
seqrelid,
format_type(seqtypid, NULL),
seqstart,
seqincrement,
seqmax,
seqmin,
seqcache,
seqcycle,
last_value,
is_called
FROM pg_catalog.pg_sequence,
pg_get_sequence_data(seqrelid)
ORDER BY seqrelid;
---------------
During this query, the backend is typically waiting on:
wait_event_type = IO
wait_event = DataFileRead
I reproduced the sequence query independently.
Running it for all sequences in the database:
---------------
SELECT count(*)
FROM (
SELECT
seqrelid,
format_type(seqtypid, NULL),
seqstart,
seqincrement,
seqmax,
seqmin,
seqcache,
seqcycle,
last_value,
is_called
FROM pg_catalog.pg_sequence,
pg_get_sequence_data(seqrelid)
ORDER BY seqrelid
) s;
Result:
count: 142237
Time: 298715.267 ms (04:58.715)
---------------
The complete pg_dump --schema=myschema takes approximately:
---------------
326.7 seconds
---------------
so this sequence collection query accounts for almost all of the dump time,
however the selected schema only contains 329 sequences.
Running an equivalent query restricted to that schema:
---------------
SELECT count(*)
FROM (
SELECT
s.seqrelid,
d.last_value,
d.is_called
FROM pg_catalog.pg_sequence s
JOIN pg_catalog.pg_class c
ON c.oid = s.seqrelid
JOIN pg_catalog.pg_namespace n
ON n.oid = c.relnamespace
CROSS JOIN LATERAL pg_get_sequence_data(s.seqrelid) d
WHERE n.nspname = 'myschema'
) x;
Result:
count: 329
Time: 4984.888 ms (00:04.985)
---------------
The important part appears to be that PostgreSQL 18 pg_dump calls
pg_get_sequence_data() for every sequence in the database, even when pg_dump
is restricted to a single schema.
This is particularly expensive for schema-per-tenant databases. In this
database there are hundreds of schemas, each with approximately 329
sequences.
I prepared an experimental patch to pg_dump, with AI assistance. I am not
familiar with the PostgreSQL codebase, so please treat this patch as a proof
of concept rather than a proposed final fix.
The patch changes collectSequences() so that, for partial dumps, the
sequence query is restricted to the sequence OIDs that pg_dump has already
selected internally.
It keeps the existing PostgreSQL 18 behavior for full database dumps, while
for partial dumps it adds a condition equivalent to:
---------------
WHERE seqrelid = ANY ('{selected sequence OIDs}'::oid[])
---------------
With this patched pg_dump, dumping the same schema takes approximately ~50
seconds instead of ~5 minutes.
I also compared the output produced by the official and patched versions.
The archive TOCs were identical except for the archive creation timestamp.
After converting both archives to SQL using pg_restore, the generated SQL
was identical except for the random \restrict / \unrestrict token generated
by pg_dump.
I also restored both dumps and compared the sequence state.
This suggests that the performance regression is caused specifically by
collectSequences() reading sequence data for sequences that are not part of
the requested partial dump.
This behavior is especially problematic when backups are performed
separately per schema, because the cost of scanning all 142,237 sequences is
paid again for every pg_dump --schema invocation. In my case i take daily
backups for every schema, and adding ~5 minutes for every one would add 36
additional hours, thus making daily backups impossible.
Would it make sense for collectSequences() to restrict
pg_get_sequence_data() to the sequence objects already selected by pg_dump
for partial dumps, while retaining the current bulk query for full database
dumps?
Here is the patch that i am using right now as i cannot rollback the
database upgrade. I used the following to configure, compile and run the
current tests:
./configure --without-readline --enable-tap-tests
make -j4
make -C src/bin/pg_dump check
All the tests passed.
--- a/src/bin/pg_dump/pg_dump.c
+++ b/src/bin/pg_dump/pg_dump.c
@@ -311,7 +311,7 @@
static void dumpTableSchema(Archive *fout, const TableInfo *tbinfo);
static void dumpTableAttach(Archive *fout, const TableAttachInfo
*attachinfo);
static void dumpAttrDef(Archive *fout, const AttrDefInfo *adinfo);
-static void collectSequences(Archive *fout);
+static void collectSequences(Archive *fout, TableInfo tblinfo[], int
numTables);
static void dumpSequence(Archive *fout, const TableInfo *tbinfo);
static void dumpSequenceData(Archive *fout, const TableDataInfo *tdinfo);
static void dumpIndex(Archive *fout, const IndxInfo *indxinfo);
@@ -1141,7 +1141,7 @@
collectBinaryUpgradeClassOids(fout);
/* Collect sequence information. */
- collectSequences(fout);
+ collectSequences(fout, tblinfo, numTables);
/* Lastly, create dummy objects to represent the section boundaries
*/
boundaryObjs = createBoundaryObjects();
@@ -18728,10 +18728,15 @@
* speed in lookup.
*/
static void
-collectSequences(Archive *fout)
+collectSequences(Archive *fout, TableInfo tblinfo[], int numTables)
{
PGresult *res;
- const char *query;
+ PQExpBuffer query;
+ bool partial_dump = !fout->dopt->include_everything ||
+ schema_exclude_oids.head != NULL ||
+ table_exclude_oids.head != NULL ||
+ tabledata_exclude_oids.head != NULL ||
+ extension_exclude_oids.head != NULL;
/*
* Before Postgres 10, sequence metadata is in the sequence itself.
With
@@ -18743,26 +18748,49 @@
*/
if (fout->remoteVersion < 100000)
return;
- else if (fout->remoteVersion < 180000 ||
+ query = createPQExpBuffer();
+ if (fout->remoteVersion < 180000 ||
(!fout->dopt->dumpData &&
!fout->dopt->sequence_data))
- query = "SELECT seqrelid, format_type(seqtypid, NULL), "
+ appendPQExpBufferStr(query, "SELECT seqrelid,
format_type(seqtypid, NULL), "
"seqstart, seqincrement, "
"seqmax, seqmin, "
"seqcache, seqcycle, "
"NULL, 'f' "
- "FROM pg_catalog.pg_sequence "
- "ORDER BY seqrelid";
+ "FROM pg_catalog.pg_sequence ");
else
- query = "SELECT seqrelid, format_type(seqtypid, NULL), "
+ appendPQExpBufferStr(query, "SELECT seqrelid,
format_type(seqtypid, NULL), "
"seqstart, seqincrement, "
"seqmax, seqmin, "
"seqcache, seqcycle, "
"last_value, is_called "
"FROM pg_catalog.pg_sequence, "
- "pg_get_sequence_data(seqrelid) "
- "ORDER BY seqrelid;";
+ "pg_get_sequence_data(seqrelid) ");
- res = ExecuteSqlQuery(fout, query, PGRES_TUPLES_OK);
+ /* For PostgreSQL 18 and newer, restrict partial dumps to sequences
whose
+ * definition or data is emitted. Keep the upstream query for older
servers.
+ * getSchemaData() has already accounted for filters, ownership, and
+ * extension membership; getTableData() has created the data
objects.
+ */
+ if (fout->remoteVersion >= 180000 && partial_dump)
+ {
+ appendPQExpBufferStr(query, "WHERE seqrelid = ANY ('{");
+ for (int i = 0, n = 0; i < numTables; i++)
+ {
+ TableInfo *tbinfo = &tblinfo[i];
+
+ if (tbinfo->relkind != RELKIND_SEQUENCE ||
+ (!(tbinfo->dobj.dump &
DUMP_COMPONENT_DEFINITION) &&
+ tbinfo->dataObj == NULL))
+ continue;
+ appendPQExpBuffer(query, "%s%u", n++ ? "," : "",
+
tbinfo->dobj.catId.oid);
+ }
+ appendPQExpBufferStr(query, "}'::pg_catalog.oid[]) ");
+ }
+ appendPQExpBufferStr(query, "ORDER BY seqrelid");
+
+ res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
+ destroyPQExpBuffer(query);
nsequences = PQntuples(res);
sequences = (SequenceItem *) pg_malloc(nsequences *
sizeof(SequenceItem));
On Mon, 14 Sep 2026 at 20:49,, PG Bug reporting form <noreply@postgresql.org>:
* Total sequences in the database: 142237
* Sequences in the schema being dumped: 329The command is approximately:
---------------
pg_dump \
-h 127.0.0.1 \
-p 5432 \
-U postgres \
-F c \
-n myschema \
-b \
mydatabase \
-f output.dump
---------------With PostgreSQL 16, dumping this schema normally took aprox. ~50 seconds.
After upgrading to PostgreSQL 18.6, the same dump takes approximately 5
minutes and half.
Hi,
This comes from commit bd15b7db48 (v18): collectSequences() calls
pg_get_sequence_data() for every sequence in the database, even when
only a few of them are going to be dumped. Tom pointed this out while
discussing bug #19365 [1]/messages/by-id/1862355.1767827628@sss.pgh.pa.us. That function opens, locks, and reads each
sequence, so the cost depends on the number of sequences in the
database rather than in the dump.
I can reproduce it on HEAD with 20000 sequences in one schema and 4 in
another. "pg_dump -n small" takes about 1.3 s, of which the
collectSequences() query takes about 1 s; with the attached patch it
takes 0.33 s and the query 25 ms. The same dump also waits for an
AccessExclusiveLock held on an unrelated sequence: with an uncommitted
DROP SEQUENCE in the other schema, it waited until thattransaction
ended.
The attached patch passes the OIDs of the sequences whose data will be
dumped to the query and calls pg_get_sequence_data() only for them.
Definitions are still fetched for all sequences, since that part is
just a catalog scan.
Since this is a v18 regression, I have also attached versions for
REL_19_STABLE and REL_18_STABLE. They differ only in keeping the early
return for servers older than v10. The same tests and output
comparisons pass on both branches.
[1]: /messages/by-id/1862355.1767827628@sss.pgh.pa.us
--
Andrew Krylosov
Attachments:
v1-0001-pg_dump-Fetch-sequence-data-only-for-sequences-be.patchapplication/octet-stream; name=v1-0001-pg_dump-Fetch-sequence-data-only-for-sequences-be.patchDownload+56-21
v1_PG19-0001-pg_dump-Fetch-sequence-data-only-for-sequences-be.patch.txttext/plain; charset=UTF-8; name=v1_PG19-0001-pg_dump-Fetch-sequence-data-only-for-sequences-be.patch.txtDownload+61-23
v1_PG18-0001-pg_dump-Fetch-sequence-data-only-for-sequences-be.patch.txttext/plain; charset=UTF-8; name=v1_PG18-0001-pg_dump-Fetch-sequence-data-only-for-sequences-be.patch.txtDownload+61-23
Hi Andrew,
Surya Poondla, Christopher Bell and I reviewed this patch together, as
part of the November patch review workshop.
Short version: the patch does what it says, we could not find any change
in what pg_dump outputs or in how it fails, and it looks ready to us.
There is one comment suggestion and one question about tests at the end.
== What we tested ==
v1_PG18 on REL_18_STABLE at its base commit, 2d748cfe33 (me), and v1 on
master at 1e676702cac (Surya). Both apply cleanly and build without
warnings; on my side that is Debian 12, gcc 12.2, meson. The pg_dump TAP
suite passes on REL_18_STABLE with the patch.
Both still apply, with offsets, on today's REL_18_STABLE (2ea7106) and
master (d5fb939), and v1_PG19 applies on today's REL_19_STABLE
(5fd37fe). On those three, pgindent and "git diff --check" are clean.
We did not test the REL_19_STABLE variant beyond that; its changed lines
are the same as the REL_18_STABLE ones. We also did not run the patched
pg_dump against a pre-18 server; that branch still sends the same query
text as before.
== The regression and the fix ==
On 2026-09-26, Andrew Krylosov wrote:
I can reproduce it on HEAD with 20000 sequences in one schema and 4 in
another. "pg_dump -n small" takes about 1.3 s, of which the
collectSequences() query takes about 1 s; with the attached patch it
takes 0.33 s and the query 25 ms.
Confirmed on both branches with that setup. On master the query goes
from about 2 s to 12 ms.
We also ran it at the size of the original report: 142,237 sequences in
one schema ("big") and 6 in another ("small"). This is REL_18_STABLE,
-O2 without assertions, everything in cache, median of 5 runs. There is
one server and one database; only the pg_dump binary changes.
unpatched patched
pg_dump -n small -Fc 3.36 s 0.80 s
collectSequences() query 2652 ms 64 ms
pg_get_sequence_data() calls 142,243 6
pg_dump -Fc (whole database) 4.06 s 4.14 s
collectSequences() query 2628 ms 2675 ms
pg_get_sequence_data() calls 142,243 142,243
length of the query text 206 bytes 912 kB
The query times come from the server log, with
log_min_duration_statement = 0. The call counts are the loops of the
Function Scan node in EXPLAIN ANALYZE of that same query text.
Two things about these numbers.
They are CPU only. In the report, the same 142,237 sequences took 298 s
waiting on DataFileRead, so with a cold cache the gain is far bigger
than the 4x shown here.
The full dump is not quite free. With the patch it came out 1-3% slower
in every set of runs we did, 0.04 to 0.13 s out of 4 s. The new query
makes the same 142,243 calls, plus a sort and a merge join that the old
one did not need, and with the default work_mem the sort spills to disk
(external merge, 3.7 MB). Timed alone, the two queries take 2637 ms and
2654 ms (median of 15), which is within the noise. We do not think it
matters, but it is not zero, so the numbers are here.
The same dump also waits for an AccessExclusiveLock held on an
unrelated sequence: with an uncommitted DROP SEQUENCE in the other
schema, it waited until thattransaction ended.
Confirmed. With "BEGIN; DROP SEQUENCE big.s000002;" left open in another
session, the unpatched "pg_dump -n small" sits in wait_event Lock /
relation on the collectSequences() query until we kill it. The patched
one finishes in 0.7 s, the same as without the lock.
== Output and error behaviour ==
Plain-format dumps taken from that same database with the unpatched and
the patched pg_dump are identical, once the random \restrict and
\unrestrict lines are removed, for all of these:
-n small -n small -s
-n small -a -n small -s --sequence-data
-t small.tab -t small.called
-n small --exclude-table-data=small.never_called
-n nosq -N big
-s (no options)
"small" has a sequence advanced with nextval(), one never called, two
set with setval() (is_called true and false), a serial column and an
identity column. "nosq" is a schema with a table and no sequences: the
OID list is '{}' and pg_get_sequence_data() is never executed. The last
one is the full dump, with 142,243 setval() calls in both.
Surya ran the same kind of comparison on master (-n, -t, -a, -N,
-s --sequence-data and a full dump) with the same result.
The failure case is preserved too. Dumping "small" as a role that lacks
SELECT on one of its sequences fails in both with
pg_dump: error: failed to get data for sequence "never_called"; user
may lack SELECT privilege on the sequence or the sequence may have
been concurrently dropped
and a role that does have SELECT on them gets the same dump as a
superuser.
== The approach ==
What has to hold is that dumpSequenceData() never looks up a sequence
whose data was not fetched. We went through it:
- dumpSequenceData() is only reached for DO_SEQUENCE_SET objects. Those
are created only in makeTableDataInfo(), which is also what sets
tbinfo->dataObj. So "has a dataObj" is exactly "will get a
dumpSequenceData() call". Testing dataObj instead of
DUMP_COMPONENT_DATA is the right choice, because makeTableDataInfo()
can decline to create the object (--exclude-table-data,
--no-unlogged-table-data).
- makeTableDataInfo() is called from getTableData(), for both of its
calls in main(), and from processExtensionTables(), which runs inside
getSchemaData(). All of that happens before collectSequences().
- dumpSequence() does look up sequences that are not in the list, but
it only reads the definition fields, and those are still fetched for
every sequence.
Keeping one row per sequence with the LEFT JOIN means the array has the
same shape as before, so neither bsearch() caller had to change. And
building the list as unnest('{...}'::pg_catalog.oid[]) AS src(...) is
what pg_dump already does for its per-table queries (getTableAttrs(),
getIndexes(), getTriggers() and others), down to the "do we have more
than the '{'?" test.
== Suggestions ==
1. A comment at the call site.
The comment inside collectSequences() says it relies on the
TableDataInfo objects already existing, but nothing at the call in
main() does, and that call sits some 30 lines below getTableData() with
unrelated calls in between. If someone later created a sequence's
TableDataInfo after collectSequences(), dumpSequenceData() would fail
with the "user may lack SELECT privilege ... or the sequence may have
been concurrently dropped" error, which would send them looking in the
wrong place. Something like:
/*
* Collect sequence information. This must come after all
* TableDataInfo objects have been created, since we fetch sequence
* data only for sequences that have one.
*/
2. Tests.
The patch adds none. The speedup is hard to test, but the lock behaviour
is deterministic: hold an uncommitted DROP SEQUENCE on a sequence
outside the dumped schema in a background session, run pg_dump -n, and
it has to finish. Would a small TAP test for that be welcome?
One catch: pg_dump sets statement_timeout and lock_timeout to 0 when it
connects, so without the fix such a test hangs instead of failing,
unless the test itself puts a timeout around pg_dump. We are happy to
write it if you think it is worth having.
That is all we have. With or without the comment, this looks ready for a
committer to us.
Thanks for picking this up.
Surya Poondla, Christopher Bell and Diego