supabase-performance-tuning
Performance tuning guide for Supabase projects and Postgres databases.
Install
mkdir -p .claude/skills/supabase-performance-tuning && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/1747" && unzip -o skill.zip -d .claude/skills/supabase-performance-tuning && rm skill.zipInstalls to .claude/skills/supabase-performance-tuning
Activation
This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.
Optimize Supabase query performance with indexes, EXPLAIN ANALYZE, connectionKey capabilities
- →Diagnose slow queries using pg_stat_statements
- →Inspect index usage and cache hit rates
- →Create B-tree, composite, and partial indexes
- →Select specific columns to reduce payload size
- →Paginate query results with .range()
- →Optimize N+1 query patterns with embedded joins
How it works
The skill guides users through diagnosing performance issues with SQL queries and CLI tools, then provides instructions for creating indexes, optimizing client-side data fetching, and use Supabase infrastructure features.
Inputs & outputs
When to use supabase-performance-tuning
- →Optimize slow SQL queries
- →Implement connection pooling
- →Configure database indexing
- →Enable query result pagination
About this skill
Supabase Performance Tuning
Overview
Systematically improve Supabase query and database performance across three layers: PostgreSQL engine (indexes, query plans, materialized views), Supabase infrastructure (Supavisor connection pooling, Edge Functions, read replicas), and client SDK patterns (column selection, pagination, RPC functions). Every technique here is measurable — run EXPLAIN ANALYZE before and after to confirm the improvement.
Prerequisites
- Supabase project (local or hosted) with
@supabase/supabase-jsv2+ installed - Supabase CLI installed (
npx supabase --versionto verify) - Access to the SQL Editor in the Supabase Dashboard or a direct Postgres connection
pg_stat_statementsextension enabled (Step 1 covers this)
Instructions
Step 1: Diagnose — Find What Is Slow
Start every performance effort with data. Enable pg_stat_statements and run the Supabase CLI diagnostics to identify bottlenecks before optimizing.
Enable the stats extension:
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
Find the slowest queries by average execution time:
SELECT
query,
calls,
mean_exec_time::numeric(10,2) AS avg_ms,
total_exec_time::numeric(10,2) AS total_ms,
rows
FROM pg_stat_statements
ORDER BY mean_exec_time DESC
LIMIT 10;
Check index usage and cache hit rates with the Supabase CLI:
# Which indexes are actually being used?
npx supabase inspect db index-usage
# What percentage of queries are served from cache vs disk?
npx supabase inspect db cache-hit
# Tables consuming the most space
npx supabase inspect db table-sizes
Inspect active connections for pooling issues:
SELECT state, count(*), max(age(now(), state_change)) AS max_age
FROM pg_stat_activity
WHERE datname = current_database()
GROUP BY state;
If idle connections exceed your plan's limit or active queries show high max_age, connection pooling (Step 2) and query optimization (Step 3) are the priority.
Step 2: Indexes and Query Plans
Indexes are the single highest-impact optimization. Use EXPLAIN ANALYZE to read query plans, then create targeted indexes.
Read a query plan:
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)
SELECT * FROM users WHERE email = '[email protected]';
Look for Seq Scan on large tables — that means no index is being used. After adding an index, the plan should show Index Scan or Index Only Scan.
Create a basic index:
CREATE INDEX idx_users_email ON users(email);
Create a composite index for multi-column filters:
-- Optimizes: WHERE user_id = ? AND created_at > ? ORDER BY created_at DESC
CREATE INDEX idx_orders_user_created
ON orders(user_id, created_at DESC);
Create a partial index to cover a common filter pattern:
-- Only indexes incomplete todos — much smaller and faster than full-table index
CREATE INDEX idx_todos_user_incomplete
ON todos(user_id, inserted_at DESC)
WHERE is_complete = false;
Find missing indexes on foreign keys (common source of slow JOINs):
SELECT
tc.table_name,
kcu.column_name AS fk_column,
'CREATE INDEX idx_' || tc.table_name || '_' || kcu.column_name
|| ' ON public.' || tc.table_name || '(' || kcu.column_name || ');' AS fix
FROM information_schema.table_constraints tc
JOIN information_schema.key_column_usage kcu
ON tc.constraint_name = kcu.constraint_name
LEFT JOIN pg_indexes i
ON i.tablename = tc.table_name
AND i.indexdef LIKE '%' || kcu.column_name || '%'
WHERE tc.constraint_type = 'FOREIGN KEY'
AND tc.table_schema = 'public'
AND i.indexname IS NULL;
Find unused indexes (candidates for removal to reduce write overhead):
SELECT schemaname, relname, indexrelname, idx_scan
FROM pg_stat_user_indexes
WHERE idx_scan = 0 AND schemaname = 'public'
ORDER BY pg_relation_size(indexrelid) DESC;
Always use CREATE INDEX CONCURRENTLY on production tables to avoid locking writes during index creation.
Step 3: Client SDK and Infrastructure Optimization
Optimize the Supabase JS client calls, then leverage infrastructure features for scale.
Select only needed columns — avoid select('*'):
import { createClient } from '@supabase/supabase-js'
const supabase = createClient(
process.env.SUPABASE_URL!,
process.env.SUPABASE_ANON_KEY!
)
// BAD: fetches every column, large payloads
const { data } = await supabase.from('users').select('*')
// GOOD: only the columns you need
const { data } = await supabase.from('users').select('id, name, avatar_url')
Paginate with .range() instead of loading all rows:
// Page 1: rows 0-49
const { data: page1 } = await supabase
.from('products')
.select('id, name, price')
.order('created_at', { ascending: false })
.range(0, 49)
// Page 2: rows 50-99
const { data: page2 } = await supabase
.from('products')
.select('id, name, price')
.order('created_at', { ascending: false })
.range(50, 99)
Use RPC functions to push complex logic to Postgres:
-- Create a server-side function for an expensive aggregation
CREATE OR REPLACE FUNCTION get_dashboard_stats(org_id uuid)
RETURNS json AS $$
SELECT json_build_object(
'total_users', (SELECT count(*) FROM users WHERE organization_id = org_id),
'active_projects', (SELECT count(*) FROM projects WHERE organization_id = org_id AND status = 'active'),
'tasks_completed_30d', (SELECT count(*) FROM tasks t
JOIN projects p ON p.id = t.project_id
WHERE p.organization_id = org_id
AND t.completed_at > now() - interval '30 days')
);
$$ LANGUAGE sql STABLE;
// One network call instead of three separate queries
const { data } = await supabase.rpc('get_dashboard_stats', {
org_id: 'your-org-uuid'
})
Create materialized views for expensive aggregations:
-- Precompute a leaderboard instead of recalculating on every request
CREATE MATERIALIZED VIEW leaderboard AS
SELECT
u.id,
u.username,
count(t.id) AS tasks_completed,
rank() OVER (ORDER BY count(t.id) DESC) AS rank
FROM users u
LEFT JOIN tasks t ON t.assignee_id = u.id AND t.status = 'done'
GROUP BY u.id, u.username;
-- Create an index on the materialized view
CREATE UNIQUE INDEX idx_leaderboard_user ON leaderboard(id);
-- Refresh on a schedule (e.g., via pg_cron or a cron Edge Function)
REFRESH MATERIALIZED VIEW CONCURRENTLY leaderboard;
Configure connection pooling with Supavisor:
// For serverless environments (Vercel, Netlify, Cloudflare Workers):
// Use the pooled connection string with transaction mode
// Dashboard → Settings → Database → Connection string → "Transaction mode"
// The JS SDK uses PostgREST (HTTP) which has its own pooling — no config needed.
// Direct Postgres clients (Prisma, Drizzle, pg) need the pooled string:
import { Pool } from 'pg'
const pool = new Pool({
connectionString: 'postgres://postgres.[ref]:[pwd]@aws-0-[region].pooler.supabase.com:6543/postgres',
max: 5, // Keep low in serverless — Supavisor manages the upstream pool
idleTimeoutMillis: 10000,
})
Use Edge Functions for compute-heavy operations close to data:
// supabase/functions/generate-report/index.ts
// Edge Functions run in the same region as your database — low latency
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
Deno.serve(async (req) => {
const supabase = createClient(
Deno.env.get('SUPABASE_URL')!,
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!
)
// Heavy aggregation runs next to the database, not in the user's browser
const { data } = await supabase.rpc('get_dashboard_stats', {
org_id: (await req.json()).org_id
})
return new Response(JSON.stringify(data), {
headers: { 'Content-Type': 'application/json' }
})
})
Enable read replicas on Pro+ plans for read-heavy workloads — route analytics and reporting queries to the replica to offload the primary.
Output
After completing these steps, you will have:
- Diagnostic baseline from
pg_stat_statements,index-usage, andcache-hit - Targeted indexes on slow query columns, foreign keys, and common filter patterns
- Query plans verified with
EXPLAIN ANALYZEshowing Index Scan instead of Seq Scan - Client queries optimized with column selection, pagination, and joined queries
- RPC functions and materialized views for expensive server-side aggregations
- Connection pooling configured via Supavisor for serverless deployments
- Edge Functions deployed for compute-heavy operations near the database
Error Handling
| Symptom | Cause | Fix |
|---|---|---|
Seq Scan in EXPLAIN output on large table | Missing index on filtered/sorted column | CREATE INDEX on the column(s) in the WHERE/ORDER BY clause |
PGRST000: could not connect to server | Connection pool exhausted | Switch to Supavisor pooled connection string; reduce max pool size in serverless |
Slow RLS policies (visible in pg_stat_statements) | Subquery in policy evaluates per row | Refactor to security definer function or use EXISTS instead of IN |
| Response payloads > 1MB | select('*') returning all columns/rows | Use .select('col1, col2') and .range() for pagination |
| Stale materialized view data | View not refreshed after writes | Set up pg_cron or a cron Edge Function to run REFRESH MATERIALIZED VIEW CONCURRENTLY |
cache-hit ratio below 99% | Working set exceeds RAM (shared_buffers) | Upgrade compute add-on or optimize queries to access fewer pages |
| High latency on aggregation endpoints | Aggregation computed live on every request | Move to materialized view or RPC function; cache at the Edge Function layer |
Examples
Before/after index optimization:
-- Before: 450ms, Seq Scan
EXPLAIN (ANALYZE) SELECT * FROM orders WHERE customer_id = 'abc-123';
-- Seq Scan on orders (cost=0.00..15234.00 rows=50 width=128) (actual time
---
*Content truncated.*
When not to use it
- →When queries are already fast
- →When connections are not exhausted
- →When response payloads are not bloated
Prerequisites
Limitations
- →High latency on aggregation endpoints if computed live
- →RLS policies can cause performance issues with per-row subqueries
How it compares
This skill offers a structured, measurable approach to Supabase performance tuning using specific SQL and client-side patterns, unlike general database optimization advice.
Compared to similar skills
supabase-performance-tuning side by side with the closest alternatives in the catalog.
| Skill | Installs | Updated | Safety | Difficulty |
|---|---|---|---|---|
| supabase-performance-tuning (this skill) | 4 | 26d | Review | Advanced |
| sql-optimization-patterns | 64 | 2mo | No flags | Advanced |
| supabase-postgres-best-practices | 4 | 6mo | No flags | Intermediate |
| analyzing-query-performance | 1 | 26d | Review | Intermediate |
Try saying
Example prompts that trigger this skill in your AI assistant.
More by jeremylongshore
View all by jeremylongshore →You might also like
sql-optimization-patterns
wshobson
Master SQL query optimization, indexing strategies, and EXPLAIN analysis to dramatically improve database performance and eliminate slow queries. Use when debugging slow queries, designing database schemas, or optimizing application performance.
supabase-postgres-best-practices
davila7
Postgres performance optimization and best practices from Supabase. Use this skill when writing, reviewing, or optimizing Postgres queries, schema designs, or database configurations.
analyzing-query-performance
jeremylongshore
Execute use when you need to work with query optimization. This skill provides query performance analysis with comprehensive guidance and automation. Trigger with phrases like "optimize queries", "analyze performance", or "improve query speed".
find-hypertable-candidates
timescale
Use this skill to analyze an existing PostgreSQL database and identify which tables should be converted to Timescale/TimescaleDB hypertables. **Trigger when user asks to:** - Analyze database tables for hypertable conversion potential - Identify time-series or event tables in an existing schema - Evaluate if a table would benefit from Timescale/TimescaleDB - Audit PostgreSQL tables for migration to Timescale/TimescaleDB/TigerData - Score or rank tables for hypertable candidacy **Keywords:** hypertable candidate, table analysis, migration assessment, Timescale, TimescaleDB, time-series detection, insert-heavy tables, event logs, audit tables Provides SQL queries to analyze table statistics, index patterns, and query patterns. Includes scoring criteria (8+ points = good candidate) and pattern recognition for IoT, events, transactions, and sequential data.
databases
mrgoonie
Work with MongoDB (document database, BSON documents, aggregation pipelines, Atlas cloud) and PostgreSQL (relational database, SQL queries, psql CLI, pgAdmin). Use when designing database schemas, writing queries and aggregations, optimizing indexes for performance, performing database migrations, configuring replication and sharding, implementing backup and restore strategies, managing database users and permissions, analyzing query performance, or administering production databases.
migrate-postgres-tables-to-hypertables
timescale
Use this skill to migrate identified PostgreSQL tables to Timescale/TimescaleDB hypertables with optimal configuration and validation. **Trigger when user asks to:** - Migrate or convert PostgreSQL tables to hypertables - Execute hypertable migration with minimal downtime - Plan blue-green migration for large tables - Validate hypertable migration success - Configure compression after migration **Prerequisites:** Tables already identified as candidates (use find-hypertable-candidates first if needed) **Keywords:** migrate to hypertable, convert table, Timescale, TimescaleDB, blue-green migration, in-place conversion, create_hypertable, migration validation, compression setup Step-by-step migration planning including: partition column selection, chunk interval calculation, PK/constraint handling, migration execution (in-place vs blue-green), and performance validation queries.