Query icon
OutputValues icon
Log icon
If icon
SlackIncomingWebhook icon
Pause icon
Loop icon
Queries icon
Fail icon
Schedule icon

pgvector IVFFlat Undersized Lists Rebuild Guard

Find pgvector IVFFlat indexes whose lists is too small for the table, rebuild them at the right lists with no index-free window, then verify.

Categories
DataInfrastructure

REINDEX cannot fix an IVFFlat index whose lists is wrong. lists is a build parameter, baked into the index when it is created. REINDEX rebuilds the same index with the same parameters. The only repair is to drop the index and create it again with a different number.

That matters because the right lists depends on how many rows the table holds. An IVFFlat index partitions the vectors into lists buckets and a query probes only a few of them, so the bucket count is what decides how much of the table a probe has to read. pgvector's guidance is about rows / 1000 up to a million rows, then sqrt(rows). An index built when the table held a few thousand rows keeps its original small lists after the table grows to millions. Each bucket is then enormous, each probe reads far more vectors than it should. Recall drops because a fixed number of probes now covers a smaller fraction of the data.

Nothing reports it. The index is valid. \d shows it. Queries still return rows. They are just slower and less accurate. No pg_stat counter or log line says why.

This blueprint was created by zkasuran.

Safety

  • Read-only by default. dry_run is true and auto_remediate is false, so a plain run reports and rebuilds nothing.
  • A rebuild happens only when auto_remediate is true and dry_run is false. It then waits for a human to resume the Pause with approved set true. An unanswered gate reads as not approved.
  • There is no window without an index. The naive repair is DROP INDEX then CREATE INDEX. Between those two statements the column has no approximate nearest neighbour index at all, so every similarity query falls back to a sequential scan with an exact distance per row. On a large table the rebuild is minutes to hours, which makes that window a real outage rather than a formality. This flow builds the replacement under a temporary name first, then drops the old index, then renames the new one into its place. All four statements run as one transaction. Other sessions keep using the old index until the swap commits.
  • Because the swap is one transaction, a failure anywhere in it rolls the whole thing back and the original index is still there, under its original name. A half-finished rebuild cannot leave the column unindexed.
  • The operator class is read from pg_index.indclass and replayed exactly. Rebuilding with a different distance would silently produce an index the planner never uses for the queries that relied on it, which looks like a successful repair and is not.
  • The index keeps its name, so nothing that references it by name has to change.
  • undersize_factor means normal growth is not a finding. At the default of 4.0 the table has to have grown about fourfold past what the index was built for.
  • The re-read of the catalog is the real gate. The run fails if any target is still below the lists it was meant to get, if its operator class changed or if the index is missing.

What the rebuild costs

The transaction is safe, not free. The CREATE INDEX holds a lock that blocks writes on that table for the whole build. The DROP INDEX takes a brief exclusive lock at the end that blocks reads for a moment. Both copies of the index exist on disk until the swap commits, so plan for the extra space. Run it in a maintenance window, which is what the Pause is for.

