Home / Databases / PostgreSQL

DatabasesHow-toAdvanced

PostgreSQL GIN indexes: stop insert latency spikes and slow searches caused by the pending list

Inserts into a jsonb, array or full-text table stall for seconds, or searches slow down as data arrives. Measure the GIN pending list, then pick between fastupdate, limits and vacuum.

Deepak Bhardwaj7 min read

Applies toPostgreSQL 13 and later, including managed services (extension availability varies)

Most inserts into a table with a GIN index take a millisecond. Every few minutes one takes seconds. Or searches get slower through the day and recover after autovacuum. Both come from the same place: the GIN pending list.

How the pending list behaves

One row can produce hundreds of GIN keys (lexemes, jsonb paths, trigrams). With fastupdate = on, the default, new entries go to an unsorted list of pages. They move into the main tree later, in bulk. Four events flush the list:

  • VACUUM of the table
  • an autoanalyze of the table
  • gin_clean_pending_list()
  • an insert that takes the list over gin_pending_list_limit (4MB by default)

The last one is the spike: the unlucky session does the cleanup inside its own INSERT or UPDATE. The slow search has the opposite cause. Every GIN scan reads the entire pending list as well as the tree, so a large list makes every search pay.

Symptom Cause Fix
Rare inserts 100–1,000x slower than median Foreground flush of the list Smaller limit, fastupdate = off, or background flush
Searches slow until vacuum runs Large pending list scanned each time Lower limit; flush more often
All inserts slow, no spikes Too many keys per row, or cold index pages Fewer keys, more cache, partitioning
Spikes get worse after raising the limit Each flush now has more work Revert; size for latency
Many sessions waiting during a flush Cleanup and page contention Shorter flushes, smaller batches

Confirm it

List GIN indexes and their options:

SELECT n.nspname, t.relname AS table_name, i.relname AS index_name,
       i.reloptions, pg_size_pretty(pg_relation_size(i.oid)) AS size
FROM pg_class i
JOIN pg_am a ON a.oid = i.relam AND a.amname = 'gin'
JOIN pg_index x ON x.indexrelid = i.oid
JOIN pg_class t ON t.oid = x.indrelid
JOIN pg_namespace n ON n.oid = t.relnamespace
ORDER BY pg_relation_size(i.oid) DESC;

Measure the pending list with pgstattuple. The caller needs pg_stat_scan_tables or an explicit grant.

CREATE EXTENSION IF NOT EXISTS pgstattuple;
SELECT * FROM pgstatginindex('public.docs_body_gin');

pending_pages × 8 kB (the default block size) is the list size. Sample it every few seconds. A sawtooth that drops at the limit, with slow inserts at each drop, confirms a foreground flush. Superusers can also see tree sizes:

CREATE EXTENSION IF NOT EXISTS pageinspect;
SELECT n_pending_pages, n_pending_tuples, n_entry_pages, n_data_pages, n_entries
FROM gin_metapage_info(get_raw_page('public.docs_body_gin', 0));

Check the spread in pg_stat_statements. A maximum far above the mean, with a high standard deviation, matches the pattern:

SELECT calls, mean_exec_time, stddev_exec_time, max_exec_time, left(query, 80) AS query
FROM pg_stat_statements
WHERE query ILIKE 'insert into%docs%'
ORDER BY max_exec_time DESC
LIMIT 5;

Catch one in the act:

SELECT pid, state, wait_event_type, wait_event, now() - query_start AS runtime, left(query, 80)
FROM pg_stat_activity
WHERE state = 'active' AND query ILIKE '%docs%';

For the search side, compare buffers before and after a manual flush on a test copy:

EXPLAIN (ANALYZE, BUFFERS)
SELECT id FROM docs WHERE body_tsv @@ to_tsquery('english', 'timeout & replica');

SELECT gin_clean_pending_list('public.docs_body_gin');

The function returns the number of pages removed and needs index ownership. A large fall in buffers on the bitmap index scan means the list was the cost. Run EXPLAIN twice so caching doesn't mislead you.

Warning

gin_clean_pending_list on a very large list is I/O heavy and generates WAL. Run the first flush off-peak and watch replication lag. It cannot run during recovery, so a standby's pending list is fixed on the primary.

Choose a fix

Steady latency: turn fastupdate off

