Postgres performance optimization guidelines from Supabase. Contains rules across 8 categories prioritized by impact...
Postgres performance optimization guidelines from Supabase, prioritized by impact.
.range() in Supabase)-- Single column index
CREATE INDEX idx_products_tenant_id ON products(tenant_id);
-- Composite index (order matters!)
CREATE INDEX idx_products_tenant_category ON products(tenant_id, category_id);
-- Partial index (for filtered queries)
CREATE INDEX idx_products_active ON products(tenant_id) WHERE active = true;
-- Unique index
CREATE UNIQUE INDEX idx_products_sku ON products(tenant_id, sku);
// ❌ Bad: SELECT * and no limit
const { data } = await supabase
.from('products')
.select('*');
// ✅ Good: Specific columns with limit
const { data } = await supabase
.from('products')
.select('id, name, price, image')
.eq('tenant_id', tenant.id)
.eq('active', true)
.order('created_at', { ascending: false })
.limit(20);
// Use range for pagination
const pageSize = 20;
const page = 1;
const { data, error } = await supabase
.from('products')
.select('id, name, price')
.eq('tenant_id', tenant.id)
.range((page - 1) * pageSize, page * pageSize - 1);
-- Enable RLS
ALTER TABLE products ENABLE ROW LEVEL SECURITY;
-- Tenant isolation policy
CREATE POLICY "tenant_isolation" ON products
FOR ALL
USING (
tenant_id = (
SELECT id FROM tenants
WHERE slug = current_setting('app.tenant_slug', true)
)
);
-- Public read policy (if needed)
CREATE POLICY "public_read_active" ON products
FOR SELECT
USING (
active = true AND
tenant_id = (
SELECT id FROM tenants
WHERE slug = current_setting('app.tenant_slug', true)
)
);
// ✅ Server component - use server client
import { createClient } from '@/lib/supabase/server';
export async function ServerComponent() {
const supabase = createClient();
// Use supabase
}
// ✅ Client component - use client
'use client';
import { createClient } from '@/lib/supabase/client';
export function ClientComponent() {
const supabase = createClient();
// Use supabase
}
supabase/migrations/ - Schema and indexessrc/lib/supabase/ - Client configuration