How it works

  1. detect (io.kestra.plugin.jdbc.postgresql.Query, read-only) joins pg_index to pg_class and pg_am to find every ivfflat index, parses the lists value out of the index reloptions (falling back to pgvector's default of 100 when the index was created without one), reads the estimated row count of its table, derives the recommended lists from the row count then returns one row per index that sits at least undersize_factor times below it. Each row carries the first key column from unnest(indkey) WITH ORDINALITY, the operator class from unnest(indclass) WITH ORDINALITY joined to pg_opclass plus the exact rebuild script built inside PostgreSQL with format('%I').
  2. summarize (io.kestra.plugin.core.output.OutputValues) builds the readable target list and the JSON the loop iterates, so the log, the alert and the loop read the same set.
  3. log_detect (io.kestra.plugin.core.log.Log) logs the count, the targets and the mode.
  4. guard (io.kestra.plugin.core.flow.If) branches on the count. With none found, clean logs and the run ends. Otherwise findings_alert posts the finding on every detection.
  5. mode (io.kestra.plugin.core.flow.If) enters the remediation branch only when auto_remediate is true and dry_run is false. Otherwise report_only lists what would be rebuilt and stops.
  6. approval_gate (io.kestra.plugin.core.flow.Pause) holds the run for a human. remediate_lists (io.kestra.plugin.core.flow.Loop, concurrencyLimit: 1) then runs one swap per index, in turn, through io.kestra.plugin.jdbc.postgresql.Queries with transaction: true: create under a temporary name, drop the old, rename the new into place.
  7. reverify reads every IVFFlat index again, verify_plan compares each target with the catalog. verify_result fails the run through io.kestra.plugin.core.execution.Fail if any target is still undersized, lost its operator class or is missing.

What you get

  • Every IVFFlat index whose lists no longer fits its table, largest table first, with the value it has and the value it should have.
  • An index created without an explicit lists handled correctly, at pgvector's default of 100, which is undersized for anything past a few hundred thousand rows.
  • A rebuild that preserves the index name, the key column and the operator class, so queries that used the index keep using it.
  • A swap with no index-free window and no half-finished state, because it is one transaction.
  • A real verification step. The run passes only when the catalog shows every target at or above the lists it was meant to get, with the operator class it started with.
  • Slack alerts on the findings and on any failure.

Who it's for

  • Teams running semantic search or retrieval augmented generation on PostgreSQL with pgvector, where the embedding table grows every day but the index was built once.
  • Platform engineers who inherited a pgvector schema and have no idea what lists any of its indexes were built with.
  • Anyone whose vector search got slower and less accurate after a backfill and who has already tried REINDEX.

Why orchestrate this with Kestra

The catalog query answers it once. Kestra runs it every month and after every backfill, so an index the table has outgrown is caught before the recall complaints arrive. The rebuild sits behind auto_remediate, dry_run and a Pause, which is what a lock taking rebuild needs. One index per loop iteration keeps a failure isolated. The re-read of the catalog decides whether the run passed. The execution history records which index was retuned, from what to what and when.

Tested end to end

On Kestra 2.0.5 OSS against pgvector/pgvector:pg16 (pgvector 0.8.2, read from vector.control), with a local HTTP sink standing in for Slack. Seeded in one database:

  • docs.embedding vector(3), an ivfflat index with vector_cosine_ops built with lists = 1 while the table held 50 rows, then grown to 40,000 rows, where guidance asks for 40;
  • docs.title_embedding vector(3), an ivfflat index with lists = 40 on the same 40,000 rows, already at guidance;
  • docs.body_embedding vector(3), an hnsw index, which has no lists at all;
  • notes.summary vector(3), an ivfflat index with lists = 1 on 500 rows, correct at that size;
  • big.e vector(3), an ivfflat index created with no lists clause on 500,000 rows, so it carries pgvector's default of 100 where guidance asks for 500;
  • plain_items, no vector column.
Run Inputs Result
1 defaults, healthy state 0 findings, clean logged
2 defaults, degraded state 1 finding, public.docs_embedding_ivf_idx at lists = 1 against a recommended 40. The already sized index, the HNSW index and the small table are absent. Alert sent
3 auto_remediate: true, dry_run: true Same finding, nothing rebuilt, report_only
4 auto_remediate: true, dry_run: false, approved Index swapped to lists = 40, same name, same vector_cosine_ops, verified from pg_class and pg_index
5 auto_remediate: true, dry_run: false, resumed without approval nothing rebuilt, not_approved
6 approved, but the connecting role does not own the table the swap was rejected, the original index survived at lists = 1 and the verify step failed the run
7 unreachable database run failed and the errors block posted to Slack
8 two targets, approved the loop ran both swaps in turn, lists 100 to 500 on the 500,000 row table and lists 1 to 40 on the other, both keeping vector_cosine_ops

The plan is the evidence. With lists = 1 the index has one bucket, so EXPLAIN (ANALYZE, BUFFERS) on SELECT id FROM docs ORDER BY embedding <=> '[0.1,0.2,0.3]' LIMIT 5 read every entry page of the index on a single probe (shared hit=193). After the swap to lists = 40 the same query at ivfflat.probes = 1 read about a fortieth of them (shared hit=21).

The zero window was measured too. With one session holding an open transaction that had already built the replacement, a second session still planned Index Scan using docs_embedding_ivf_idx on the same column, so similarity queries never fell back to a sequential scan during the build.

Prerequisites

  • pgvector installed in the database (CREATE EXTENSION vector) with at least one ivfflat index. Detection reads pg_index, pg_class, pg_am, pg_opclass and pg_attribute, which any role can read.
  • Remediation needs a role that owns the tables, since CREATE INDEX and DROP INDEX do.
  • Raise maintenance_work_mem for the session or the database before a large rebuild. A build that does not fit in memory falls back to a much slower path.
  • Space for both copies of the index until the swap commits.
  • Local testing:
    • docker run -d --name pgvec -p 5432:5432 -e POSTGRES_PASSWORD=pg pgvector/pgvector:pg16;
    • CREATE EXTENSION vector, a table with a vector column, an ivfflat index built with WITH (lists = 1) while the table is tiny, then a few tens of thousands of rows inserted after it.

Secrets

  • POSTGRES_USERNAME and POSTGRES_PASSWORD: credentials used by every query.
  • SLACK_WEBHOOK_URL: used by findings_alert and the errors block.
  • In Kestra OSS, provide each one as a base64 encoded environment variable prefixed SECRET_.

Inputs

Input Default Purpose
postgres_url jdbc:postgresql://localhost:5432/postgres Database to check
use_secret_auth true Read credentials from secrets. Set false only in a disposable test
postgres_username postgres Inline username when use_secret_auth is false
postgres_password empty Inline password when use_secret_auth is false
only_schema empty Restrict to one schema
min_table_rows 1000 Smallest table worth retuning
undersize_factor 4.0 How far below guidance an index has to sit to be reported
max_lists 10000 Ceiling on the recommended lists
dry_run true Must be false for a rebuild to run
auto_remediate false Must be true for a rebuild to run

Quick start

  1. Add the POSTGRES_USERNAME, POSTGRES_PASSWORD and SLACK_WEBHOOK_URL secrets.
  2. Import the flow and set postgres_url.
  3. Run it once and read the findings. Each line gives the index, its column, its operator class, the rows the table holds, the lists it has and the lists it wants.
  4. Lower undersize_factor to 2.0 to see the indexes that are drifting rather than badly wrong.
  5. Pick a maintenance window, raise maintenance_work_mem, then run it with auto_remediate: true and dry_run: false and resume the Pause with approved set true.
  6. Raise ivfflat.probes afterwards. More lists with the same probes means each query reads a smaller share of the data, so recall needs the probes to come up with the lists. pgvector suggests about sqrt(lists).
  7. Enable the monthly_ivfflat_lists_check trigger, which always runs in safe mode.

How to extend

  • Swap CREATE INDEX for CREATE INDEX CONCURRENTLY where no write lock can be taken. It cannot run inside a transaction, so the swap stops being atomic and a failure can leave an invalid index under the temporary name, which the verify step already reports.
  • Set ivfflat.probes per database with ALTER DATABASE ... SET ivfflat.probes as part of the same change, so probes and lists move together.
  • Drive the recommendation from count(*) instead of reltuples where the table is not analyzed often. It is exact and much more expensive.
  • Add an HNSW branch for indexes whose m and ef_construction were left at defaults on a table that has since grown.
  • Loop over several JDBC URLs to sweep every database of a cluster.
  • Record each rebuild in a table so the next run can see how long the previous one took on that table.

Links

See How

New to Kestra?

Use blueprints to kickstart your first workflows.