A glowing database cylinder surrounded by branching, web-like, and layered indexing structures.
Three paths through organized SaaS data

PostgreSQL Indexing for SaaS: B-Tree, GIN, or BRIN

Use B-tree for tenant-scoped filtering and sorting, GIN for searching JSONB or text components, and BRIN for large, physically time-ordered tables. Good PostgreSQL indexing starts with query shape, because the same column can need different indexes for different endpoints.

Every index also adds storage and write work, so adding all three rarely makes sense. Start with representative queries, then measure whether each candidate reduces database work without weakening tenant isolation.

Key takeaways

  • B-tree usually fits dashboard lists, record lookups, and ordered pagination.
  • GIN supports document-style searches, while BRIN suits broad time filtering on physically ordered data.
  • Validate candidates with actual execution plans, representative tenant sizes, and write-load measurements before keeping them.

Match PostgreSQL indexing to the workload

Read the endpoint’s SQL before choosing an index. Identify equality filters, range conditions, requested ordering, and how many rows match.

PostgreSQL’s index type documentation describes the access methods behind these choices.

Index Typical SaaS query Main tradeoff
B-tree Tenant invoices ordered by date Extra storage and maintenance per indexed row
GIN JSONB containment or full-text search Multiple searchable components increase write work
BRIN Time windows over large event tables Poor physical correlation causes more rechecks

These are starting points, not performance guarantees. A sequential scan can be cheaper when a query returns much of a table.

Run this setup once in a scratch database for the invoice examples:

CREATE TABLE invoices (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    tenant_id bigint NOT NULL,
    status text NOT NULL,
    created_at timestamptz NOT NULL DEFAULT now(),
    metadata jsonb NOT NULL DEFAULT '{}'::jsonb,
    description text NOT NULL DEFAULT ''
);

The examples use literal tenant IDs for readability. Application queries should bind authorized tenant values as parameters.

Use B-tree for tenant filtering and ordered results

Put equality filters before sort columns

For an invoice endpoint, the tenant and status filters narrow the search before PostgreSQL retrieves the newest records.

On a live database, run CONCURRENTLY outside a transaction block. It permits ordinary writes during construction, but consumes resources and can wait for transactions.

CREATE INDEX CONCURRENTLY invoices_tenant_status_created_idx
ON invoices (tenant_id, status, created_at DESC, id DESC);


SELECT id, created_at
FROM invoices
WHERE tenant_id = 42 AND status = 'open'
ORDER BY created_at DESC, id DESC
LIMIT 50;

The index matches both equality conditions and the requested ordering. PostgreSQL can potentially avoid sorting and stop after finding 50 matching rows. Meanwhile, id provides deterministic ordering when timestamps tie.

PostgreSQL’s multicolumn index guidance explains why leading columns matter. This tenant-first index isn’t the natural choice for a global date-only report.

Use partial indexes for important subsets

If open invoices are a small, frequently queried subset, consider this candidate instead:

CREATE INDEX CONCURRENTLY invoices_open_tenant_created_idx
ON invoices (tenant_id, created_at DESC, id DESC)
WHERE status = 'open';

Only matching rows occupy this index. However, queries must imply its predicate, and changing an invoice’s status can change its index membership.

Generic prepared plans with parameterized status conditions may not prove that the predicate holds. Test the SQL and prepared-statement behavior your ORM actually uses.

Choose the full or partial candidate according to workload coverage. Don’t install both automatically.

Use GIN for JSONB and full-text search

Match the JSONB operator to the index

GIN indexes document components rather than treating each document as one scalar value.

For containment searches, use:

CREATE INDEX CONCURRENTLY invoices_metadata_gin
ON invoices USING gin (metadata jsonb_path_ops);


SELECT id
FROM invoices
WHERE tenant_id = 42
  AND metadata @> '{"plan":"pro"}'::jsonb;

The @> operator asks whether the document contains the specified structure. Here, jsonb_path_ops supports that containment operation.

If your application also uses key-existence operators such as ?, the default jsonb_ops operator class offers that coverage. PostgreSQL’s GIN index documentation explains the operator-class model.

For a repeated scalar comparison such as metadata->>'plan' = 'pro', a targeted B-tree expression index may fit better. Also, an index on the whole document doesn’t automatically support predicates on every extracted expression.

Index the same text expression you search

Full-text search works with a tsvector, which stores searchable text terms.

CREATE INDEX CONCURRENTLY invoices_description_gin
ON invoices USING gin (
    to_tsvector('english', description)
);


SELECT id
FROM invoices
WHERE tenant_id = 42
  AND to_tsvector('english', description)
      @@ plainto_tsquery('english', 'payment failed');

The explicit english configuration keeps indexing and querying aligned. This is term-based search, not arbitrary substring matching.

GIN doesn’t provide chronological ordering. PostgreSQL may combine it with another index through a bitmap plan, but that doesn’t preserve B-tree order.

Because one document can contribute many index entries, measure insert and update throughput alongside search latency.

