When starting out in backend development, almost everyone reflexively creates a B-Tree index whenever a query runs slow. I once learned this lesson the hard way. An audit log table hit the 80-million-row mark, and querying by date took nearly 5 seconds. Without a second thought, I slapped a B-Tree index on the created_at column.
The query became blazing fast. But just 3 months later, the index file alone ballooned to 3.2 GB—larger than the original data table itself (2.8 GB)—devouring the database server’s entire buffer cache. Digging deeper into PostgreSQL’s documentation, I discovered BRIN Indexes (Block Range Index). This feature completely resolves index bloat for time-series data while maintaining excellent read speeds.
1. Three Approaches for Tables Ballooning to Tens of Millions of Rows
When a table reaches tens of millions of records (system logs, audit trails, IoT sensor metrics, transaction history), you typically face three choices:
Approach 1: No Index (Sequential Scan)
PostgreSQL must scan every data block on the disk from the beginning to the end of the table, inspecting each row to see whether it satisfies the timestamp filter.
- Storage: Consumes zero additional bytes.
- Write Performance: Extremely fast. New data is simply appended to the end of the file.
- Read Performance: Abysmal. On a 50 GB table, a simple query can force the disk to read millions of pages and pin CPU utilization at 100%.
Approach 2: Traditional B-Tree Index
This is PostgreSQL’s default index type. A B-Tree stores every key value alongside a physical pointer pointing directly to each row of data.
- Storage: Very expensive. A 50-million-row table typically produces a B-Tree index ranging from 1.2 GB to 2.5 GB.
- Write Performance: Degrades noticeably. Every INSERT operation must traverse and rebalance the index tree.
- Read Performance: Lightning-fast with O(log N) complexity. Ideal for looking up a single specific record.
Approach 3: BRIN Index (Block Range Index)
BRIN operates on a completely different principle. Instead of indexing every row, it partitions the table into contiguous ranges of physical blocks (defaulting to 128 blocks, or roughly 1 MB). For each range, BRIN records just two values: the minimum (MIN) and maximum (MAX) values of that column.
- Storage: Incredibly lightweight. The entire index usually takes up only a few tens of kilobytes to a few megabytes—200 to 1,000 times smaller than a B-Tree.
- Write Performance: Virtually zero overhead on INSERT statements. The database only checks whether the incoming value falls outside the current block range’s MIN/MAX bounds.
- Read Performance: Far faster than a Sequential Scan. For date-range queries, it closely approaches B-Tree speeds.
2. Real-World Comparison: B-Tree vs. BRIN
The summary table below outlines the trade-offs to weigh before indexing:
| Criteria | B-Tree Index | BRIN Index |
|---|---|---|
| File Size | Consumes 20% – 60% of table size | Usually under 1% of table size |
| RAM Footprint (Buffer Cache) | Competes heavily with table data for RAM | Fits effortlessly entirely in RAM |
| Point Lookup (Exact Record) | Instant (sub-millisecond) | Slower, as it must scan rows within the matching block range |
| Range Scans (Day, Week, Month) | Very fast | Very fast if the data exhibits high physical correlation |
| Impact on INSERT Statements | Increases I/O and node-split overhead | Negligible impact |
Key Limitation to Keep in Mind
BRIN is effective only when the physical write order on disk aligns with the logical values of the column. A classic example is a created_at column that increments monotonically over time.
If you run arbitrary UPDATE operations that cause a row from 2021 to share a disk block with a row from 2026, the MIN-MAX interval of that block range stretches wide open. When this range becomes excessively broad, BRIN cannot skip any blocks. The query planner is forced to read nearly the entire table, degrading performance down to that of a Sequential Scan.
3. When to Use B-Tree vs. BRIN
Follow these simple guidelines to make the right choice:
- Use B-Tree when: You need exact point lookups (finding a user by
email, an order byuuid), working with smaller tables (under 1 million rows), or handling tables subject to frequent, random UPDATE/DELETE operations. - Choose BRIN when:
- The table is append-only, rarely or never updating or deleting existing rows.
- The indexed column increases steadily along with insert order (such as
created_at,logged_at, orBIGSERIALIDs). - The table size spans tens of gigabytes or more while database server RAM is limited.
- Queries predominantly filter by ranges: fetching logs from the last 24 hours, aggregating last week’s revenue, etc.
4. Hands-On Practice with a 10-Million-Row Table
Step 1: Set Up the Sample Table and Generate Data
Let’s create a table simulating API access logs and insert 10 million sequentially incrementing timestamps:
CREATE TABLE access_logs (
id BIGSERIAL,
endpoint VARCHAR(100),
status_code INT,
response_time_ms INT,
created_at TIMESTAMP WITHOUT TIME ZONE DEFAULT clock_timestamp()
);
-- Generate 10 million records with created_at incrementing by 0.3 seconds per row
INSERT INTO access_logs (endpoint, status_code, response_time_ms, created_at)
SELECT
'/api/v1/checkout',
200,
(random() * 500)::INT,
'2026-01-01 00:00:00'::TIMESTAMP + (g * INTERVAL '0.3 second')
FROM generate_series(1, 10000000) AS g;
ANALYZE access_logs;
Step 2: Measure Physical Correlation
Before creating a BRIN index, verify whether the data on disk is truly ordered sequentially alongside the timestamp column:
SELECT tablename, attname, correlation
FROM pg_stats
WHERE tablename = 'access_logs' AND attname = 'created_at';
The correlation metric ranges between -1.0 and 1.0. If the value sits between 0.95 and 1.0 (or near -1.0), the column meets the criteria for using BRIN.
Step 3: Create the BRIN Index and Fine-Tune Block Ranges
The syntax for creating a BRIN index is concise:
CREATE INDEX idx_access_logs_created_at_brin
ON access_logs USING brin(created_at);
By default, PostgreSQL bundles pages_per_range = 128 (roughly 1 MB of data). You can tune this parameter to match your query patterns:
- If queries frequently target tight time windows (a few minutes to an hour): Lower it to
pages_per_range = 32. The index will grow slightly larger, but the database will prune irrelevant blocks with greater precision. - If you only query wide ranges (several weeks or months): Keep the default 128 or increase it to 256 for the smallest possible index footprint.
-- Tune to a narrower block range to improve filtering precision
CREATE INDEX idx_access_logs_created_at_brin_fine
ON access_logs USING brin(created_at)
WITH (pages_per_range = 32);
Step 4: Compare Actual Disk Usage
Now create a B-Tree index on the same column to see the stark difference (in high-concurrency environments, consider using PostgreSQL CREATE INDEX CONCURRENTLY to avoid blocking operations):
CREATE INDEX idx_access_logs_created_at_btree
ON access_logs (created_at);
Query the size of both indexes:
SELECT
relname AS index_name,
pg_size_pretty(pg_relation_size(oid)) AS index_size
FROM pg_class
WHERE relname IN ('idx_access_logs_created_at_brin', 'idx_access_logs_created_at_btree');
Results on the test machine:
idx_access_logs_created_at_btree: 214 MBidx_access_logs_created_at_brin: 48 KB
That is no typo: BRIN is 4,450 times smaller than the B-Tree. The ~214 MB of saved memory is freed up for Postgres to cache actual table data in RAM.
Step 5: Verify the Execution Plan with EXPLAIN ANALYZE
Run a test query retrieving log entries for January 15, 2026, and inspect the cost breakdown using PostgreSQL EXPLAIN ANALYZE:
EXPLAIN ANALYZE
SELECT COUNT(*), AVG(response_time_ms)
FROM access_logs
WHERE created_at BETWEEN '2026-01-15 00:00:00' AND '2026-01-15 23:59:59';
The execution plan will show Bitmap Index Scan on idx_access_logs_created_at_brin. Instead of scanning all 10 million rows, PostgreSQL reads only the specific block ranges matching the timestamp range. Over 98% of the remaining disk blocks are completely bypassed.
Step 6: Update the BRIN Index After Large Bulk Inserts
Data appended to newly allocated pages may not always be summarized into BRIN ranges right away. After massive data imports via COPY, you should explicitly summarize new blocks into the index:
-- Immediately summarize new data blocks into the BRIN index
SELECT brin_summarize_new_values('idx_access_logs_created_at_brin');
If your system handles massive log or metrics tables growing day by day, run a quick correlation check today. Combined with strategies like automating PostgreSQL partitioning with pg_partman, using BRIN indexes allows you to liberate tens of gigabytes of memory long before you even need to consider upgrading your database server hardware.

