postgres best practices
Postgres performance optimization and best practices from Supabase. Use this skill when writing, reviewing, or optimizing Postgres queries, schema designs, or database configurations.
Documentation & Preview
Postgres Best Practices
Version 1.0.0 Supabase January 2026
> This document is optimized for AI agents and LLMs. Rules are prioritized by performance impact.
---
Abstract
Comprehensive Postgres performance optimization guide for developers using Supabase and Postgres. Contains performance rules across 8 categories, prioritized by impact from critical (query performance, connection management) to incremental (advanced features). Each rule includes detailed explanations, incorrect vs. correct SQL examples, query plan analysis, and specific performance metrics to guide automated optimization and code generation.
---
Table of Contents
- Query Performance - CRITICAL
- 1.1 Add Indexes on WHERE and JOIN Columns
- 1.2 Choose the Right Index Type for Your Data
- 1.3 Create Composite Indexes for Multi-Column Queries
- 1.4 Use Covering Indexes to Avoid Table Lookups
- 1.5 Use Partial Indexes for Filtered Queries
- Connection Management - CRITICAL
- 2.1 Configure Idle Connection Timeouts
- 2.2 Set Appropriate Connection Limits
- 2.3 Use Connection Pooling for All Applications
- 2.4 Use Prepared Statements Correctly with Pooling
- Security & RLS - CRITICAL
- 3.1 Apply Principle of Least Privilege
- 3.2 Enable Row Level Security for Multi-Tenant Data
- 3.3 Optimize RLS Policies for Performance
- Schema Design - HIGH
- 4.1 Choose Appropriate Data Types
- 4.2 Index Foreign Key Columns
- 4.3 Partition Large Tables for Better Performance
- 4.4 Select Optimal Primary Key Strategy
- 4.5 Use Lowercase Identifiers for Compatibility
- Concurrency & Locking - MEDIUM-HIGH
- 5.1 Keep Transactions Short to Reduce Lock Contention
- 5.2 Prevent Deadlocks with Consistent Lock Ordering
- 5.3 Use Advisory Locks for Application-Level Locking
- 5.4 Use SKIP LOCKED for Non-Blocking Queue Processing
- Data Access Patterns - MEDIUM
- 6.1 Batch INSERT Statements for Bulk Data
- 6.2 Eliminate N+1 Queries with Batch Loading
- 6.3 Use Cursor-Based Pagination Instead of OFFSET
- 6.4 Use UPSERT for Insert-or-Update Operations
- Monitoring & Diagnostics - LOW-MEDIUM
- 7.1 Enable pg_stat_statements for Query Analysis
- 7.2 Maintain Table Statistics with VACUUM and ANALYZE
- 7.3 Use EXPLAIN ANALYZE to Diagnose Slow Queries
- Advanced Features - LOW
- 8.1 Index JSONB Columns for Efficient Querying
- 8.2 Use tsvector for Full-Text Search
---
1. Query Performance
Impact: CRITICAL
Slow queries, missing indexes, inefficient query plans. The most common source of Postgres performance issues.
1.1 Add Indexes on WHERE and JOIN Columns
Impact: CRITICAL (100-1000x faster queries on large tables)
Queries filtering or joining on unindexed columns cause full table scans, which become exponentially slower as tables grow.
Incorrect (sequential scan on large table):
-- No index on customer_id causes full table scan
select * from orders where customer_id = 123;
-- EXPLAIN shows: Seq Scan on orders (cost=0.00..25000.00 rows=100 width=85)Correct (index scan):
-- Create index on frequently filtered column
create index orders_customer_id_idx on orders (customer_id);
select * from orders where customer_id = 123;
-- EXPLAIN shows: Index Scan using orders_customer_id_idx (cost=0.42..8.44 rows=100 width=85)
-- Index the referencing column
create index orders_customer_id_idx on orders (customer_id);
select c.name, o.total
from customers c
join orders o on o.customer_id = c.id;For JOIN columns, always index the foreign key side:
Reference: https://supabase.com/docs/guides/database/query-optimization
---
1.2 Choose the Right Index Type for Your Data
Impact: HIGH (10-100x improvement with correct index type)
Different index types excel at different query patterns. The default B-tree isn't always optimal.
Incorrect (B-tree for JSONB containment):
-- B-tree cannot optimize containment operators
create index products_attrs_idx on products (attributes);
select * from products where attributes @> '{"color": "red"}';
-- Full table scan - B-tree doesn't support @> operatorCorrect (GIN for JSONB):
-- GIN supports @>, ?, ?&, ?| operators
create index products_attrs_idx on products using gin (attributes);
select * from products where attributes @> '{"color": "red"}';
-- B-tree (default): =, <, >, BETWEEN, IN, IS NULL
create index users_created_idx on users (created_at);
-- GIN: arrays, JSONB, full-text search
create index posts_tags_idx on posts using gin (tags);
-- BRIN: large time-series tables (10-100x smaller)
create index events_time_idx on events using brin (created_at);
-- Hash: equality-only (slightly faster than B-tree for =)
create index sessions_token_idx on sessions using hash (token);Index type guide:
Reference: https://www.postgresql.org/docs/current/indexes-types.html
---
1.3 Create Composite Indexes for Multi-Column Queries
Impact: HIGH (5-10x faster multi-column queries)
When queries filter on multiple columns, a composite index is more efficient than separate single-column indexes.
Incorrect (separate indexes require bitmap scan):
-- Two separate indexes
create index orders_status_idx on orders (status);
create index orders_created_idx on orders (created_at);
-- Query must combine both indexes (slower)
select * from orders where status = 'pending' and created_at > '2024-01-01';Correct (composite index):
-- Single composite index (leftmost column first for equality checks)
create index orders_status_created_idx on orders (status, created_at);
-- Query uses one efficient index scan
select * from orders where status = 'pending' and created_at > '2024-01-01';
-- Good: status (=) before created_at (>)
create index idx on orders (status, created_at);
-- Works for: WHERE status = 'pending'
-- Works for: WHERE status = 'pending' AND created_at > '2024-01-01'
-- Does NOT work for: WHERE created_at > '2024-01-01' (leftmost prefix rule)Column order matters - place equality columns first, range columns last:
Reference: https://www.postgresql.org/docs/current/indexes-multicolumn.html
---
1.4 Use Covering Indexes to Avoid Table Lookups
Impact: MEDIUM-HIGH (2-5x faster queries by eliminating heap fetches)
Covering indexes include all columns needed by a query, enabling index-only scans that skip the table entirely.
Incorrect (index scan + heap fetch):
create index users_email_idx on users (email);
-- Must fetch name and created_at from table heap
select email, name, created_at from users where email = 'user@example.com';Correct (index-only scan with INCLUDE):
-- Include non-searchable columns in the index
create index users_email_idx on users (email) include (name, created_at);
-- All columns served from index, no table access needed
select email, name, created_at from users where email = 'user@example.com';
-- Searching by status, but also need customer_id and total
create index orders_status_idx on orders (status) include (customer_id, total);
select status, customer_id, total from orders where status = 'shipped';Use INCLUDE for columns you SELECT but don't filter on:
Reference: https://www.postgresql.org/docs/current/indexes-index-only-scans.html
---
1.5 Use Partial Indexes for Filtered Queries
Impact: HIGH (5-20x smaller indexes, faster writes and queries)
Partial indexes only include rows matching a WHERE condition, making them smaller and faster when queries consistently filter on the same condition.
Incorrect (full index includes irrelevant rows):
-- Index includes all rows, even soft-deleted ones
create index users_email_idx on users (email);
-- Query always filters active users
select * from users where email = 'user@example.com' and deleted_at is null;Correct (partial index matches query filter):
-- Index only includes active users
create index users_active_email_idx on users (email)
where deleted_at is null;
-- Query uses the smaller, faster index
select * from users where email = 'user@example.com' and deleted_at is null;
-- Only pending orders (status rarely changes once completed)
create index orders_pending_idx on orders (created_at)
where status = 'pending';
-- Only non-null values
create index products_sku_idx on products (sku)
where sku is not null;Common use cases for partial indexes:
Reference: https://www.postgresql.org/docs/current/indexes-partial.html
---
2. Connection Management
Impact: CRITICAL
Connection pooling, limits, and serverless strategies. Critical for applications with high concurrency or serverless deployments.
2.1 Configure Idle Connection Timeouts
Impact: HIGH (Reclaim 30-50% of connection slots from idle clients)
Idle connections waste resources. Configure timeouts to automatically reclaim them.
Incorrect (connections held indefinitely):
-- No timeout configured
show idle_in_transaction_session_timeout; -- 0 (disabled)
-- Connections stay open forever, even when idle
select pid, state, state_change, query
from pg_stat_activity
where state = 'idle in transaction';
-- Shows transactions idle for hours, holding locksCorrect (automatic cleanup of idle connections):
-- Terminate connections idle in transaction after 30 seconds
alter system set idle_in_transaction_session_timeout = '30s';
-- Terminate completely idle connections after 10 minutes
alter system set idle_session_timeout = '10min';
-- Reload configuration
select pg_reload_conf();
# pgbouncer.ini
server_idle_timeout = 60
client_idle_timeout = 300For pooled connections, configure at the pooler level:
Reference: https://www.postgresql.org/docs/current/runtime-config-client.html#GUC-IDLE-IN-TRANSACTION-SESSION-TIMEOUT
---
2.2 Set Appropriate Connection Limits
Impact: CRITICAL (Prevent database crashes and memory exhaustion)
Too many connections exhaust memory and degrade performance. Set limits based on available resources.
Incorrect (unlimited or excessive connections):
-- Default max_connections = 100, but often increased blindly
show max_connections; -- 500 (way too high for 4GB RAM)
-- Each connection uses 1-3MB RAM
-- 500