TL;DR
- Start with the SQL shape and the operating budget for the endpoint. A PostgreSQL indexing strategy for SaaS often begins with one composite B-tree that supports a tenant equality filter, a deterministic sort and a small page. A feed that queries across tenants usually needs a separate plan.
- Use a partial index when an important endpoint only reads a stable subset, such as pending jobs. Keep that eligibility predicate explicit in the SQL for the endpoint. A generic plan for a parameterized status cannot prove that the partial index covers every possible execution.
- Consider BRIN for time-bounded analytics over values correlated with physical insertion order. Its summaries can skip blocks, and the heap scan still rechecks rows inside matching ranges. Test a late-arrival fixture before committing to this choice.
- Benchmark the exact statement your service sends. Compare execution buffers, scan conditions, rows discarded, index bytes and writer cost. Roll out one index at a time with a lock budget and a plan to handle an interrupted build.
What the index needs to do for a tenant-scoped endpoint
Consider a job history screen for a SaaS product. An organization admin opens a general feed to investigate completed jobs, or switches to an operations queue containing only pending jobs. The service fetches 50 rows for a tenant and emits a cursor for the next page. It also supports audit exports bounded by UTC timestamps. These are three different query shapes, even when a single Postgres database serves all of them.
A team often starts with standalone indexes on the columns exposed in API filters. The database can sometimes combine indexes through a bitmap, then visit the table for the matching rows. A bitmap loses the individual indexes’ ordering. For a short page, the database may gather far more rows than the caller needs and sort them before the limit can take effect. Separate indexes also add structures the write path must maintain. PostgreSQL documentation on combining indexes
The operational constraint is that the expensive route may serve a small number of large tenants. A median based on a hundred quiet tenants can conceal the problem. Measure tenant-level spread by replaying representative high- and low-volume requests in a controlled environment. Keep tenant identifiers out of metric labels with unbounded cardinality. In a lab, tag fixtures by size or distribution instead.
Write down the filter, ordering, projection and limit together. Determine how often a row enters or leaves each hot subset. Measure whether the endpoint usually stops at the first page. For audit, distinguish requests for an entire time interval from point lookups by an event ID. That inventory exposes the underlying jobs an access path must perform and the writer overhead the service can tolerate.
Choose a composite B-tree, partial index or BRIN by access pattern
| Query shape | Candidate | Operating cost |
|---|---|---|
| Latest jobs for one tenant | B-tree on tenant, timestamp and ID | Every job contributes an entry. The key order supports the tenant feed and its sort. |
| Latest pending jobs for one tenant | Same key with a pending-only predicate | Fewer live entries when pending is rare. Status transitions can churn the index and write amplification still needs measurement. |
| Count audit events in a narrow window | BRIN on the time column | Small summaries are effective when nearby rows have similar timestamps. Candidate blocks require rechecks. |
The tenant-first B-tree is useful because equality fixes the first key column. Within that slice, timestamp and ID supply the expected ordering. A range on the first unfixed key then narrows the portion scanned. An ID at the end disambiguates timestamp ties, even when many events came from a single batch. PostgreSQL can scan a B-tree backwards for the corresponding reverse order, while mixed directions in multi-column sorts can require a particular index definition. Multicolumn indexes, Indexes and ordering
Keep tenant isolation as its own requirement. An index improves access to tenant data. The route still needs authenticated tenant scope, and row policies can provide an independent database guard where that fits the tenancy model. A well-indexed query that lacks the right tenant predicate still poses a correctness problem.
BRIN stores information per range of physical pages. A BRIN min/max summary on time can disregard a range whose minimum timestamp lies after the window or whose maximum lies before it. The range is a storage unit, independent of business concepts like a tenant or a calendar day. An ingest pipeline that bulk-loads months of older timestamps into current pages can widen those ranges. Distinguish event time from arrival time in your schema and index whichever the route actually filters. PostgreSQL BRIN internals and summarization
Implement the tenant feed and pending queue
The following index setup assumes PostgreSQL 18 and the two tables in the reproducible fixture below. Run each concurrent index statement outside a transaction block on a writable database. The full feed index is useful when the general history screen matters. For a product with only the pending queue, establish whether that extra full index has a caller before adding it. CREATE INDEX and concurrent builds
CREATE INDEX CONCURRENTLY jobs_tenant_feed_idx
ON jobs (tenant_id, created_at DESC, id DESC);
CREATE INDEX CONCURRENTLY jobs_tenant_pending_idx
ON jobs (tenant_id, created_at DESC, id DESC)
WHERE status = 'pending';
CREATE INDEX CONCURRENTLY audit_events_time_brin_idx
ON audit_events USING brin (occurred_at)
WITH (pages_per_range = 32, autosummarize = on);
Use separate SQL statements for the initial page and the continuation. Both have a literal pending predicate because this queue has fixed eligibility. The tenant and cursor values remain bound parameters. Derive the tenant value from the authenticated context. Treat a cursor as a continuation boundary and check it against the requested tenant and filter when decoding it.
PREPARE pending_first (integer) AS
SELECT id, created_at
FROM jobs
WHERE tenant_id = $1 AND status = 'pending'
ORDER BY created_at DESC, id DESC
LIMIT 50;
PREPARE pending_after (integer, timestamptz, bigint) AS
SELECT id, created_at
FROM jobs
WHERE tenant_id = $1
AND status = 'pending'
AND (created_at, id) < ($2, $3)
ORDER BY created_at DESC, id DESC
LIMIT 50;
EXECUTE pending_first(42);
EXECUTE pending_after(42, TIMESTAMPTZ '2026-01-01 04:00:00+00', 144000);
The strict tuple comparison advances past the previous page’s last row in descending order. Both columns in the fixture are non-null, so the cursor does not need special null handling. The paging query still reads the current eligible set. If a job changes from pending to running between requests, it can disappear from later pages. A feed promises continuation over a changing set. An export that promises a snapshot needs a separate consistency contract. Designing PostgreSQL cursor pagination
One instructive mistake is to reuse a single prepared query with an arbitrary bound status for both tabs. To reproduce it, prepare the same pending-page query with a text parameter instead of the status literal and explain the execution under a forced generic plan in a disposable session. The lab used the full feed index and applied the status filter afterwards. The specialized statement lets the planner reason about the partial predicate even when it does not know the tenant ID at plan time. Keep the status literal inside reviewed SQL for this fixed endpoint. Continue parameterizing every caller-supplied value. Partial-index predicate matching, Generic and custom prepared plans
Set an index rollout budget
Run index creation in a dedicated migration session, without a framework-managed transaction. A sample session budget is below. Choose your own timeout from a staging build and your production lock policy. A cancelled concurrent build can leave an invalid index. Check its catalog state before retrying, even if the migration runner says the step failed.
SET lock_timeout = '3s';
SET statement_timeout = '30min';
-- Run the concurrent index statements in this session.
-- Inspect the catalog before you mark the migration complete.
SELECT indexrelid::regclass AS index_name, indisvalid, indisready
FROM pg_index
WHERE indrelid = 'jobs'::regclass;
RESET lock_timeout;
RESET statement_timeout;
Watch long-running transactions and the phases in pg_stat_progress_create_index. Schedule the build around backfills and other large operations touching the same table. An old snapshot can prolong a phase after the scans have completed. Keep read and write resource headroom during the build, then compare the new plan before removing any overlapping legacy index. Index build progress reporting, Phasing Alembic changes during rolling deploys
Failure modes to reproduce before rollout
- The planner skips the partial index. A query builder replaces the fixed predicate with a bound status or a differently written expression. Explain the statement through the same driver and prepare behavior used by the service. Inspect
Index CondversusFilter. For an endpoint with fixed eligibility, encode that condition directly in its SQL. - An index-only scan still fetches heap tuples. Rapid updates clear page-level visibility information. Check
Heap Fetchesunder realistic status churn and vacuum timing. Adding another included column will not by itself make the page all-visible. Visibility and index-only scans - The BRIN scan rechecks too many rows. Late imports widen timestamp spans inside physical ranges. Inspect
Heap BlocksandRows Removed by Index Recheck. Try fewer pages per range against the messy fixture. If that still leaves many blocks, compare a time-key B-tree or reconsider whether the endpoint can filter by arrival time. - An interrupted build leaves an invalid relation. Timeouts and cancellation may interrupt the index build. Check
pg_index.indisvalidandindisready. Review the failed build’s state, remove the invalid index with the appropriate production procedure, and rerun the migration. Concurrent-index failure behavior - The first tenant looks fast and the largest tenant still hurts. Data skew changes the number of rows that qualify and can affect plan selection. Benchmark several distributions and the oldest as well as newest cursor boundaries. Recheck row estimates after backfills. Reading EXPLAIN results
Alternatives worth measuring
A single general-purpose B-tree is a reasonable first choice when status distributions are close or the queue is lightly used. It keeps the ordered tenant scan and avoids a second tree. If repeated status transitions and queue reads dominate, compare a partial index with a fuller key such as (tenant_id, status, created_at DESC, id DESC). The latter can serve multiple fixed-status queues. It will disturb the desired ordering for the unfiltered feed because status comes before time.
A timestamp B-tree can serve queries that demand specific timestamps, ordered ranges or even highly selective windows over data with poor physical correlation. Its footprint and maintenance work are higher than a small BRIN summary in a well-ordered append stream. Both may be justified when low-latency point access and scanning broad windows serve different products with separate budgets.
Time partitioning is worth considering when dropping old data by time is itself a core operation. It can narrow the relations the optimizer considers through pruning, which has a different job from choosing an index inside a partition. Start with the workload and retention policy before assuming partitioning will improve individual queries. PostgreSQL partitioning and pruning
Reproduce the PostgreSQL 18 indexing measurements
We ran this synthetic fixture in a disposable PostgreSQL 18.6 cluster, with parallel query execution disabled for the session. The observations below are individual warm-cache runs. They describe this fixture and its hardware, with no production latency or throughput implication. Use fresh tables in a scratch database. Run the two measured queries before and after the index statements above. Before the second run, use VACUUM (ANALYZE) jobs and ANALYZE audit_events to match the lab conditions.
CREATE TABLE jobs (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
tenant_id integer NOT NULL,
created_at timestamptz NOT NULL,
status text NOT NULL CHECK (status IN ('pending','running','done'))
);
CREATE TABLE audit_events (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
tenant_id integer NOT NULL,
occurred_at timestamptz NOT NULL,
action text NOT NULL
);
INSERT INTO jobs (tenant_id, created_at, status)
SELECT n % 100 + 1,
TIMESTAMPTZ '2026-01-01 00:00:00+00' + (n / 10) * INTERVAL '1 second',
CASE WHEN (n / 100) % 20 = 0 THEN 'pending' ELSE 'done' END
FROM generate_series(1, 200000) AS g(n);
INSERT INTO audit_events (tenant_id, occurred_at, action)
SELECT n % 100 + 1,
TIMESTAMPTZ '2026-01-01 00:00:00+00' + n * INTERVAL '1 second',
'job.completed'
FROM generate_series(1, 500000) AS g(n);
SET max_parallel_workers_per_gather = 0;
ANALYZE jobs;
ANALYZE audit_events;
EXPLAIN (ANALYZE, BUFFERS, TIMING OFF)
SELECT id, created_at FROM jobs
WHERE tenant_id = 42 AND status = 'pending'
ORDER BY created_at DESC, id DESC LIMIT 50;
EXPLAIN (ANALYZE, BUFFERS, TIMING OFF)
SELECT count(*) FROM audit_events
WHERE occurred_at >= '2026-01-03 12:00:00+00'
AND occurred_at < '2026-01-03 12:30:00+00';
SELECT indexrelname, pg_relation_size(indexrelid) AS bytes
FROM pg_stat_user_indexes
WHERE indexrelname IN (
'jobs_tenant_feed_idx', 'jobs_tenant_pending_idx', 'audit_events_time_brin_idx'
);
| Query | Without added index | With added indexes |
|---|---|---|
| Pending jobs for tenant 42 | 1,471 shared hits, 9.427 ms | 3 shared hits, 0.024 ms with the partial B-tree |
| Audit count over 30 minutes | 4,167 shared hits, 24.162 ms | 37 shared hits, 0.383 ms with BRIN |
The full feed index occupied 8,134,656 bytes, the pending-only index 425,984 bytes, and the audit BRIN 24,576 bytes. The indexed audit scan still rechecked 32 lossy heap pages and discarded 2,040 nonmatching rows. That is useful evidence for the search shape alongside the speedup. The write path was outside this run. For a deployment, separately instrument inserts and natural status transitions, compare WAL and write latency across candidates, and use timings from multiple repetitions and comparably warmed fixtures.
Frequently asked questions
Should tenant ID always come first in a composite PostgreSQL index?
Use tenant ID first when your important queries bind it by equality and then sort or range over later columns. A global administration view or time-based export might need an independent access path. Choose the index by frequency and cost of the actual statements, and check representative query plans before adding another tree.
Can a prepared statement use a PostgreSQL partial index?
Yes, if the planner can prove that the query predicate implies the index predicate. A fixed pending status and a bound tenant are compatible. A generic plan that receives the status itself as a parameter has to serve every status and cannot assume that the pending-only index covers them all.
When does a BRIN index stop being useful for time filters?
BRIN becomes less selective when timestamps within physical page ranges span much of the table’s history. Backfills and late-arriving events can produce this distribution. Compare heap blocks visited and rows removed on recheck across typical windows, and test a smaller page-range setting or a B-tree before making the choice.
Further reading
- Cursor pagination with a composite PostgreSQL key
- Expand-and-contract database migrations with Alembic
- PostgreSQL 18 index access methods and planning
Review your PostgreSQL indexing strategy
Bring a slow query, its execution plan and a sample distribution of the data it reads. Get in touch for a PostgreSQL architecture review to compare access paths and define a rollout that accounts for your write workload.
