ablevarghese/ios-claude-toolkit/supabase-postgres-best-practices

Claude Code and agent skill by ablevarghese/ios-claude-toolkit

Trust tier 3
  • community
Source check pending

Checking that the SKILL.md file is still in the repository.

Query is slow, optimize database, add an index, RLS policy. Postgres query optimization, schema design, indexing, RLS policy performance, and connection pooling best practices. Trigger on: 'slow query', 'EXPLAIN ANALYZE', 'add an index', 'RLS is slow', 'optimize this query', 'N+1 problem', 'connection pooling', 'Supavisor', 'SELECT * performance', 'database health', 'Edge Function database access', or any question about making Postgres faster. For creating/repairing/pushing migrations, use atlas-database instead.

Install

npx vskill@latest install ablevarghese/ios-claude-toolkit/supabase-postgres-best-practices

SKILL.md

The same SKILL.md was published earlier as ablevarghese/ios-claude-toolkit/supabase-postgres-best-practices.

Supabase Postgres Best Practices

Iron Law: "Every query touching user data must go through RLS. Service role keys never reach the client."

Comprehensive performance optimization guide for Postgres, maintained by Supabase. Contains rules across 8 categories, prioritized by impact to guide automated query optimization and schema design.

Source: github.com/supabase/agent-skills


Rationalizations (Do Not Skip)

RationalizationWhy It's WrongRequired Action
"The query is fast enough""Fast enough" today is slow tomorrow. Database performance degrades non-linearly: a query that's 50ms at 10K rows becomes 5 seconds at 1M rows. By the time you notice, it's a production incident.Run EXPLAIN ANALYZE on every query that touches a table expected to exceed 10K rows. Add indexes proactively.
"We don't need indexes yet"Sequential scans on unindexed columns are the #1 cause of Postgres performance issues. Adding indexes retroactively on large tables locks the table for writes (unless you use CONCURRENTLY, which you probably won't remember under pressure).Add indexes at table creation time for every column used in WHERE, JOIN, and ORDER BY clauses.
"RLS is too slow"RLS adds 0.1-0.5ms per query when policies use direct column comparisons with auth.uid(). That's negligible. RLS being "slow" almost always means the policy uses a subquery or function call that triggers per-row evaluation. The fix is better policies, not disabling RLS.Write efficient RLS policies using direct comparisons. Index the columns used in RLS policies. Never disable RLS on user-facing tables.
"We'll optimize when we scale"Database optimization at scale is 10x harder because you can't easily run migrations, you can't test with production-scale data locally, and every change risks downtime. Build the right patterns now when they're cheap.Follow the patterns in this guide from the start. Proper schema design, indexing, and RLS policies are not premature optimization -- they're baseline engineering.
"SELECT * is fine for our use case"SELECT * fetches all columns including large JSONB blobs, text fields, and columns you added "just in case." It also breaks if you add a column with sensitive data later -- suddenly your API returns it.Select only the columns you need. Create specific views for different access patterns.
"Service role key is safe in our Edge Function"Edge Functions run server-side, so service_role is acceptable there. But if you're passing the service_role key from a client to an Edge Function, or if your Edge Function uses service_role when anon would suffice, you've expanded your attack surface unnecessarily.Use anon key (RLS-enforced) for client-initiated operations. Use service_role only when explicitly bypassing RLS for admin operations in trusted server-side code.

Red Flags -- STOP

  • SELECT * in production queries: Fetches unnecessary data, breaks when schema changes, may expose sensitive columns. Always specify columns.
  • Missing RLS on user-facing tables: Any table accessible through the Supabase client (anon key) without RLS is a complete data breach. Enable RLS and add policies immediately.
  • N+1 query patterns: Querying in a loop (for each user, fetch their transfers) instead of a single JOIN query. This turns 1 query into N+1 queries and destroys performance.
  • Sequential scans on large tables: EXPLAIN ANALYZE showing Seq Scan on a table with >10K rows means you're scanning every row. Add an index.
  • Service role key in client code: The service_role key bypasses ALL RLS. If it's in your iOS app bundle, JavaScript, or any client-accessible code, every user can access every row in every table.
  • Missing connection pooling: Direct connections from serverless functions exhaust the connection pool in minutes. Always use Supavisor (port 6543) for pooled connections.

