Scrivio Interview library
DebuggingIntermediate6 min read · updated 12 November 2026

A PostgreSQL index on a queue table is 25 GB while the table holds 200,000 live rows. Queries on it are getting slower. Explain the cause and how you fix it without downtime.

A queue table inserts and deletes rows constantly. Vacuum removes the dead index entries, but the freed space sits in pages that new keys never land in, and B-tree pages are not merged back eagerly, so the index grows to 25 GB of mostly empty pages, and anything that holds back vacuum makes it worse. We confirm it with pgstatindex and pg_stat_user_tables, fix it now with REINDEX INDEX CONCURRENTLY (or pg_repack), and prevent it with aggressive autovacuum for the table, no long-running transactions, and partitioning the queue so old partitions are dropped.

Why this question is asked

Queue tables are a common pattern in Java services: an outbox, a job table, a notification queue. They are also the classic source of index bloat, because their workload, a steady stream of inserts at one end and deletes at the other, is the worst case for B-tree space reuse. Interviewers ask this debugging scenario because the numbers, 25 GB for 200,000 rows, point clearly at bloat, and the fix must be done without downtime. In this answer, we will see why queue indexes bloat, confirm it with measurements, rebuild without blocking, stop it from coming back, and look at what newer PostgreSQL versions improve.

1Why Queue Indexes Bloat

Think of an index on (created_at) or on a sequence id in a queue table. New jobs always get the newest keys, so they are inserted at the right edge of the B-tree. Workers delete processed jobs, which have the oldest keys, at the left edge. The live data is a small window that keeps moving to the right.

When vacuum runs, it removes the dead entries from the left pages. Pages that become completely empty can be recycled for new pages, but only after vacuum has processed them and no transaction can still need them, and pages with even a few live or not-yet-removable entries stay in place. Because new keys never go to the left, the half-empty pages on the left are never refilled. If vacuum falls behind, or something prevents it from removing dead entries, the index grows with every cycle. 200,000 live rows need perhaps 10 MB of index; the other 25 GB are empty or dead space that scans still have to walk through.

Step throughHow the queue index grows
  1. Insert new jobsalways at the right edge
  2. Delete processed jobsdead entries at the left edge
  3. Can vacuum remove them?
    YesSpace freed, but left pages rarely reusedNoDead entries pile up
  4. Long transaction or replica feedbackholds back the xmin horizon
  5. Index keeps growing25 GB for 200,000 live rows

5 steps in order. Play them, or step through them one at a time.

2Confirming the Diagnosis

We measure before acting. pgstatindex shows how full the leaf pages are, and pg_stat_user_tables shows whether autovacuum keeps up.

SQL
SELECT avg_leaf_density, leaf_pages, deleted_pages, pg_size_pretty(index_size)
FROM pgstatindex('jobs_created_at_idx');
-- 4.2 | 3150000 | 210000 | 25 GB -- leaf pages are 4 percent full
SELECT n_live_tup, n_dead_tup, last_autovacuum, autovacuum_count
FROM pg_stat_user_tables WHERE relname = 'jobs';
-- 200000 | 5400000 | 2026-11-05 03:12 | 41
SELECT pid, now() - xact_start AS age, state, left(query, 40)
FROM pg_stat_activity WHERE xact_start IS NOT NULL ORDER BY age DESC LIMIT 3;
-- 8812 | 06:41:10 | idle in transaction | SELECT ... FROM report_x

Three findings fit together. The index is 4 percent full. The table has 5.4 million dead rows for 200,000 live ones, so vacuum is not removing them. And a session has been idle in transaction for nearly seven hours. That last one matters most: vacuum can only remove row versions that no running transaction could still see, and the oldest open transaction sets that limit, called the xmin horizon. One forgotten transaction stops cleanup for the whole database.

3Fixing It Now Without Downtime

First we remove what holds vacuum back, here by ending the idle transaction after checking with its owner, and let vacuum run. Then we rebuild the index without blocking the queue.

SQL
SELECT pg_terminate_backend(8812); -- after confirming it is safe
VACUUM (VERBOSE) jobs;
REINDEX INDEX CONCURRENTLY jobs_created_at_idx; -- PostgreSQL 12+, writes continue
SELECT pg_size_pretty(pg_relation_size('jobs_created_at_idx')); -- 9 MB

REINDEX INDEX CONCURRENTLY builds a fresh, compact copy while inserts and deletes continue, then swaps it in. It needs a moment of lock at the swap and fails if it cannot get it in time, in which case it leaves an invalid index we must drop. If the table itself is bloated too, pg_repack rebuilds the table and all its indexes online with short locks. Queries become fast again at once, because they now walk a few thousand pages instead of millions.

4Preventing It From Coming Back

