DEV Community

Cover image for Autovacuum ran 443,863 times and cleaned nothing: orphan queries on a read replica
Sergey Stebakov
Sergey Stebakov

Posted on Edited on Originally published at stebas.com

Autovacuum ran 443,863 times and cleaned nothing: orphan queries on a read replica

Originally published at stebas.com.

At night, deposits in a payments service started getting stuck in pending. The money had already been taken by the payment provider, the webhook had been accepted, and the balance was not credited. The delay kept growing until it peaked at 85 minutes. Nothing was lost in the end. But that was a long night for support and for players.

The pipeline, and the first lie

The service uses a transactional outbox. The webhook handler writes an event to an outbox table in the same transaction as the business change. A relay worker reads the table in order, publishes to Kafka and deletes the rows it has sent. The wallet consumes the event and credits the balance.

The relay's health metric said alive = 1 the whole night, while the queue grew to 560,000 events. Alive is not the same as keeping up. The signals that mattered were the age of the oldest pending event (normal is 1–2 seconds, it reached 5,100) and the publish rate compared with the same hour on previous nights. The publish rate was half of normal, and incoming traffic was flat. So this was not a flood: the relay had slowed down.

The relay's logs showed its own queries to the outbox table timing out.

A table that vacuum could not clean

On the primary, the table statistics told the story:

select n_live_tup, n_dead_tup, autovacuum_count,
       pg_size_pretty(pg_total_relation_size(relid))
from pg_stat_user_tables where relname = 'outbox_message';
Enter fullscreen mode Exit fullscreen mode

About 0.5 million live rows, 10.8 million dead ones and 9.7 GB on disk for a table that is normally a few hundred megabytes. autovacuum_count was 443,863 and went up every time I looked. Vacuum was working constantly, and it still could not remove anything.

When vacuum runs and removes nothing, something is holding the xmin horizon: an old snapshot that might still need those row versions. A table that inserts and deletes every second turns into a field of dead tuples that every ordered SELECT has to walk through.

Three places to look, in order

  1. Long or idle in transaction sessions on the primary (pg_stat_activity, backend_xmin).
  2. Replication slots (pg_replication_slots, age(xmin)).
  3. Forgotten two-phase transactions (pg_prepared_xacts).

The primary was clean. The slots were not: both physical slots, one per read replica, had age(xmin) around 9.3 million. The database ran with hot_standby_feedback on. Each replica reports the oldest snapshot it still needs back to the primary, so a long query on a replica stops vacuum on the primary.

On the replicas I found nine SELECT count(*) queries that had been running for 17 hours. Their application_name pointed to a ReplicaSet that no longer existed. They came from an admin segment builder: an operator had built a filter that matched almost every user. The HTTP request returned a 500 after 60 seconds, the operator retried, and each retry started another query. The application gave up but never cancelled the query in the database. Restarting or replacing the pod does not stop a query that is already running on the server either.

The fix took seconds

select pid, pg_cancel_backend(pid) from pg_stat_activity
 where application_name like '<dead-replicaset>-%'
   and xact_start < now() - interval '1 hour';
Enter fullscreen mode Exit fullscreen mode

I ran this on each replica, with a narrow filter, after writing down the pids and the query texts. The slots' age(xmin) dropped from 9.3 million to double digits. The next vacuum pass finished, and the backlog went from 510,000 to 11 in about two minutes. All delayed deposits were published.

What I deliberately did not do: restart the relay (the backlog lives in the table, and an interrupted batch can duplicate messages), run VACUUM FULL (an exclusive lock that stops the relay completely), or delete rows from the outbox (they are undelivered payments).

Why monitoring missed it

The Postgres exporter scraped only the primary. Its longest-transaction metric showed 30–57 seconds while the replicas held 17-hour queries. The first alert that fired was the outbox age alert, hours after the horizon was pinned.

Takeaways

  • Vacuum that runs and removes nothing is a pinned horizon, not a slow vacuum. Check sessions, slots and prepared transactions.
  • With hot_standby_feedback, a replica can block vacuum on the primary. Monitor the replicas, not only the writer, and alert on slot age(xmin).
  • A client timeout does not cancel a server query. Set statement_timeout on read-only roles. A query should not outlive the request that started it.
  • "Alive" is not throughput. For queues, alert on the age of the oldest item and compare rates with yesterday, not with zero.

Top comments (12)

Collapse
 