When NOT to Use This Skill

  • Migration file creation and management: For creating, repairing, and pushing Supabase migrations, see atlas-database.
  • Stripe webhook data storage: For designing webhook event storage with idempotent processing, see stripe-best-practices (but use schema patterns from this skill).
  • Application-level data access patterns: This skill covers database-level optimization. For service/repository layer patterns in Swift, see forge-development.
  • Database backup and disaster recovery: For backup strategies and point-in-time recovery, consult Supabase documentation directly.

Decision Framework

Query Optimization Decision Tree
Is the query slow (>100ms for simple, >500ms for complex)?
|
YES --> Run EXPLAIN ANALYZE
| |
| Is there a Seq Scan on a large table?
| YES --> Add index on the filtered/joined column
| Use partial index if filtering on a subset (e.g., WHERE status = 'active')
| NO --> Is there a Nested Loop Join on large datasets?
| YES --> Verify JOIN columns are indexed
| Consider using a CTE or subquery to reduce the join input
| NO --> Is actual rows >> estimated rows?
| YES --> Run ANALYZE on the table to update statistics
| NO --> Check for unnecessary columns (SELECT *)
| Check for missing LIMIT on unbounded queries
|
NO --> Is it a frequently executed query?
YES --> Monitor over time. Small queries add up.
NO --> No action needed.
Index Selection Decision Tree
What column am I indexing?
Equality comparison (WHERE col = value)?
--> B-tree index (default): CREATE INDEX idx ON table(col);
Range comparison (WHERE col > value, BETWEEN)?
--> B-tree index: CREATE INDEX idx ON table(col);
Full-text search (WHERE col @@ to_tsquery(...))?
--> GIN index: CREATE INDEX idx ON table USING gin(col);
JSONB containment (WHERE col @> '{"key": "value"}')?
--> GIN index: CREATE INDEX idx ON table USING gin(col);
JSONB specific path (WHERE col->>'key' = 'value')?
--> B-tree on expression: CREATE INDEX idx ON table((col->>'key'));
Geometric / spatial queries?
--> GiST index: CREATE INDEX idx ON table USING gist(col);
Array containment (WHERE col @> ARRAY[...])?
--> GIN index: CREATE INDEX idx ON table USING gin(col);
Only need index for a subset of rows?
--> Partial index: CREATE INDEX idx ON table(col) WHERE condition;

EXPLAIN ANALYZE Reading Guide

Understanding query plans is the single most important database optimization skill.

Running EXPLAIN ANALYZE
sql
-- Always use ANALYZE (executes the query) for accurate timing
-- Use BUFFERS for I/O information
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)
SELECT t.id, t.amount, u.full_name
FROM transfers t
JOIN users u ON t.sender_id = u.id
WHERE t.status = 'completed'
AND t.created_at > now() - interval '30 days'
ORDER BY t.created_at DESC
LIMIT 20;
Reading the Output
Limit (cost=0.86..45.32 rows=20 width=48) (actual time=0.128..0.342 rows=20 loops=1)
-> Nested Loop (cost=0.86..1234.56 rows=555 width=48) (actual time=0.126..0.338 rows=20 loops=1)
-> Index Scan Backward using idx_transfers_created_at on transfers t
(cost=0.43..789.12 rows=555 width=40) (actual time=0.089..0.198 rows=20 loops=1)
Filter: (status = 'completed')
Rows Removed by Filter: 5
-> Index Scan using users_pkey on users u
(cost=0.43..0.80 rows=1 width=16) (actual time=0.006..0.006 rows=1 loops=20)
Index Cond: (id = t.sender_id)
Planning Time: 0.245 ms
Execution Time: 0.389 ms
Buffers: shared hit=65
What Each Field Means
FieldMeaningWhat to Look For
cost=X..YEstimated startup..total cost (arbitrary units)Higher = more expensive
rows=NEstimated number of rows outputCompare with actual rows
actual time=X..YReal execution time in msTotal time of operation
actual rows=NReal rows returnedIf >> estimated, run ANALYZE
loops=NHow many times this node executedHigh loops in nested loops = expensive
Buffers: shared hit=NPages read from cacheHigher = more I/O
Buffers: shared read=NPages read from diskHigh = needs more cache or index
Warning Signs in EXPLAIN ANALYZE
SignProblemSolution
Seq Scan on large tableFull table scan, no index usedAdd index on filtered column
actual rows >> estimated rowsStale statisticsRun ANALYZE table_name;
Nested Loop with high loopsN+1 join patternAdd index on JOIN column
Sort with external mergeSort spilling to diskAdd index matching ORDER BY, or increase work_mem
Hash Join with high memoryLarge hash table in memoryMay need more work_mem or different join strategy
Filter: Rows Removed (large)Index fetch then discardUse partial index or refine WHERE clause

