skip to content

On a PostgreSQL append-only readings table of billions of rows, when does a BRIN index on observed_at beat a B-tree, and what does pages_per_range trade?

level: seniorimportance: should knowfreq 47%

answer

  1. physical order matches value order
  2. min and max per range
  3. lossy: every row rechecked
  4. the unsummarized tail
  5. smaller ranges, bigger index

basics

~20 s

BRIN wins when observed_at rises with physical position: each block range's min/max summary excludes most of the table at a tiny index size. pages_per_range (default 128 blocks) trades index size against heap pages rechecked per matching range.

solid answer

~50 s

A BRIN index keeps one summary per **block range** of `pages_per_range` table blocks, 128 by default. With the default `minmax` class for `timestamptz`, the summary is the minimum and maximum `observed_at` in that range. A query does a bitmap scan that keeps only ranges whose summary overlaps the filter, then reads every row in them and rechecks the condition. Because readings arrive in time order, each range covers a narrow slice of time, so a one-day filter touches a few ranges while the index stays orders of magnitude smaller than a B-tree and cheap to maintain. Smaller `pages_per_range` makes the index larger but more precise; larger makes it smaller but rechecks more pages. Pruning degrades when late backfills or reused free space mix distant timestamps into the same ranges. Pages beyond the last summarized range are always scanned until VACUUM, `autosummarize` (off by default) or `brin_summarize_new_values()` summarizes them.

code

sql · 11 lines
sql
CREATE INDEX readings_observed_brin ON readings
    USING brin (observed_at)
    WITH (pages_per_range = 32, autosummarize = on);

-- summarize the tail now instead of waiting for vacuum
SELECT brin_summarize_new_values('readings_observed_brin');

SELECT station_id, avg(temperature_c)
FROM readings
WHERE observed_at >= now() - interval '1 day'
GROUP BY station_id;

go deeper

for a junior

Recall that BRIN stores a min/max summary per group of table pages and fits very large tables whose rows arrive in the order of the indexed column.

for a middle

Explain block ranges, pages_per_range and its default of 128 blocks, the lossy recheck, and why physical correlation decides whether BRIN prunes anything.

for a senior

Diagnose BRIN that stopped helping: backfills, reused free space, the unsummarized tail and autosummarize, and pick minmax_multi or a tighter pages_per_range from measured data.

for a principal

Combine BRIN with partitioning and load design so time-series data stays physically ordered, trading tiny indexes and cheap ingest against slower point lookups.

## What a BRIN index stores **BRIN** (Block Range Index) divides the table into **block ranges**: runs of `pages_per_range` physically adjacent heap pages, **128 by default**, which is 1 MB of table at the standard 8 kB page size. For each range it stores a small **summary** produced by the column's operator class. For `timestamptz` the default is `timestamptz_minmax_ops`, which stores the **minimum and maximum** `observed_at` found in the range. The number of index entries is the table's page count divided by `pages_per_range`, so even a multi-terabyte `readings` table has a BRIN index that is tiny next to a B-tree, which needs one entry per row. ## How a query uses it For `WHERE observed_at >= now() - interval '1 day'`: 1. The index is read in full; it is small. 2. Every range whose `[min, max]` cannot overlap the filter is skipped. 3. Every page of each remaining range goes into a **bitmap**, and a Bitmap Heap Scan reads those pages. 4. Each row is **rechecked** against the filter, because BRIN is **lossy**: it knows a range might match, never which rows do. BRIN cannot return rows in order, cannot enforce uniqueness, and offers no index-only scans. ## Why the readings table fits BRIN pays off only when the column's values **correlate with physical position**. An append-only table that receives readings in time order writes new rows at the end, so each range covers a narrow, non-overlapping window of time. A filter on one day then keeps a handful of ranges and skips the rest. | | B-tree on `observed_at` | BRIN on `observed_at` | |---|---|---| | Index size | one entry per row | one entry per block range | | Insert cost | descend and insert per row | update or leave the last range | | Point lookup | very precise | reads whole ranges | | Range scan on ordered data | good | good, at a fraction of the size | | Data in random order | still works | nearly useless | ## What breaks it - **Late backfills.** Readings from last month inserted today land at the end of the table and widen the newest ranges' min/max, so those ranges match many unrelated queries. - **Reused free space.** After rows are deleted and vacuumed, new inserts may fill the freed space in old pages, mixing new timestamps into old ranges. - **UPDATEs** that move row versions to other pages have the same effect. - **Random keys.** A random UUID gives every range a min and max spanning nearly everything. The `minmax_multi` classes, such as `timestamptz_minmax_multi_ops`, store several intervals per range (`values_per_range`, default 32) and tolerate a few outliers. The `bloom` classes serve only equality. `brin_desummarize_range()` lets you drop a summary that no longer represents its range so it can be rebuilt. ## The unsummarized tail When inserts fill a new page beyond the last summarized range, that range gets **no summary** until summarization runs, and **unsummarized ranges are always returned** by the index scan. On an append-only table, that means the newest data, often what queries ask for, is read without pruning until one of these happens: - a manual or automatic **VACUUM** of the table; - autovacuum serves a request queued by the **`autosummarize`** storage parameter, which is **off by default**; - someone calls **`brin_summarize_new_values(regclass)`** or `brin_summarize_range(regclass, bigint)`. ## Tuning pages_per_range Set it when the index is created. **Smaller** values mean more entries, a larger index and more precise pruning; **larger** values mean a smaller index and more heap pages rechecked per matching range. Size it to your typical filter: if one day of readings fills about 2,000 pages, the default 128 already prunes well, while a query for ten minutes of data would benefit from smaller ranges. ## Checking the fit - Look at the column's physical-order **correlation** statistic first; values near 1 or -1 mean BRIN can prune, values near 0 mean it cannot (reading those statistics is the planner-statistics leaf's subject). - Run the typical query under `EXPLAIN (ANALYZE)` and compare the rows removed by the index recheck with the rows returned. A recheck that discards most of what it reads says the ranges are too wide, either from poor ordering or a `pages_per_range` too large for the filter. - Compare the index size with a B-tree on the same column; the gap is the storage and write cost BRIN saves.

  • Queries for the last hour are slow even though BRIN prunes older data well. What is the likely cause?
    The newest pages lie in block ranges that have not been summarized yet, and the index returns unsummarized ranges for every query. They stay that way until a VACUUM runs on the table, autovacuum handles an `autosummarize` request, or `brin_summarize_new_values()` is called. Turning `autosummarize` on, or scheduling the function, keeps the tail pruned.
  • A bulk backfill inserted a year of historic readings into the live table. What happens to the BRIN index, and what can you do?
    The backfilled rows sit in the newest pages, so those ranges' min/max now span the whole year and match almost every time filter. Loading historic data into a separate table or partition keeps ranges narrow. If the data must stay, rewriting the table in `observed_at` order and rebuilding the index restores the correlation.

BRIN is a warehouse of archive boxes in arrival order, each labelled only with its earliest and latest date: you open just the boxes whose label overlaps your dates, but if late paperwork is stuffed into recent boxes, their labels stretch until nearly every box must be opened.

  • BRIN is a good fit for a random UUID column on a big table.
  • pages_per_range is measured in kilobytes of index.
  • New BRIN ranges are summarized automatically on every insert by default.
  • A BRIN index can return rows in observed_at order.
  • BRIN rows never need rechecking because min and max are exact.