Repository navigation
Avoid full pg_constraint scan on chunk creation - #10808
Merged
Merged
Conversation
|
@akuzm, @pnthao: please review this pull request.
|
Codecov Reportβ Patch coverage is
π’ Thoughts on this report? Let us know! |
feikesteenbergen
force-pushed
the
feike/speedup_chunk_creation
branch
2 times, most recently
from
October 13, 2026 07:55
971c3f5 to
344a1c5
Compare
svenklemm
approved these changes
Oct 13, 2026
antekresic
approved these changes
Oct 13, 2026
Creating a chunk looks up the foreign keys that reference the hypertable, so their triggers can also be applied to the new chunk. The hypertable is the referenced table in these keys. This is what declarative partitioning does for foreign keys that reference a partitioned table. Without the triggers on the chunk, deleting or updating a row in the chunk would not be checked against the referencing tables. To find these keys, the code scanned all of pg_constraint for confrelid = hypertable. PostgreSQL has no index on confrelid, so every chunk creation read the whole table, even when no foreign key exists. The cost grows with the number of constraints in the database. Every table adds some, and so does every chunk, for example a primary key, unique constraints and the time range check. Since PostgreSQL 18, NOT NULL constraints are stored in pg_constraint too. That adds a row for every NOT NULL column of every table, and makes the scan slower again. The bottleneck was found with perf on a backend that was creating chunks. 89.5% of the samples were in relation_get_referencing_fk(), and the stacks showed a sequential scan of pg_constraint below it. pg_statio_all_tables confirmed this. pg_constraint was scanned once per chunk (157,675 scans for 156,000 chunks) and had 3.09 billion buffer accesses, more than 300 times any other catalog table. Its seq_tup_read stays at 0, because the scan finds no matching row, so that counter hides the problem. Find the foreign keys through pg_depend instead. A foreign key has a normal dependency on each column it references, and pg_depend has an index on (refclassid, refobjid, refobjsubid). Scan it for the hypertable and keep only column dependencies (refobjsubid > 0). Every chunk also has a whole-table dependency on the hypertable from inheritance, and there can be millions of those. Fetch each candidate constraint by OID and check contype and confrelid. The same helper is used when a chunk is dropped and when check triggers are swapped on PG19, so those paths get faster too. Measured on PG19 with a table that has a primary key, a unique constraint and 3 NOT NULL columns, 1 second chunks, 4 hypertables filled in parallel with _timescaledb_functions.create_chunk(): chunks created before (s/10k) after (s/10k) 0 to 10k 43.7 13.4 20k to 30k 200.9 23.4 40k to 50k 353.1 30.0 Creating one chunk takes about 35 ms before and about 3 ms after, once a hypertable holds around 45k chunks. After the change, perf shows 0.17% of the time in relation_get_referencing_fk(). pg_constraint was scanned 4 times in total and used about 44 buffer accesses per chunk, down from about 19.8k. The size of the catalogs per chunk did not change. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
feikesteenbergen
force-pushed
the
feike/speedup_chunk_creation
branch
from
October 13, 2026 09:31
344a1c5 to
ee4325d
Compare
Merged
surister
added a commit
that referenced
this pull request
Oct 20, 2026
## 2.31.0 (2026-10-20) This release contains performance improvements and bug fixes since the 2.30.2 release. We recommend that you upgrade at the next available opportunity. **Highlighted features in TimescaleDB v2.31.0** * Improved performance for `UPDATE` and `DELETE` queries on the columnstore with vectorized key processing for bulk decompression. The vectorized aggregation makes DML and recompression operations faster through parallelism, when a single-chunk query groups by an expression, resulting in up to 6.5 times faster queries. * Preview of the new Adaptive Integer Compressor (AIC), which chooses the best encoding for each block of integer values. This results in the up to 20% improvement in compression ratios for integers, while queries benefiting from faster decompression perform up to two times better. AIC is disabled by default in this release and will be enabled by default in the `2.32.0` release. **Loader changes** This release allows controlling extension hook order to improve compatibility with other extensions. To ensure pgaudit hooks work together with timescaledb, pgaudit must come after timescaledb in `shared_preload_libraries` setting. This loader change, requires a PostgreSQL restart to enable the compatibility, but if you have no need to control the hook order, the previous loader version is enough, and you don't require a service restart. **Backward-Incompatible Changes** * [#10666](#10666) Rename `timescaledb.enable_columnarscan` to `timescaledb.debug_enable_columnarscan` to make its debugging-only purpose explicit * [#10772](#10772) Make the direct-compress batch sorting GUCs available only in debug builds **Features** * [#9737](#9737) Speed up aggregation with `time_bucket_gapfill()` by performing aggregation per chunk * [#10412](#10412) Exclude chunks at execution time when a hypertable is on the parameterized side of a nested-loop join * [#10512](#10512) Block `ALTER` and `DROP` operations on a granular-refresh tracking column * [#10517](#10517) Block granular refresh on a continuous aggregate's materialization hypertable * [#10546](#10546) Add an API to disable granular refresh on a hypertable * [#10588](#10588) Allow changing the granular refresh offsets of a hypertable * [#10589](#10589) Add informational views for granular refresh * [#10626](#10626) Add the experimental Adaptive Integer Compressor (AIC) * [#10632](#10632) Add `move_to_columnstore()` to compress chunk rows without blocking concurrent DML * [#10647](#10647) Report continuous aggregate refresh statistics * [#10678](#10678) Use vectorized key processing for `UPDATE` and `DELETE` * [#10705](#10705) Use vectorized aggregation when a single-chunk query groups by an expression * [#10724](#10724) Use bulk decompression in `UPDATE`, `DELETE`, and recompression * [#10730](#10730) Add `timescaledb.cagg_refresh_stats_level` to control continuous aggregate refresh statistics * [#10770](#10770) Answer eligible `LIMIT 1` queries on compressed chunks from batch metadata without decompression * [#10780](#10780) Report materialized and deleted row counts in the continuous aggregate refresh statistics * [#10781](#10781) Flush continuous aggregate tenant tracking only once per refresh call **Bugfixes** * [#10418](#10418) Fix a hypertable `COPY` crash when pgAudit is enabled * [#10454](#10454) Make `SkipScan` use the correct index column when distinct columns are equivalent * [#10558](#10558) Fix wrong query results for chunk skipping columns at the maximum value of a chunk or after DML on a compressed chunk * [#10616](#10616) Harden the `DeferredChunkAppend` deparse and parse cycle * [#10617](#10617) Use compressed indexes for joins on segment-by columns with explicit casts, and prevent sort pushdown when the query and compression keys use different operator families * [#10630](#10630) Exclude hash-partitioned chunks at execution time on the parameterized side of a nested loop, while respecting nondeterministic collations * [#10635](#10635) Use the default B-tree operator when evaluating `first()` and `last()` aggregates * [#10639](#10639) Report rows moved to the columnstore clearly * [#10651](#10651) Avoid evaluating expressions over `GROUP BY` columns twice in single-chunk vectorized aggregation * [#10693](#10693) Use the unique index's collation when checking compressed inserts for conflicts * [#10701](#10701) Mark the result of `merge_chunks()` unordered when merged chunks can contain overlapping batches * [#10715](#10715) Truncate both the rowstore and columnstore parts of a partially compressed chunk * [#10718](#10718) Preserve foreign keys that reference a hypertable during `TRUNCATE ... CASCADE`, and allow `compress_chunk()` on referenced hypertables * [#10749](#10749) Fix an infinite refresh loop for continuous aggregates with variable-sized buckets and negative offsets * [#10747](#10747) Propagate changed parameters when rescanning a `ColumnarIndexScan` * [#10748](#10748) Propagate changed parameters when rescanning a `ConstraintAwareAppend` * [#10795](#10795) Preserve compression order for rows written before adding an order-by column with a default * [#10763](#10763) Fix a potential `ChunkAppend` segfault when parameterized clauses are removed from every chunk * [#10765](#10765) Allow negative day offsets for the `date` variant of `time_bucket()` * [#10778](#10778) Do not use `SkipScan` below a subquery with pseudoconstant qualifiers on the subquery result * [#10791](#10791) Fix potential data loss when direct compression automatically selects segment-by columns * [#10797](#10797) Preserve default values when splitting or merging compressed chunks after `ADD COLUMN` * [#10806](#10806) Do not push parallel-unsafe aggregate expressions below a `Gather` during chunkwise aggregation * [#10808](#10808) Speed up chunk creation in databases with many constraints * [#10817](#10817) Fix `DeferredChunkAppend` planning chunk queries with a restricted `search_path` * [#10783](#10783) Fix missing continuous aggregate invalidation when dropping a chunk by unqualified name * [#10827](#10827) Validate the full 64-bit version of statement-tracking callbacks * [#10830](#10830) Fix `split_chunk` routing rows to the wrong chunk * [#10883](#10838) Fix bloom filters not being used on compressed chunks after renaming a column * [#10508](#10508) Fix missing CAgg invalidations during MERGE UPDATE/DELETE * [#10844](#10844) Keep owner of user-defined jobs when hypertable owner changes **New Settings** * `timescaledb.cagg_refresh_stats_level`: controls continuous aggregate refresh statistics. Valid values are `off` (the default), `summary`, and `verbose_log`. * `timescaledb.enable_aic_compression`: enables the experimental Adaptive Integer Compressor. Off by default. * `timescaledb.enable_columnarscan_metadata_only`: answers eligible `LIMIT 1` queries on compressed chunks from batch metadata. On by default. * `timescaledb.move_to_columnstore_tuple_sort_limit`: limits how many tuples `move_to_columnstore()` sorts at once to bound memory usage. Defaults to 0 for no limit. **Thanks** * @AdrianAcala for fixing a crash with hypertable `COPY` when pgAudit is enabled [#10418](#10418) * @hyeokhee for reporting an error with parallel chunkwise aggregation and subqueries in aggregates [#10804](#10804) fixed via [#10806](#10806) * @igor2x for reporting a performance regression with joins on segment-by columns with explicit casts [#10591](#10591) fixed via [#10617](#10617) * @salmanazmat666 for reporting a refresh that could not be cancelled and ran out of memory [#10746](#10749) fixed via [#10806](#10749) * @jf0x3f for reporting a security issue when changing hypertable owner fixed via [#10844](#10844)
surister
added a commit
that referenced
this pull request
Oct 20, 2026
## 2.31.0 (2026-10-20) This release contains performance improvements and bug fixes since the 2.30.2 release. We recommend that you upgrade at the next available opportunity. **Highlighted features in TimescaleDB v2.31.0** * Improved performance for `UPDATE` and `DELETE` queries on the columnstore with vectorized key processing for bulk decompression. The vectorized aggregation makes DML and recompression operations faster through parallelism, when a single-chunk query groups by an expression, resulting in up to 6.5 times faster queries. * Preview of the new Adaptive Integer Compressor (AIC), which chooses the best encoding for each block of integer values. This results in the up to 20% improvement in compression ratios for integers, while queries benefiting from faster decompression perform up to two times better. AIC is disabled by default in this release and will be enabled by default in the `2.32.0` release. **Loader changes** This release allows controlling extension hook order to improve compatibility with other extensions. To ensure pgaudit hooks work together with timescaledb, pgaudit must come after timescaledb in `shared_preload_libraries` setting. This loader change, requires a PostgreSQL restart to enable the compatibility, but if you have no need to control the hook order, the previous loader version is enough, and you don't require a service restart. **Backward-Incompatible Changes** * [#10666](#10666) Rename `timescaledb.enable_columnarscan` to `timescaledb.debug_enable_columnarscan` to make its debugging-only purpose explicit * [#10772](#10772) Make the direct-compress batch sorting GUCs available only in debug builds **Features** * [#9737](#9737) Speed up aggregation with `time_bucket_gapfill()` by performing aggregation per chunk * [#10412](#10412) Exclude chunks at execution time when a hypertable is on the parameterized side of a nested-loop join * [#10512](#10512) Block `ALTER` and `DROP` operations on a granular-refresh tracking column * [#10517](#10517) Block granular refresh on a continuous aggregate's materialization hypertable * [#10546](#10546) Add an API to disable granular refresh on a hypertable * [#10588](#10588) Allow changing the granular refresh offsets of a hypertable * [#10589](#10589) Add informational views for granular refresh * [#10626](#10626) Add the experimental Adaptive Integer Compressor (AIC) * [#10632](#10632) Add `move_to_columnstore()` to compress chunk rows without blocking concurrent DML * [#10647](#10647) Report continuous aggregate refresh statistics * [#10678](#10678) Use vectorized key processing for `UPDATE` and `DELETE` * [#10705](#10705) Use vectorized aggregation when a single-chunk query groups by an expression * [#10724](#10724) Use bulk decompression in `UPDATE`, `DELETE`, and recompression * [#10730](#10730) Add `timescaledb.cagg_refresh_stats_level` to control continuous aggregate refresh statistics * [#10770](#10770) Answer eligible `LIMIT 1` queries on compressed chunks from batch metadata without decompression * [#10780](#10780) Report materialized and deleted row counts in the continuous aggregate refresh statistics * [#10781](#10781) Flush continuous aggregate tenant tracking only once per refresh call **Bugfixes** * [#10418](#10418) Fix a hypertable `COPY` crash when pgAudit is enabled * [#10454](#10454) Make `SkipScan` use the correct index column when distinct columns are equivalent * [#10558](#10558) Fix wrong query results for chunk skipping columns at the maximum value of a chunk or after DML on a compressed chunk * [#10616](#10616) Harden the `DeferredChunkAppend` deparse and parse cycle * [#10617](#10617) Use compressed indexes for joins on segment-by columns with explicit casts, and prevent sort pushdown when the query and compression keys use different operator families * [#10630](#10630) Exclude hash-partitioned chunks at execution time on the parameterized side of a nested loop, while respecting nondeterministic collations * [#10635](#10635) Use the default B-tree operator when evaluating `first()` and `last()` aggregates * [#10639](#10639) Report rows moved to the columnstore clearly * [#10651](#10651) Avoid evaluating expressions over `GROUP BY` columns twice in single-chunk vectorized aggregation * [#10693](#10693) Use the unique index's collation when checking compressed inserts for conflicts * [#10701](#10701) Mark the result of `merge_chunks()` unordered when merged chunks can contain overlapping batches * [#10715](#10715) Truncate both the rowstore and columnstore parts of a partially compressed chunk * [#10718](#10718) Preserve foreign keys that reference a hypertable during `TRUNCATE ... CASCADE`, and allow `compress_chunk()` on referenced hypertables * [#10749](#10749) Fix an infinite refresh loop for continuous aggregates with variable-sized buckets and negative offsets * [#10747](#10747) Propagate changed parameters when rescanning a `ColumnarIndexScan` * [#10748](#10748) Propagate changed parameters when rescanning a `ConstraintAwareAppend` * [#10795](#10795) Preserve compression order for rows written before adding an order-by column with a default * [#10763](#10763) Fix a potential `ChunkAppend` segfault when parameterized clauses are removed from every chunk * [#10765](#10765) Allow negative day offsets for the `date` variant of `time_bucket()` * [#10778](#10778) Do not use `SkipScan` below a subquery with pseudoconstant qualifiers on the subquery result * [#10791](#10791) Fix potential data loss when direct compression automatically selects segment-by columns * [#10797](#10797) Preserve default values when splitting or merging compressed chunks after `ADD COLUMN` * [#10806](#10806) Do not push parallel-unsafe aggregate expressions below a `Gather` during chunkwise aggregation * [#10808](#10808) Speed up chunk creation in databases with many constraints * [#10817](#10817) Fix `DeferredChunkAppend` planning chunk queries with a restricted `search_path` * [#10783](#10783) Fix missing continuous aggregate invalidation when dropping a chunk by unqualified name * [#10827](#10827) Validate the full 64-bit version of statement-tracking callbacks * [#10830](#10830) Fix `split_chunk` routing rows to the wrong chunk * [#10883](#10838) Fix bloom filters not being used on compressed chunks after renaming a column * [#10508](#10508) Fix missing CAgg invalidations during MERGE UPDATE/DELETE * [#10844](#10844) Keep owner of user-defined jobs when hypertable owner changes **New Settings** * `timescaledb.cagg_refresh_stats_level`: controls continuous aggregate refresh statistics. Valid values are `off` (the default), `summary`, and `verbose_log`. * `timescaledb.enable_aic_compression`: enables the experimental Adaptive Integer Compressor. Off by default. * `timescaledb.enable_columnarscan_metadata_only`: answers eligible `LIMIT 1` queries on compressed chunks from batch metadata. On by default. * `timescaledb.move_to_columnstore_tuple_sort_limit`: limits how many tuples `move_to_columnstore()` sorts at once to bound memory usage. Defaults to 0 for no limit. **Thanks** * @AdrianAcala for fixing a crash with hypertable `COPY` when pgAudit is enabled [#10418](#10418) * @hyeokhee for reporting an error with parallel chunkwise aggregation and subqueries in aggregates [#10804](#10804) fixed via [#10806](#10806) * @igor2x for reporting a performance regression with joins on segment-by columns with explicit casts [#10591](#10591) fixed via [#10617](#10617) * @salmanazmat666 for reporting a refresh that could not be cancelled and ran out of memory [#10746](#10749) fixed via [#10806](#10749) * @jf0x3f for reporting a security issue when changing hypertable owner fixed via [#10844](#10844)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Avoid full pg_constraint scan on chunk creation
Creating a chunk looks up the foreign keys that reference the
hypertable, so their triggers can also be applied to the new chunk.
The hypertable is the referenced table in these keys. This is what
declarative partitioning does for foreign keys that reference a
partitioned table. Without the triggers on the chunk, deleting or
updating a row in the chunk would not be checked against the
referencing tables.
To find these keys, the code scanned all of pg_constraint for
confrelid = hypertable. PostgreSQL has no index on confrelid, so every
chunk creation read the whole table, even when no foreign key exists.
The cost grows with the number of constraints in the database. Every
table adds some, and so does every chunk, for example a primary key,
unique constraints and the time range check. Since PostgreSQL 18,
NOT NULL constraints are stored in pg_constraint too. That adds a row
for every NOT NULL column of every table, and makes the scan slower
again.
The bottleneck was found with perf on a backend that was creating
chunks. 89.5% of the samples were in relation_get_referencing_fk(),
and the stacks showed a sequential scan of pg_constraint below it.
pg_statio_all_tables confirmed this. pg_constraint was scanned once per
chunk (157,675 scans for 156,000 chunks) and had 3.09 billion buffer
accesses, more than 300 times any other catalog table. Its
seq_tup_read stays at 0, because the scan finds no matching row, so
that counter hides the problem.
Find the foreign keys through pg_depend instead. A foreign key has a
normal dependency on each column it references, and pg_depend has an
index on (refclassid, refobjid, refobjsubid). Scan it for the
hypertable and keep only column dependencies (refobjsubid > 0). Every
chunk also has a whole-table dependency on the hypertable from
inheritance, and there can be millions of those. Fetch each candidate
constraint by OID and check contype and confrelid.
The same helper is used when a chunk is dropped and when check triggers
are swapped on PG19, so those paths get faster too.
Measured on PG19 with a table that has a primary key, a unique
constraint and 3 NOT NULL columns, 1 second chunks, 4 hypertables
filled in parallel with _timescaledb_functions.create_chunk():
Creating one chunk takes about 35 ms before and about 3 ms after, once
a hypertable holds around 45k chunks. After the change, perf shows
0.17% of the time in relation_get_referencing_fk(). pg_constraint was
scanned 4 times in total and used about 44 buffer accesses per chunk,
down from about 19.8k. The size of the catalogs per chunk did not
change.
Co-Authored-By: Claude Sonnet 5.5 noreply@anthropic.com