A rebuild without fixing the causes buys a few weeks. For the queue table we set autovacuum to run very often: a tiny scale factor or a fixed threshold, so vacuum runs every few thousand changes instead of after 20 percent of the table. We guard against long transactions with idle_in_transaction_session_timeout and statement timeouts for application roles, and alert on transactions older than a few minutes. We also check replication slots and replicas with hot_standby_feedback, which can hold back the horizon too.

The strongest structural fix is partitioning the queue by time, for example one partition per day or hour. Processed jobs are not deleted one by one; whole old partitions are dropped once all their jobs are done, which removes their indexes instantly with no bloat at all.

SQL
ALTER TABLE jobs SET (
autovacuum_vacuum_scale_factor = 0,
autovacuum_vacuum_threshold = 5000, -- vacuum after about 5,000 dead rows
autovacuum_vacuum_cost_delay = 0
);
ALTER ROLE app_user SET idle_in_transaction_session_timeout = '60s';

5What Newer PostgreSQL Versions Improve

PostgreSQL 13 added B-tree deduplication, which stores repeated key values once with a list of row pointers, shrinking indexes with many duplicates. PostgreSQL 14 added bottom-up index deletion, which removes dead entries from a page when an update would otherwise split it, so version churn from updates bloats indexes less. Both reduce bloat, but they help most with duplicates and updates. The queue pattern of deleting old keys and inserting new ones elsewhere still leaves empty space behind, and nothing helps if a long transaction blocks cleanup. Check your version for the exact behaviour.

6Follow-up questions

Why does a long-running transaction on a replica with hot_standby_feedback cause bloat on the primary?

With hot_standby_feedback on, the replica tells the primary the oldest transaction it is still running, so that the primary does not remove row versions the replica's query might still need. That avoids query cancellations on the replica, but it means the primary's vacuum treats the replica's oldest query as if it were a local one. A six-hour report on a replica therefore holds back the xmin horizon on the primary, and vacuum cannot remove dead rows or index entries created during those six hours. On a queue table with constant churn, that is millions of dead entries. Statement timeouts on replicas, a separate replica for long reports without feedback, or limits such as max_standby_streaming_delay address it.

Should queue tables live in PostgreSQL at all?

For moderate volumes, yes. A PostgreSQL queue with FOR UPDATE SKIP LOCKED, a small partial index and good vacuum settings is simple and transactional. At very high volumes, or when many consumers need replay and retention, a log system such as Kafka is the better tool. The decision is about volume and semantics, not about bloat alone.

7Conclusion

In this answer, we saw that a queue table's index bloats because new keys arrive at one end and deleted keys leave space at the other, B-tree pages are not merged back eagerly, and anything holding back the xmin horizon stops vacuum from cleaning. pgstatindex and pg_stat_user_tables confirmed the cause, and REINDEX INDEX CONCURRENTLY or pg_repack fixed it without downtime. To prevent it, we set aggressive autovacuum for the table, limited long-running transactions with timeouts, watched replicas and slots, and considered partitioning so old partitions are dropped. Newer versions reduce bloat with deduplication and bottom-up deletion but do not remove this pattern.

What to say in the interviewAbout 90 seconds aloud

Open with

25 GB of index for 200,000 live rows is almost certainly bloat. In a queue table, new jobs get the newest keys at the right edge of the B-tree and processed jobs are deleted from the left edge.

Then, if they want more

Vacuum removes dead entries, but that space can only be reused by keys that belong on those pages, which never come, and B-tree pages are not merged back eagerly, so the index fills with nearly empty pages that every scan still walks.

It gets much worse if vacuum cannot remove dead entries at all, for example because of a long-running or idle-in-transaction session holding back the xmin horizon. I would confirm with pgstatindex, expecting a very low leaf density, look at dead tuples and last autovacuum in pg_stat_user_tables, and check pg_stat_activity for old transactions.

To fix it now, I would end whatever holds back vacuum, run vacuum, and then REINDEX INDEX CONCURRENTLY, which rebuilds without blocking the queue on PostgreSQL 12 and later; pg_repack if the table is bloated as well.

To prevent it: autovacuum settings for that table so it runs every few thousand changes, idle_in_transaction_session_timeout and statement timeouts, watching replicas with hot_standby_feedback and replication slots, and ideally partitioning the queue by time so we drop old partitions instead of deleting rows. Deduplication in 13 and bottom-up deletion in 14 reduce bloat, but they do not remove this pattern.

About this answer

Last updated
12 November 2026
Versions it names
PostgreSQL 12, PostgreSQL 13, PostgreSQL 14
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A PostgreSQL index on a queue table is 25 GB while the table holds 200,000 live rows....": https://scrivio-interview-library.netlify.app/databases/indexing/19b002cf0c/