Every insert pays its own cost. Throughput per row falls, but the spikes go. Use it for OLTP tables with small documents and a tail-latency target.

SET lock_timeout = '2s';
ALTER INDEX public.docs_body_gin SET (fastupdate = off);
RESET lock_timeout;
SELECT gin_clean_pending_list('public.docs_body_gin');

The option change needs a strong, brief lock on the index, and planning of queries on the table needs that index too. Without lock_timeout, it can queue behind a long query and freeze the table.

Caution

Turning the option off does not empty the existing list. Flush right after the change with VACUUM or gin_clean_pending_list, and confirm pending_pages = 0 with pgstatginindex. If the clean function returns 0 while pages remain, run VACUUM docs;.

Short flushes: lower the limit per index

SET lock_timeout = '2s';
ALTER INDEX public.docs_body_gin SET (gin_pending_list_limit = 512);
RESET lock_timeout;

The per-index value is an integer in kilobytes. A smaller list gives more frequent, shorter flushes and bounded scan cost. Test 256, 512 and 1024 under production-like write rates and compare p99.

Write-heavy ingest: keep the list and flush in the background

If a large list is fine between flushes, move the work off user sessions. Make autovacuum visit often enough to beat the foreground limit:

ALTER TABLE docs SET (
  autovacuum_vacuum_insert_scale_factor = 0.0,
  autovacuum_vacuum_insert_threshold    = 20000,
  autovacuum_analyze_scale_factor       = 0.0,
  autovacuum_analyze_threshold          = 20000
);

The insert thresholds exist from PostgreSQL 13. Pick a threshold from your own rate: rows per second × the flush interval you want. Or schedule an explicit flush:

-- pg_cron, every minute
SELECT cron.schedule('flush-docs-gin', '* * * * *',
  $$SELECT gin_clean_pending_list('public.docs_body_gin')$$);

Don't rely on scheduled flushes alone. A missed run brings the foreground flush back. Give autovacuum enough memory as well: autovacuum_work_mem (or maintenance_work_mem when it is -1) lets its flush batch more keys per pass. It is allocated per worker, so multiply by autovacuum_max_workers.

Bulk loads: drop and rebuild

For a one-off load of a large share of the table, build the index afterwards:

SET maintenance_work_mem = '2GB';
CREATE INDEX CONCURRENTLY docs_body_gin ON docs USING gin (body_tsv);

GIN builds are very sensitive to maintenance_work_mem. PostgreSQL 18 and later can build GIN indexes in parallel; max_parallel_maintenance_workers caps the workers, and the memory setting covers the whole build rather than each worker.

Reduce the keys before tuning the list

The cheapest entry is the one you don't create.

  • jsonb: jsonb_path_ops creates one hashed entry per path and value. It is normally smaller than the default class, but doesn't support the key-exists operators (?, ?|, ?&).
  • One attribute searched: index the expression, such as (payload -> 'tags'), not the whole document.
  • Scalar equality only: use a B-tree on (payload ->> 'customer_id').
  • Updates: changing an indexed column, or losing HOT for any reason, re-inserts keys for the new tuple. Keep volatile columns (counters, timestamps) in a separate table, or leave them unindexed.
  • Partial indexes: if searches only hit live rows, add WHERE archived = false.

Tip

gin_fuzzy_search_limit caps the result set of GIN scans and returns a random subset. It is not a tuning knob for exact queries. Leave it at 0 unless the application accepts sampled results.

Trade-offs at a glance

Choice Insert p99 Insert throughput Search cost Use for
Default 4MB Spiky High Rises with list General use
Small limit Short spikes Medium Bounded Mixed workloads
fastupdate = off Steady Lowest Lowest Latency-sensitive OLTP
Big limit and background flush Good while flush keeps up Highest Highest between flushes Ingest pipelines

Under SERIALIZABLE, fast update also makes predicate locking coarser, so it can raise the rate of serialization failures. Test it off if you see them on these tables.

Prevent it next time

  • Graph pending_pages per large GIN index and alert when it stays above your chosen limit.
  • Alert on the ratio of p99 to p50 for writes, not only the average.
  • Cancelled autovacuums leave lists unflushed. Check last_autovacuum and last_autoanalyze in pg_stat_user_tables.
  • Review every new GIN index for keys per row and write rate before it ships.
  • Load-test with concurrent writers until the list has flushed at least ten times; a short test may never hit a flush.