4 Hours

11. Performance, Indexing & Query Optimization

Performance

Making Your Supabase App Blazingly Fast

A Supabase project that works correctly but slowly will fail in production. This module covers the full stack of Postgres performance — from understanding B-Tree indexes, to reading EXPLAIN plans, to connection pooling strategies — giving you the tools to diagnose and fix any slow query.

Postgres performance is a deep topic, but the fundamentals are accessible. The most important tool is indexes. A well-placed index can turn a full table scan into an instant lookup. Understanding when and how to use indexes is essential. The second tool is query analysis. EXPLAIN ANALYZE shows you exactly how Postgres executes your query. It reveals which indexes are used and where the bottlenecks are. The third tool is connection pooling. Serverless applications need pooling to handle large numbers of concurrent connections. The fourth tool is monitoring. pg_stat_statements shows you your slowest queries. pg_stat_activity shows you what's running right now. Together, these tools give you complete visibility into your database performance.

Understanding B-Tree Indexes

B-Tree indexes are the default and most versatile index type. They store values in a balanced tree structure, enabling O(log n) lookups. This means finding a row in a million-row table requires only about 20 comparisons. B-Tree indexes support equality (=), range (> <), and ordering (ORDER BY) operations. You can create indexes on single columns, multiple columns (composite indexes), or expressions. The left-prefix rule applies to composite indexes — the index can be used for queries that filter on the first column, the first two columns, etc., but not the second column alone. Partial indexes include only rows that match a WHERE condition. This makes them smaller and faster for filtered queries. Expression indexes work on computed values, like LOWER(email) for case-insensitive search.

SQL
-- Single column index
CREATE INDEX idx_posts_user_id ON posts(user_id);

-- Composite index (left-prefix rule: can use user_id alone, or user_id+status)
CREATE INDEX idx_orders_user_status ON orders(user_id, status, created_at DESC);

-- Partial index (only indexes active subscriptions)
CREATE INDEX idx_active_subscriptions ON subscriptions(user_id)
  WHERE status = 'active';
The Left-Prefix Rule:A composite index on (user_id, status, created_at) can be used for queries filtering on user_id alone, or user_id + status, but NOT status alone. Design your indexes starting with the most selective column used in your WHERE clauses.

Reading EXPLAIN ANALYZE

EXPLAIN ANALYZE is your primary tool for understanding query performance. It shows the query plan and actual execution statistics. Key nodes to look for: Seq Scan means the database read every row — add an index. Index Scan means the database used an index to find specific rows — good. Bitmap Heap Scan means the database used an index to find positions, then fetched rows in batches. Nested Loop joins are good for small tables. Hash Join and Merge Join are used for larger tables. The cost estimates show the planner's guess at execution cost. The actual time shows real execution time. If there's a large gap between estimated and actual rows, your statistics are out of date — run ANALYZE. The BUFFERS option shows data access patterns — Hits are from RAM, Reads are from disk.

SQL
-- Always use EXPLAIN (ANALYZE, BUFFERS)
EXPLAIN (ANALYZE, BUFFERS)
SELECT p.title, pr.username
FROM posts p
JOIN profiles pr ON p.user_id = pr.id
WHERE p.status = 'published'
ORDER BY p.created_at DESC
LIMIT 20;

Hits vs Reads in BUFFERS

The BUFFERS option shows Blocks Hit (data found in RAM shared_buffers — fast) vs Blocks Read (data fetched from disk — slow). A query with many Reads on a large table indicates either insufficient shared_buffers or that your query is reading too much data.

Connection Pooling with Supabase

Each Postgres connection uses ~5-10MB of RAM and a worker process. A serverless deployment with 1000 concurrent Lambda/Edge functions would open 1000 database connections and crash the server. Supabase uses PgBouncer to pool connections. The direct connection port (5432) is for long-lived connections like local dev, Prisma, and persistent servers. The pooled connection port (6543) is for serverless — Next.js API routes, Edge Functions, short-lived requests. Transaction pooling is the most efficient — connections are returned to the pool after each transaction. Session pooling is more compatible but less efficient. Choose the right pooling mode for your use case. For serverless, always use the pooled connection port. Configure your ORM to use the pooled port. This prevents connection exhaustion.

Direct Connection (port 5432)

Use for long-lived connections: local dev, Prisma, persistent servers. Supports all Postgres features including prepared statements and LISTEN/NOTIFY.

Pooled Connection (port 6543)

Use for serverless: Next.js API routes, Edge Functions, short-lived requests. PgBouncer manages the pool. Does NOT support session-level features like SET LOCAL or advisory locks.

Monitoring & Maintenance

Monitoring is essential for maintaining performance. pg_stat_statements shows you the most expensive queries by total time, average time, and number of calls. pg_stat_user_tables shows table statistics including dead tuples (bloat). VACUUM ANALYZE reclaims storage from dead rows and updates statistics. Unused indexes waste space and slow down writes — find them with pg_stat_user_indexes. Regular monitoring helps you catch performance issues before they affect users. Set up alerts for slow queries. Run VACUUM ANALYZE on a regular schedule. Monitor connection counts to prevent connection exhaustion. These practices ensure your Supabase project stays fast as it grows.

  • Find your slowest queries: pg_stat_statements ORDER BY avg_ms DESC
  • Find tables with bloat: pg_stat_user_tables ORDER BY n_dead_tup DESC
  • Force vacuum: VACUUM ANALYZE posts
  • Find unused indexes: pg_stat_user_indexes WHERE idx_scan = 0

Knowledge Check

Ready to test your understanding of 11. Performance, Indexing & Query Optimization?

Back