0
Challenge · 59RLS at Scale

RLS performance: (select auth.uid()) & indexes

Perfused in ~85% of apps

Every policy you've written so far has been correct. None of them has had to survive a table with two million rows. A policy is invisible in your code, which is exactly what makes it easy to forget it isn't invisible to the query planner — it runs on every row a query touches, and the three ways to make that expensive (a function call that can't be cached, a predicate column with no index, a subquery shaped the wrong way) are all things you can spot, and fix, in under a minute with EXPLAIN.

Core idea. RLS performance comes down to three concrete, checkable decisions. First: wrap `auth.*()` calls in `(select ...)` so the planner can cache them as an InitPlan — but only calls that don't vary per row benefit; a helper function called with a row's own column, like `is_org_member(org_id)`, is still re-run once per row no matter how you wrap it, because the wrapping doesn't remove the correlation. Second: index every column a policy predicate touches, exactly as you would for a WHERE clause. Third: prefer a subquery shape where the caller's own data ("which orgs am I in") is computed ONCE and matched against every row, over a shape that asks "is this specific row's org mine" once per row.
Playground, this isn't a screenshot
Live demointeractive
Real Postgres · in your browseridle
team_posts has a REAL policy installed — using ((select is_org_member(org_id))) — on 3,000 rows across 5 orgs. Run this as alice (impersonated) and note the total Execution Time and the loops count next to SubPlan. Later in this concept you'll run the identical query against a rewritten policy and compare.
Querying as
Cmd/Ctrl + Enter
↑ play a little first, then dig in