skip to content

On a busy PostgreSQL news site, each page view runs UPDATE articles SET view_count = view_count + 1, n_tup_hot_upd stays near zero, and the table and its indexes keep growing; why, and what do you change?

level: seniorimportance: should knowfreq 46%

answer

  1. each increment is a new tuple
  2. what rules out HOT here?
  3. an index on view_count, fillfactor 100
  4. compare the update counters over time
  5. narrow counter table, batched increments

basics

~20 s

Each increment writes a new row version, and because view_count is indexed or the pages are full, none are HOT, so every index gains an entry too. Drop that index, lower fillfactor and rewrite once, or move batched counts to a narrow table.

solid answer

~50 s

Every increment writes a new tuple. With `n_tup_hot_upd` near zero the updates are not HOT, so **every index** on `articles` gets a new entry per page view and the dead versions and dead index entries pile up faster than vacuum reuses them. Two causes are typical: an **index that references `view_count`** (a 'most read' index rules out HOT whatever the free space), and **full pages** at the default `fillfactor` of 100, visible as a high `n_tup_newpage_upd`. Fixes, cheapest first: drop the index on the counter and rank 'most read' from a periodically refreshed summary; `ALTER TABLE articles SET (fillfactor = 80)`, remembering it only affects pages filled later until the table is rewritten; move the counter into a narrow `article_stats` table; and batch increments so a thousand views become one update. A long out-of-line `body` is not copied by the increment, since the TOAST pointer is reused.

code

sql · 10 lines
sql
CREATE TABLE article_stats (
  article_id bigint PRIMARY KEY REFERENCES articles (id),
  view_count bigint NOT NULL DEFAULT 0
) WITH (fillfactor = 70);

-- Flushed by the application every few seconds with aggregated counts
UPDATE article_stats AS s
SET view_count = s.view_count + v.n
FROM (VALUES (42, 17), (97, 3), (311, 120)) AS v (article_id, n)
WHERE s.article_id = v.article_id;

go deeper

for a junior

Remember that a PostgreSQL UPDATE writes a whole new row version, so a counter bumped on every page view is never as cheap as it looks.

for a middle

Name the two things that block HOT here, the index on the counter and full pages, and how fillfactor and n_tup_hot_upd relate.

for a senior

Diagnose from the update counters, then fix in order: drop the hot index, lower fillfactor and plan the rewrite, split the counter out, batch increments.

for a principal

Treat high-frequency counters as a modelling decision: per-event logs aggregated later, a separate counter store, or accepted write cost, and what each means for freshness.

## What one increment really writes Take the news-site table `articles(id, slug, title, body, published_at, view_count)` with a primary key on `id`, a unique index on `slug`, an index on `published_at` for the front page, and an index on `view_count` added later for a 'most read' box. Every page view runs `UPDATE articles SET view_count = view_count + 1 WHERE id = $1`. In PostgreSQL that statement: 1. Writes a **new tuple**: the whole row, except values already stored out of line in TOAST. 2. Generates WAL for the heap change, including, with the default full_page_writes, a full-page image the first time a page changes after a checkpoint. 3. If the update is not HOT, inserts a **new entry into every index**: four index insertions for one counter bump. 4. Leaves a dead tuple and, for a non-HOT update, dead index entries that vacuum must remove later. At thousands of views per second, that is where the growth comes from. ## Reading the symptoms The counters in `pg_stat_user_tables` are cumulative, so compare two samples taken some minutes apart: ```sql SELECT n_tup_upd, n_tup_hot_upd, n_tup_newpage_upd, round(100.0 * n_tup_hot_upd / nullif(n_tup_upd, 0), 1) AS hot_pct FROM pg_stat_user_tables WHERE relname = 'articles'; ``` | Pattern | Likely cause | |---|---| | `hot_pct` near 0 while `n_tup_newpage_upd` stays low | An updated column is indexed, so HOT is impossible whatever the free space | | `hot_pct` low and `n_tup_newpage_upd` high | Pages are full: `fillfactor` 100, or pruning cannot keep up | | `hot_pct` high but the table still grows | Old versions stay visible to some snapshot, so pruning and vacuum cannot remove them | ## Why these updates are not HOT - **The index on `view_count`.** Any changed column referenced by a non-summarizing index rules HOT out. This alone explains `hot_pct` near zero. - **`fillfactor` 100.** The default packs pages full at insert time, so the first update of a row on a full page must go elsewhere; pruning makes room only once dead versions exist. - **Medium-width rows.** If `body` is short enough to stay inline, say 1.5 kB after compression, every version copies it and a page fills after a few updates. - **Old snapshots.** A long-running transaction keeps old versions visible, so pruning cannot reclaim them; finding that session is a vacuum and monitoring task. ## Fixes, cheapest first 1. **Drop the index on `view_count`.** Serve 'most read' from a small summary table or materialized view refreshed every minute. The increments become HOT-eligible. 2. **Lower `fillfactor`** with `ALTER TABLE articles SET (fillfactor = 80)`. It takes a `SHARE UPDATE EXCLUSIVE` lock and **rewrites nothing**: only pages filled afterwards keep the reserve. Existing pages get it only after a rewrite such as `VACUUM FULL` or an online tool like pg_repack, which is the bloat topic's business. 3. **Move the counter out** into `article_stats(article_id, view_count)`. A row there is a few dozen bytes, hundreds share a page, and the wide `articles` row with its four indexes is never touched by page views. 4. **Batch the increments.** Aggregate views in the application or in an append-only log table and apply them every few seconds as one `UPDATE ... FROM (VALUES ...)`. A thousand views of one article become one new version instead of a thousand. ## Where TOAST fits If `body` is stored out of line, the increment does not copy it: an `UPDATE` normally carries the existing TOAST pointer into the new version. Long bodies are therefore less of a problem than medium ones. Lowering the table's `toast_tuple_target` pushes medium values out of line for rows written later, keeping heap tuples small, at the cost of TOAST reads whenever the body is selected. ## What not to do - Do not schedule a nightly `VACUUM FULL` as the fix: it takes an `ACCESS EXCLUSIVE` lock, and the bloat returns the next day. - Do not only make autovacuum more aggressive: cleanup gets faster, but every non-HOT update still writes into every index. - Do not move the counter to its own table and then index `view_count` there without deciding that the narrow index is a cost worth paying. - Do not lower `fillfactor` on every table just in case: on read-mostly tables it only spreads the same rows over more pages, so scans and the buffer cache pay for space no update will use. The general rule the scenario teaches: in PostgreSQL the cost of an `UPDATE` depends less on how much data changed than on whether the new version can stay on its page without touching an index.

  • Would a separate article_stats table still help if 'most read' needs an index on its view_count?
    Yes, though less. Increments there are non-HOT, but each new version is a few dozen bytes and touches two small indexes instead of four indexes on a wide row, and `articles` itself is never rewritten by page views. Batching keeps the number of versions low. Without the index, the narrow table's updates can also be HOT.
  • How do you confirm the fix worked?
    Sample `n_tup_upd`, `n_tup_hot_upd` and `n_tup_newpage_upd` for the table twice, some minutes apart, and compare the deltas: the HOT share should approach 100% and new-page updates should stay flat. After one rewrite to apply the new `fillfactor`, the table's size should stop climbing under the same traffic.

  • Incrementing view_count changes the number in place, so it costs one tiny write.
  • ALTER TABLE ... SET (fillfactor = 80) immediately frees space on existing pages.
  • Each increment rewrites the article's TOASTed body as well.
  • An index on view_count is cheap because the column is only a bigint.
  • A nightly VACUUM FULL is the fix; the update pattern itself is fine.