Rule Categories by Priority

PriorityCategoryImpactReference
1Query PerformanceCRITICALreferences/query-patterns.md
2Connection ManagementCRITICALreferences/query-patterns.md
3Security & RLSCRITICALBelow
4Schema DesignHIGHreferences/schema-patterns.md
5Concurrency & LockingMEDIUM-HIGHreferences/schema-patterns.md
6Migration Best PracticesMEDIUMreferences/migration-patterns.md
7Monitoring & DiagnosticsLOW-MEDIUMBelow
8Edge Functions PatternsLOWBelow

3. Security & RLS (CRITICAL)

Always Enable RLS
sql
-- MANDATORY for all user-facing tables
ALTER TABLE transfers ENABLE ROW LEVEL SECURITY;
-- Deny all access by default
-- Then add specific policies
Write Efficient RLS Policies
sql
-- BAD: Subquery in policy (executes per row)
CREATE POLICY "Users see own transfers" ON transfers
FOR SELECT USING (
sender_id IN (SELECT id FROM users WHERE auth.uid() = id)
);
-- GOOD: Direct comparison (uses index)
CREATE POLICY "Users see own transfers" ON transfers
FOR SELECT USING (sender_id = auth.uid());
RLS Policy Performance Patterns
sql
-- Pattern 1: Direct uid comparison (fastest)
CREATE POLICY "own_data" ON transfers
FOR ALL USING (user_id = auth.uid());
-- Pattern 2: Role-based with JWT claims (fast)
CREATE POLICY "admin_access" ON transfers
FOR ALL USING (
auth.jwt()->>'role' = 'admin'
OR user_id = auth.uid()
);
-- Pattern 3: Team-based with indexed lookup (acceptable)
-- REQUIRES: CREATE INDEX idx_team_members_user ON team_members(user_id);
CREATE POLICY "team_access" ON documents
FOR SELECT USING (
team_id IN (
SELECT team_id FROM team_members WHERE user_id = auth.uid()
)
);
-- This subquery is OK because it filters a small set per user
-- Pattern 4: AVOID -- function call per row
CREATE POLICY "complex_access" ON transfers
FOR SELECT USING (
has_access(auth.uid(), id) -- Function called for EVERY row
);
Use Security Definer Functions Carefully
sql
-- Use security definer for admin operations that bypass RLS
CREATE OR REPLACE FUNCTION admin_get_transfer(transfer_id uuid)
RETURNS transfers
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
BEGIN
-- Always validate inputs in security definer functions
IF transfer_id IS NULL THEN
RAISE EXCEPTION 'transfer_id cannot be null';
END IF;
RETURN (SELECT * FROM transfers WHERE id = transfer_id);
END;
$$;
Service Role Key Safety

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 95 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

7-day trend score
0

Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/ablevarghese/ios-claude-toolkit/supabase-postgres-best-practices/badge)](https://verified-skill.com/skills/ablevarghese/ios-claude-toolkit/supabase-postgres-best-practices)

Something wrong with this skill or its page? Tell us.