Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Comprehensive Postgres performance optimization and best practices guide maintained by Supabase
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/security-rls-performance.md
1---2title: Optimize RLS Policies for Performance3impact: HIGH4impactDescription: 5-10x faster RLS queries with proper patterns5tags: rls, performance, security, optimization6---78## Optimize RLS Policies for Performance910Poorly written RLS policies can cause severe performance issues. Use subqueries and indexes strategically.1112**Incorrect (function called for every row):**1314```sql15create policy orders_policy on orders16using (auth.uid() = user_id); -- auth.uid() called per row!1718-- With 1M rows, auth.uid() is called 1M times19```2021**Correct (wrap functions in SELECT):**2223```sql24create policy orders_policy on orders25using ((select auth.uid()) = user_id); -- Called once, cached2627-- 100x+ faster on large tables28```2930Use security definer functions for complex checks:3132```sql33-- Create helper function (runs as definer, bypasses RLS)34create or replace function is_team_member(team_id bigint)35returns boolean36language sql37security definer38set search_path = ''39as $$40select exists (41select 1 from public.team_members42where team_id = $1 and user_id = (select auth.uid())43);44$$;4546-- Use in policy (indexed lookup, not per-row check)47create policy team_orders_policy on orders48using ((select is_team_member(team_id)));49```5051Always add indexes on columns used in RLS policies:5253```sql54create index orders_user_id_idx on orders (user_id);55```5657Reference: [RLS Performance](https://supabase.com/docs/guides/database/postgres/row-level-security#rls-performance-recommendations)58