Postgres Best Practices (Supabase)
Guidelines for high-performance and secure Postgres usage, specifically optimized for Supabase environments.
1. Query Performance
- •Indexes: Always index columns used in
WHEREandJOINclauses. - •Index Types: Use
B-treefor most cases,GINfor JSONB/Full-text, andPartial Indexesfor filtered queries. - •Covering Indexes: Use the
INCLUDEclause to avoid table lookups for common projection columns.
2. Schema Design
- •Data Types: Choose the most compact data type (e.g.,
int4instead ofint8if range allows). - •Foreign Keys: Always index foreign key columns to speed up joins and deletions.
- •Naming: Use lowercase identifiers for maximum compatibility with various drivers and tools.
3. Connection Management
- •Pooling: Use connection pooling for all application connections to handle high concurrency.
- •Timeouts: Configure idle connection timeouts to prevent resource exhaustion.
4. Security & RLS
- •Principle of Least Privilege: Grant only necessary permissions to database roles.
- •Row Level Security (RLS): Enable RLS for multi-tenant data isolation.
- •Policy Optimization: Ensure RLS policies are performant by using indexed columns in policy conditions.
5. Data Access Patterns
- •Batching: Use batch
INSERTorCOPYfor bulk data operations. - •N+1 Queries: Use joins or batch loading (Prisma handles this via
includeorselect) to eliminate N+1 issues. - •Pagination: Prefer cursor-based pagination over
OFFSETfor large datasets.
6. Advanced Features
- •JSONB: Use JSONB for unstructured data and create GIN indexes for efficient querying.
- •Full-Text Search: Use
tsvectorandtsqueryfor robust search capabilities.