5 Hours

8. Performance: Index Internals & B-Trees

Engineering

The 100ms Goal

Building a database that works with 1,000 rows is easy. Building one that works with 100 million rows is Engineering. In this module, we explore how Postgres actually finds your data and how to use Indexes to turn minutes into milliseconds.

The B-Tree Index: Under the Hood

By default, Postgres uses a B-Tree (Balanced Tree) index. Instead of reading every row (O(N)), it traverses a tree (O(log N)). For 1 million rows, a B-Tree only needs about 20 comparisons to find your record.

The Index Tax: Every index you add makes INSERT, UPDATE, and DELETE slower because the database has to update the tree structure. Never index columns you don't frequently search by.

Advanced Index Types

Sometimes a B-Tree isn't enough.

GIN (Generalized Inverted Index)

Best for searching inside JSONB objects or arrays. It allows you to query Does this array contain X?.

BRIN (Block Range Index)

For massive, time-sorted tables (billions of rows). It uses 1% of the RAM of a B-Tree but is only efficient if the data is stored in physical order.

Partial Index

Only index some rows: WHERE active = true. Saves massive disk space and RAM.

SQL
-- Creating a high-performance GIN index on JSONB
CREATE INDEX idx_user_metadata ON users USING GIN (metadata);

Step-by-Step: Performance Debugging

  1. Identify: Use pg_stat_statements to find queries taking > 500ms.
  2. Analyze: Run EXPLAIN ANALYZE to see if it's doing a Seq Scan.
  3. Monitor: Check pg_stat_user_indexes to see if your index is actually being used.
  4. Harden: Use CREATE INDEX CONCURRENTLY in production to avoid locking your table!

Knowledge Check

Ready to test your understanding of 8. Performance: Index Internals & B-Trees?

Back