Use BRIN for large, time-correlated event tables

BRIN stores summaries for physical block ranges. It’s useful when nearby rows tend to contain nearby timestamps, as often happens with append-heavy events.

CREATE TABLE events (
    tenant_id bigint NOT NULL,
    occurred_at timestamptz NOT NULL,
    value double precision NOT NULL
);


CREATE INDEX CONCURRENTLY events_occurred_brin
ON events USING brin (occurred_at)
WITH (pages_per_range = 128);


SELECT avg(value)
FROM events
WHERE tenant_id = 42
  AND occurred_at >= TIMESTAMPTZ '2026-11-01 00:00:00+00'
  AND occurred_at < TIMESTAMPTZ '2026-11-02 00:00:00+00';

Here, each summary covers 128 table blocks. Smaller pages_per_range values create more summaries and a larger index, but can improve filtering precision.

BRIN is lossy: PostgreSQL identifies candidate ranges, visits their table pages, and rechecks rows. Backfilled timestamps scattered throughout the table can reduce its usefulness.

A timestamp column alone doesn’t justify BRIN. The timestamp values must correlate with physical row placement for block summaries to exclude much work.

This index also doesn’t isolate a tenant or provide sorted output. If an endpoint needs one tenant’s latest 50 events, a B-tree on (tenant_id, occurred_at DESC) is usually the stronger candidate.

BRIN’s appeal is its compact summaries, especially when a large table makes a row-level index expensive. Its benefit still depends on the selected time window.

Validate choices with EXPLAIN (ANALYZE, BUFFERS)

Capture actual work safely

Populate the tables with representative application data before comparing plans. Empty-table plans won’t predict production behavior.

Use the application’s database role and tenant context, including row-level security settings:

BEGIN READ ONLY;
SET LOCAL statement_timeout = '5s';


EXPLAIN (ANALYZE, BUFFERS)
SELECT id, created_at
FROM invoices
WHERE tenant_id = 42 AND status = 'open'
ORDER BY created_at DESC, id DESC
LIMIT 50;


ROLLBACK;

Plain EXPLAIN plans without executing. Adding ANALYZE runs the statement, while BUFFERS reports block activity. For modifying statements, execution can change data; rollback doesn’t reverse every possible side effect.

If the timeout fires, issue ROLLBACK before continuing. Read-only queries still consume CPU, memory, and I/O, so use representative staging data or controlled production sampling.

Compare estimates, loops, and buffers

Read the plan upward from its leaf nodes. Compare estimated and actual row counts, then account for loops: repeated work can dominate an otherwise cheap operation.

For the invoice query, inspect whether the separate sort disappears and fewer rows reach filtering. Also compare execution time and buffer activity across repeated runs.

shared hit means a block was already in PostgreSQL’s shared buffers. shared read means PostgreSQL brought it into those buffers, although the operating system may have cached it.

Buffer counts aren’t distinct-page counts. Parent nodes include child activity, so don’t add every node’s totals together.

Finally, test small and large tenants under representative concurrency. One warm-cache execution doesn’t establish application p95 latency.

Maintain indexes without accumulating unnecessary work

After substantial data changes, refresh statistics with:

ANALYZE invoices;

Standalone ANALYZE updates planner statistics. In contrast, EXPLAIN ANALYZE measures execution.

If tenant and status distributions are related, extended statistics can improve combined-condition estimates:

CREATE STATISTICS invoices_tenant_status_stats
    (mcv, dependencies)
ON tenant_id, status FROM invoices;


ANALYZE invoices;

mcv records common value combinations, while dependencies describes relationships between columns. These statistics concern this table; they don’t generally fix estimation errors across joins.

Keep autovacuum healthy and monitor index sizes and usage. BRIN also needs newly added ranges summarized; autovacuum can handle this, or you can request it:

SELECT brin_summarize_new_values('events_occurred_brin');

PostgreSQL’s index management documentation covers ongoing operational considerations. A failed concurrent build can leave an invalid index, so include detection and cleanup in migration failure handling.

Don’t drop an index solely because its scan counter is low. Counters can reset, and an index may support uniqueness or an infrequent but important job.

Frequently asked questions

Should I add INCLUDE columns?

Add payload columns only when a measured query benefits. They can support index-only access, but increase index size and write work.

PostgreSQL’s covering index documentation explains why index-only scans also depend on table-page visibility. Included columns don’t provide additional search keys.

Does a tenant-first index enforce tenant isolation?

No. It improves an access path, but doesn’t restrict which rows a query may return.

Keep authorization, tenant-scoped predicates, and appropriate row-level security policies. Faster execution must preserve the same authorized results.

Keep the indexes your workload earns

Choose B-tree for ordered scalar access, GIN for component searches, and BRIN when physical ordering makes block summaries useful. Then let measured database work decide which candidates stay.

Start with one important endpoint and change one thing at a time. Keep an index when its read benefit justifies its storage, maintenance, and write costs.

About the author

The SAAS Podium

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *