OwlTheEngineer
How It Actually WorksEpisode 49 · Backend

Database index types deep dive: B-Tree, Hash, GIN, GiST, and BRIN

Why defaulting to B-Tree indexes on every column wastes gigabytes of RAM, and how PostgreSQL's specialized index engines (GIN, GiST, BRIN) accelerate JSONB, full-text, and time-series queries.

Owl · 2 min read · 0 views
– comments
Ep 49 · Backend
60s VISUAL BREAKDOWN
Episode 49
Watch the fast visual breakdown or discuss on social:

When optimizing slow database queries, developers frequently create a standard index on the slow column:

CREATE INDEX idx_orders_data ON orders (data);

By default, relational database engines like PostgreSQL build a B-Tree (Balanced Tree) index. While B-Trees are exceptionally versatile for sorted scalar data, they are completely unsuited for semi-structured JSONB payloads, geographic coordinates, or billion-row append-only logs.

PostgreSQL provides five distinct core index engines, each engineered for specific mathematical access patterns and storage characteristics.

POSTGRESQL INDEX MATRIX:
┌──────────┬─────────────────────────────┬──────────────────────────┬─────────────────────────┐
│ Type     │ Internal Structure          │ Best Operators           │ Typical Use Cases       │
├──────────┼─────────────────────────────┼──────────────────────────┼─────────────────────────┤
│ B-Tree   │ Self-balancing search tree  │ =, <, <=, >, >=, BETWEEN │ Primary Keys, IDs, Sort │
│ Hash     │ Bucketed 32-bit hash table  │ = (Equality only)        │ Exact UUID / Text Match │
│ GIN      │ Inverted array index        │ @>, ?, ?&, @@ (Search)   │ JSONB, Tags, Full-Text  │
│ GiST     │ Generalized R-Tree / Trees  │ &&, @>, <-> (Distance)   │ PostGIS Spatial, Ranges │
│ BRIN     │ Min/Max block summaries     │ =, <, >, BETWEEN         │ Massive Time-Series/Logs│
└──────────┴─────────────────────────────┴──────────────────────────┴─────────────────────────┘

1. B-Tree: The General-Purpose Default

B-Tree (Balanced Tree) maintains sorted multi-level node pages.

  • Logarithmic lookup complexity: O(log N).
  • Enforces UNIQUE constraints and powers ORDER BY operations without requiring in-memory quicksort.
  • Supports composite indexing across multiple columns (tenant_id, created_at).
                [ Root Node: 50 | 100 ]
                     /       |       \
        [ 20 | 35 ]     [ 65 | 80 ]     [ 120 | 150 ]
          /    \           /    \           /     \
       [Leaf] [Leaf]    [Leaf] [Leaf]    [Leaf]  [Leaf]
         (Double-linked list for lightning fast range scans)

2. GIN: Generalized Inverted Index for JSONB & Arrays

Standard B-Trees index entire rows as a single atomic value. But when storing document payloads in JSONB or PostgreSQL TEXT[] arrays:

-- Query: Find all users with the "admin" role inside a JSONB metadata column
SELECT * FROM users WHERE metadata @> '{"roles": ["admin"]}';

A B-Tree cannot index internal keys inside the document. GIN (Generalized Inverted Index) extracts every individual key and value inside the JSON document, creating an inverted mapping pointing back to matching table tuples (row pointers):

GIN INVERTED DICTIONARY:
"admin"     ➔ [ Row 1, Row 42, Row 109 ]
"active"    ➔ [ Row 1, Row 2, Row 3, Row 42 ]
"verified"  ➔ [ Row 42, Row 88 ]

When querying @> '{"roles": ["admin"], "status": "active"}', Postgres calculates the binary set intersection of [Row 1, 42, 109] and [Row 1, 2, 3, 42], immediately finding Row 1 and Row 42 in microseconds.

-- Optimize JSONB search with GIN path operations:
CREATE INDEX idx_users_metadata_gin ON users USING GIN (metadata jsonb_path_ops);

3. BRIN: Block Range Index for Billion-Row Time-Series

In high-throughput logging, telemetry, and financial market data, rows are appended in strict chronological order on physical disk.

Building a standard B-Tree on a 500-million-row audit_logs table requires 30 to 40 Gigabytes of RAM just to hold the B-Tree index pages in cache.

How BRIN Works

Instead of storing a pointer for every single row, BRIN (Block Range Index) divides the physical table heap into chunks (e.g. 128 disk pages / 1MB) and records only two values per chunk: [min_value, max_value].

PHYSICAL HEAP BLOCKS:
Block 0-127:   [ Min: 2026-09-01 00:00:00 , Max: 2026-09-01 04:00:00 ]
Block 128-255: [ Min: 2026-09-01 04:00:01 , Max: 2026-09-01 08:00:00 ]
Block 256-383: [ Min: 2026-09-01 08:00:01 , Max: 2026-09-01 12:00:00 ]

When executing WHERE created_at BETWEEN '2026-09-01 05:00:00' AND '2026-09-01 06:00:00', Postgres checks the lightweight BRIN summary, instantly skips Blocks 0-127 and Blocks 256+, and scans only Block 128-255.

-- 99% RAM savings on massive append-only tables:
CREATE INDEX idx_logs_created_brin ON audit_logs USING BRIN (created_at);
  • B-Tree Size: 32,000 MB (32 GB)
  • BRIN Size: 12 MB (99.96% memory reduction!)

4. Architectural Selection Guide

  1. Use B-Tree for standard unique IDs, email lookups, foreign keys, and sorting operations.
  2. Use GIN for JSONB columns, tags arrays (text[]), and tsvector full-text search dictionaries.
  3. Use BRIN for append-only time-series data, event streams, and audit tables exceeding 10 million rows.
  4. Use GiST for PostGIS geospatial points (ST_DWithin), bounding boxes, and overlapping scheduling ranges (tsrange).
SYSTEM DESIGN CHECK

Test Your Understanding

Quick architectural scenario challenge based on this breakdown.

SCENARIO

A 3rd-party payment gateway starts timing out with 504 errors during peak traffic.

Q1.How should a downstream dependency failure be handled to protect upstream service availability?

Comments –