hritik_chaudhary_5db0056f profile image
Hritik Chaudhary •

Good diagnosis order. One design option beyond statement_timeout: run the admin and segment-builder queries on their own replica with hot_standby_feedback off. Long queries there get cancelled by recovery conflicts when they collide with vacuum cleanup (max_standby_streaming_delay sets how patient it is), but they can no longer pin the primary's horizon. The replicas serving latency-sensitive reads keep feedback on. You trade some cancelled reports for a primary that vacuum can always clean. For the alert, pg_stat_replication.backend_xmin on the primary shows the horizon each replica reports, so one query covers all of them.

Collapse
 
stebas profile image
Sergey Stebakov •

Agree, separate replica with feedback off is a good option. But for this query I think it should not be on postgres at all. Count over all users is analytics work.

One note about backend_xmin. If replica uses replication slot, backend_xmin is NULL and xmin is in pg_replication_slots. I checked it on PG 17 with test replica to be sure. In our case replicas had slots, so we found it there. Better to check both.

Collapse
 
hritik_chaudhary_5db0056f profile image
Hritik Chaudhary •

Good catch, I only had the no-slot case in mind. With a slot the feedback xmin sits in pg_replication_slots, so a check that reads only pg_stat_replication.backend_xmin will show NULL and miss the standby. Worth querying both. Agreed on the count too: all-users analytics belongs in a warehouse or a materialized rollup, not on the replica.

Collapse
 
stebas profile image
Sergey Stebakov •

Here is the test on PG 17, replica with slot:

Collapse
 
lycore profile image
Lycore Development •

Good diagnosis path, and the point that alive=1 is not the same as keeping up is the part many teams miss. With hot_standby_feedback on, a runaway replica query holding back the primary's xmin is nasty. Would you consider setting max_standby_streaming_delay or a statement_timeout on the replica role used by the admin segment builder? That would cap the damage even if another filter matches nearly every user.

Collapse
 
stebas profile image
Sergey Stebakov •

Thanks. statement_timeout on the read-only role yes, this is the plan, it caps the query no matter what filter somebody builds.

max_standby_streaming_delay will not help here. With hot_standby_feedback on, vacuum on the primary does not remove rows the replica still needs, so there is no recovery conflict and nothing to cancel. The query can run forever. That setting only works when feedback is off.

Collapse
 
kevinhall profile image
Kevin Hall •

one catch with putting statement_timeout on the role is that only new sessions pick it up, so long lived pool connections run without it until they get recycled

Collapse
 
userxnom profile image
Abdullah Naseer •

Sergey, the number that reframes the whole story for me is 443,863 — autovacuum running constantly and removing nothing is the kind of metric that looks like effort and is actually a stuck horizon. The detail I would steal is the diagnosis order: sessions, then slots, then prepared transactions. Most people would start by tuning vacuum.

One thing that stuck with me: the slot age(xmin) of 9.3 million was visible from the primary the whole time — pg_replication_slots lives there — so the monitoring gap was not where the data lived, it was which number got an alert. Longest transaction at 30–57 seconds looked calm because the 17-hour queries were sitting on the replicas.

And the orphaned application_name is the part that would keep me up at night: a ReplicaSet that no longer exists, still holding nine count(*) queries open for 17 hours. A client timeout clearly fired and nobody noticed, because the server kept running.

One question: after this, did you put a guard on the segment-builder role itself — a statement_timeout, or a periodic check for sessions whose application_name no longer matches a live deployment — or is the slot age(xmin) alert the only tripwire now?

Collapse
 
stebas profile image
Sergey Stebakov •

Thanks. You are right, the slot xmin was on the primary all the time, we just did not alert on it.

About your question. Not yet. Now we have alerts on the outbox (age of oldest event and relay rate) and a runbook for on-call: if vacuum runs all the time but dead tuples do not go down, look who holds xmin. statement_timeout for the read-only role and xmin alert on replicas are in the plan, not done yet. I need to push this.

Checking application_name against live pods is a good idea, I did not think about it. Will add it.

Collapse
 
syedfahads profile image
Syed Fahad •

did you look at partitioning the outbox and dropping old partitions? a pinned xmin can stop vacuum but it can't stop a drop

Collapse
 
hongke_shop profile image
HONGKE •

Great write-up, that debugging story was really interesting to follow!

Collapse
 
stebas profile image
Sergey Stebakov •

Thanks, glad you liked it!