Contact
EngineeringNov 13, 2026ยท24 min read

Postgres RLS Performance: What Makes a Policy Slow, Measured on PostgreSQL 18.7

KT
Keplaris TeamNov 13, 2026
On a cream background, a matte black conveyor of frosted glass tiles queued at a gate while tiles with green lights pass on a fast lane marked by a blue line

Postgres row-level security (RLS) performance is about the same as a plain WHERE clause when the policy compares tenant_id to a per-statement value and an index leads with tenant_id. On PostgreSQL 18.7 with 1,000,000 seeded rows across 1,000 tenants, a warm cache and an index on (tenant_id, created_at), the largest tenant's latest-20 query had a median of 0.014 ms under the policy and 0.015 ms with a WHERE on a copy without RLS. RLS gets slow when a policy function runs once per row, when a membership subquery forces a full scan, or when your own filter passes a column to a function that isn't leakproof. With no tenant index, a count for a 544-row tenant had a median of 1,184.6 ms when the policy called a SECURITY DEFINER SQL function and 39.1 ms with that call wrapped in (select ...). The difference shows up as one line of the query plan: Index Cond or Filter.

Keplaris, a New York product engineering studio, ran these timings three times on PostgreSQL 18.7 (official postgres:18 image, Docker on an Apple M1 Max laptop) and published run 1 unedited with the script at the end. Postgres schema and policy design for multi-tenant products is part of our API and SaaS development work.

This post measures cost only. The ways RLS leaks across tenants are tested in multi-tenant SaaS architecture, and we don't repeat them here.

Postgres RLS performance: the short answer

RLS was cheap when the policy became an Index Cond, a condition Postgres uses to search the index. Every expensive case we found ran a function or subquery per row in a Filter, a condition checked on every row the scan reads.

PostgreSQL 18.7, 1,000,000 rows, warm cache, Docker on an Apple M1 Max, run 1, medians in ms. Whale: tenant 1, 399,015 rows. Small: tenant 7, 544 rows.

Policy shapeMedian, msVerdict and plan lineFix, median ms
Tenant policy, index leads with tenant_idWhale latest 20: 0.014; no RLS 0.015Cheap, Index CondNone needed
Same policy, app also sends the same WHEREWhale count: 17.1; policy only 13.4No gain, One-Time FilterOptional
current_setting() wrapped, (tenant_id) indexWhale count: 21.2; direct 17.8Small cost on big tenantsCall it directly
Same policy, (created_at) index onlySmall latest 20: 5.353Hurts small tenants, FilterLead with tenant_id: 0.018
current_setting() direct, no tenant indexSmall count: 44.7; no RLS 19.7Hurts, FilterWrap in (select ...): 20.9
Default plpgsql function, no tenant indexSmall count: 532.3Hurts, Filter even with an indexWrap: 37.8
SECURITY DEFINER SQL function, no tenant indexSmall count: 1,184.6Hurts, FilterWrap: 39.1
Membership IN or EXISTS subquerySingle-tenant user count: 34.8 and 128.2Hurts, Seq Scan with SubPlan= any(array(select ...)), counts only: 0.049 (its latest 20: 0.312)
Your filter uses lower(email)Whale lookup: 96.9; no RLS 0.010Hurts, Seq ScanStored lowercased column: 0.010
10,000-row update, WITH CHECK, mid tenantSimple policy 62.9; no RLS 61.7Cheap if simple, same scanPlain comparison (membership subquery: 78.2)

Ashwin Sridhar's dev.to post (May 29, 2026, per the page's timestamp) says "Policy evaluation is not your bottleneck." Tom Lane wrote on pgsql-bugs on 2025-05-30: "The real story is that RLS is a performance killer in multiple ways, so if you need speed you're better off looking for an alternative solution to your security requirements." Both are right, for different policy shapes.

The rules we would ship with:

  1. Lead every index on a tenant table with tenant_id.
  2. Never pass a row column into a policy function; it runs once per row.
  3. Wrap helper function calls in (select ...); a bare current_setting() needs it only when no index leads with tenant_id.
  4. Declare helper functions STABLE and PARALLEL SAFE when they are.
  5. Compute a user's tenant list once, as an array, not in an IN or EXISTS subquery; for ordered pages, a user in one tenant was faster on the plain tenant_id policy.
  6. Keep non-leakproof functions on your columns out of your own WHERE clauses on RLS tables.

On performance alone, nothing we measured argues for moving tenant filtering into the app: each slow shape had a fix within a few hundredths of a millisecond of the no-RLS query for the 544-row tenant, and within 4 ms for the whale. We didn't time a no-RLS baseline for the membership forms.

How we measured: PostgreSQL 18.7, 1,000,000 rows, three runs

One Node script did everything below on one local Docker container, with synthetic data, not client, production or Keplaris product data.

Data. documents gets 1,000,000 seeded rows with tenant_id, a five-value status, a mixed-case email, a created_at across 2026 and a stored generated email_lower. The skew is a test choice: the whale (tenant 1) has 399,015 rows, the mid tenant (2) 49,802, the small tenant (7) 544, and tenants 3 to 1,000 share the rest. documents_norls, an identical copy with the same indexes and no RLS, is the baseline for every "no RLS" cell. In memberships, user 1 (the consultant) belongs to 200 tenants (558,217 visible rows) and user 2 only to tenant 7.

Roles and timing. documents has ENABLE and FORCE ROW LEVEL SECURITY, and every timed query runs as app_user, neither owner nor superuser, inside BEGIN, SET LOCAL statement_timeout = '30s', set_config('app.tenant_id', $1, true), the query, ROLLBACK. Each cell gets three untimed warm-ups, then 21 timed runs of EXPLAIN (ANALYZE, BUFFERS, TIMING OFF, FORMAT JSON), or five if the first warm-up took 50 ms or more; we report the server's Execution Time, median and nearest-rank p95 (with five runs, the maximum). No cell hit the timeout. A separate execution counts calls to our own functions in pg_stat_user_functions (built-ins aren't counted).

Runs. Three runs on fresh containers on 2026-11-13, about 131 seconds each; plans, row counts, call counts and results were identical, timings varied. All 150 cells returned the same result as the no-RLS table, an equivalence check for the timings, not an isolation test.

How Postgres applies a policy: security quals and leakproof functions

Postgres adds the policy to each query as a security qual (a security barrier condition) and runs it before any condition from your query that passes the row's columns to a non-leakproof function; the policy itself can still use an index. A LEAKPROOF function promises to reveal nothing about its arguments except through its return value. The PostgreSQL 18 row security docs say the policy "will be evaluated for each row prior to any conditions or functions coming from the user's query," except "leakproof functions, which are guaranteed to not leak information," and the rules and privileges page gives the cost: an index scan "cannot be selected" when a WHERE operator's "underlying function is not marked LEAKPROOF." Several permissive policies, per CREATE POLICY, "will be combined together using the Boolean 'OR' operator."

Two posts apply that rule to the policy itself. Bytebase's "Postgres Row-Level Security Footguns" (Adela, Sep 5, 2025): "When an RLS policy calls a function that isn't marked LEAKPROOF, Postgres can't safely push it down with index scans." Jan Dvorak on dev.to (Mar 17, 2026, per the page's timestamp): "PostgreSQL will only push a security barrier expression into an index scan if every function in that expression is marked as leakproof."

For the policy, the docs and our run disagree with both. CREATE FUNCTION says that "functions which do not take arguments or which are not passed any arguments from the security barrier view or table do not have to be marked as leakproof to be executed before security conditions." current_setting() gets no argument from the table, and neither does our plpgsql STABLE function; both have proleakproof = false, and both policies became index conditions, the first printed as Index Cond: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer). What blocked an index was volatility, and leakiness in the user's own filter. Bytebase's example also adds title ILIKE '%search%', which a btree can't serve even without RLS (index types).

On PostgreSQL 18.7, 264 of 524 boolean-returning operator functions are not leakproof:

select count(*) filter (where not p.proleakproof) as not_leakproof, count(*) as total
from pg_proc p
where p.oid in (select o.oprcode from pg_operator o where o.oprresult = 'boolean'::regtype);

Does RLS slow down Postgres queries compared with a WHERE clause?

Row-level security barely slows a query when an index leads with tenant_id: on PostgreSQL 18.7 with an index on (tenant_id, created_at), the policy alone matched a WHERE on the no-RLS table within run-to-run noise for latest 20 and counts. Adding the same WHERE on top of the policy made the whale's count slower, 17.1 ms against 13.4 ms.

PostgreSQL 18.7, index (tenant_id, created_at), run 1, median (p95) in ms:

Query and formWhaleMidSmall
Latest 20, no RLS + WHERE0.015 (0.021)0.016 (0.026)0.016 (0.018)
Latest 20, RLS only0.014 (0.019)0.014 (0.023)0.016 (0.033)
Latest 20, RLS + same WHERE0.014 (0.019)0.015 (0.021)0.033 (0.042)
Count, no RLS + WHERE14.5 (15.9)3.124 (3.422)0.042 (0.047)
Count, RLS only13.4 (14.2)2.945 (3.463)0.042 (0.054)
Count, RLS + same WHERE17.1 (17.7)4.839 (5.063)0.062 (0.075)
Open since Dec 1, no RLS + WHERE3.466 (4.298)1.162 (1.476)0.038 (0.060)
Open since Dec 1, RLS only3.767 (4.654)1.142 (1.476)0.033 (0.064)

Across runs the whale counts overlapped, but two gaps held in all three 18.7 runs: the whale's "open since Dec 1" query (3.767 to 4.396 ms under RLS, 3.387 to 3.466 without, same plan and buffers, unexplained, and reversed in the 18.6 run, 3.536 against 3.587) and the RLS-plus-WHERE count (17.1 to 18.4 ms).

Supabase's RLS performance guide says to filter in the client too: "Even though this duplicates the contents of the policy, Postgres can use the filter to construct a better query plan." With this index, it didn't: the planner used Index Cond: (documents.tenant_id = 1) from the WHERE and moved the policy into a One-Time Filter on a Result node, the only plan difference. The duplicate may help where the policy can't be an index condition; we didn't time that case.

Wrapping current_setting() in a select: when the InitPlan helps

Wrapping current_setting() in (select ...) helps when the policy runs as a Filter and doesn't help when it is an Index Cond. On PostgreSQL 18.7 with no tenant index, the 544-row tenant's count took 44.7 ms direct and 20.9 ms wrapped; with a (tenant_id) index, the wrap made the whale's count slower, 21.2 ms against 17.8 ms. With a tenant index the value is computed once per scan anyway; the PostgreSQL 18 volatility page says "an index scan will evaluate the comparison value only once." Without one, the direct call runs per row in a Filter, and the wrap turns it into one InitPlan, a subplan Postgres runs once per query and reuses for every row. Our untimed PGlite test of the same wrap compared only plan shapes and row counts, which a wrap doesn't change, even in its four cases where the policy was a Filter.

PostgreSQL 18.7, count(*), run 1, median (p95) in ms. Calls: our function's tracked calls in one execution, planner included.

Policy formNo tenant index, small(tenant_id) index, whale(tenant_id) index, smallCalls (no index; index)
No RLS, WHERE tenant_id = n19.7 (20.1)17.2 (18.8)0.040 (0.050)n/a
current_setting() direct44.7 (45.4)17.8 (18.5)0.045 (0.052)not tracked
current_setting() wrapped20.9 (21.8)21.2 (22.1)0.046 (0.055)not tracked
SQL STABLE function110.2 (111.2)21.7 (22.2)0.041 (0.050)0; 0
SQL STABLE PARALLEL SAFE function44.8 (47.4)17.3 (18.1)0.047 (0.052)0; 0
plpgsql, default VOLATILE532.3 (537.3)531.0 (546.8)518.5 (528.4)1,000,000; 1,000,000
plpgsql default, wrapped37.8 (39.0)20.8 (21.3)0.045 (0.053)1; 1
plpgsql STABLE PARALLEL SAFE174.9 (177.8)16.5 (17.7)0.038 (0.049)1,000,001; 4 whale, 2 small
SQL SECURITY DEFINER1,184.6 (1,190.6)21.0 (22.5)0.047 (0.056)1,000,001; 2
SQL SECURITY DEFINER, wrapped39.1 (43.7)20.7 (21.6)0.044 (0.056)1; 1
plpgsql STABLE taking tenant_id187.8 (188.9)182.2 (183.7)180.3 (181.6)1,000,000; 1,000,000

With the index, every form but the default plpgsql function and the one taking tenant_id was an Index Cond. In this table, medians over 1 ms moved under 10% across runs, except the wrapped definer whale cell and the tenant_id function with the index.

Supabase's caveat, from its RLS performance and best practices page: "You can only do this if the results of the query or function do not change based on the row data."

The wrap costs something on big tenants. With the index, every wrapped form estimated 1,000 rows for the whale against 399,015 actual and got no parallel workers; we didn't isolate the cause. The direct call ran with two workers (16.3 to 17.8 ms across runs, wrapped 20.4 to 21.2), and the PARALLEL UNSAFE SQL STABLE and definer functions, also without workers, took 21.7 and 21.0 ms direct. So wrap helper function calls, since a default helper stays a per-row Filter even with an index (531.0 ms against 20.8 ms wrapped for the whale), and leave a bare current_setting() unwrapped when an index leads with tenant_id.

Supabase RLS performance: the same rule for auth.uid()

Supabase's advice to wrap auth.uid() in (select ...) follows the same rule. We didn't test Supabase or PostgREST, and our function reads current_setting(), so this is the Postgres mechanism behind the advice, not a Supabase measurement. Splinter's "Auth RLS InitPlan" lint (0003, WARN) says there is "no downside" to wrapping; with a tenant-leading index we found one. Its multiple permissive policies lint (0006, WARN) says "all of the relevant RLS policies must be applied/tested before Postgres can determine if a row should be visible"; we didn't time OR'd policies. We don't compare our numbers with the timing tables on Supabase's RLS performance and best practices page, which mix "ms" cells with bare numbers and name no Postgres version.

Why policy functions make RLS slow: volatility, parallel safety and SECURITY DEFINER

A function's declaration decided whether it ran once or 1,000,000 times and whether the query got parallel workers (the pg_proc table is in the output). CREATE FUNCTION says "If none of these appear, VOLATILE is the default assumption," and PARALLEL UNSAFE is the default too.

Parallel safety survives inlining. The parallel safety page says: "When a query contains anything that is parallel unsafe, parallel query is completely disabled for that query." Our two SQL STABLE functions were inlined (0 calls, the current_setting() expression printed in their place), yet the PARALLEL UNSAFE one got no workers (110.2 ms) and the PARALLEL SAFE one got two (44.8 ms).

STABLE is not a per-query cache. The volatility page says STABLE "allows the optimizer to optimize multiple calls of the function to a single call." The run shows that only in the index condition (two calls for the small tenant, four for the whale's parallel scan; the 547-row estimate suggests one of them was the planner's); in a Filter the same plpgsql STABLE function ran 1,000,001 times. Bytebase says a STABLE LEAKPROOF function taking a row's region lets Postgres "cache the result within a query"; our plpgsql STABLE one taking tenant_id ran 1,000,000 times (we didn't run their SQL version).

SECURITY DEFINER and SET block inlining. The definer SQL function was called 1,000,001 times where the plain one was inlined. The PostgreSQL wiki page "Inlining of SQL functions" requires that "the function is not SECURITY DEFINER" and "has no SET clauses"; ours had both, so the run doesn't say which one stopped it. A definer function also runs with its owner's privileges and needs SET search_path with pg_temp last; multi-tenant SaaS architecture covers that risk.

Indexes for RLS: tenant_id first, and the cost of adding it

An index that leads with tenant_id lets the policy narrow the scan to one tenant. This repeats Test 6 from multi-tenant SaaS architecture, which reported plans only, with timings and ten times the rows.

PostgreSQL 18.7, direct policy, latest 20, run 1, median (p95) in ms:

Index (size)WhaleMidSmall
(created_at) (22,487,040 bytes)0.022 (0.026)0.074 (0.085)5.353 (5.664)
(tenant_id) (7,200,768 bytes)43.5 (46.4)29.6 (31.9)0.300 (0.562)
(tenant_id, created_at) (31,563,776 bytes)0.014 (0.019)0.015 (0.021)0.018 (0.023)

With only (created_at), the small tenant's latest 20 stepped over 36,399 other tenants' rows, the whale over 36: the noisy-neighbor problem at the storage layer (the API half is per-tenant limits, in SaaS API rate limiting). With (tenant_id) alone, big tenants got parallel bitmap heap scans over all of their rows.

Tom Lane, in a 2023-10-13 pgsql-performance reply: "Adding tenant_id is going to bloat your indexes quite a bit, so I wouldn't do that except in cases where you've demonstrated it's important." Here it added 40% to the created_at index, 10% to lower(email) (59,039,744 against 53,854,208 bytes) and 3% to status. For a small tenant's 5 ms latest 20, we would pay that.

On a live table, build it with CREATE INDEX CONCURRENTLY; zero-downtime Postgres migrations covers the invalid index a failed build leaves. A tenant_id added late is one of the jobs in what breaks when a SaaS hits product-market fit.

Membership-table policies: why IN and EXISTS are slow

Membership policies were fast for counts when the tenant list was computed once and handed to the index, and slow as IN or EXISTS subqueries. memberships had a (user_id, tenant_id) primary key and no policy.

PostgreSQL 18.7, index (tenant_id, created_at), run 1, median (p95) in ms:

Policy formConsultant (200 tenants), countSingle-tenant user, countSingle-tenant user, latest 20Plan for counts
IN subquery50.9 (51.4)34.8 (37.1)35.9 (39.9)Parallel Seq Scan, hashed SubPlan
EXISTS correlated159.8 (165.6)128.2 (136.6)129.5 (131.1)Seq Scan, hashed SubPlan, no workers
= any(array(select ...))34.0 (35.9)0.049 (0.059)0.312 (0.538)InitPlan, tenant index
SECURITY DEFINER function returning int[]34.2 (35.8)0.047 (0.056)0.312 (0.429)Index Cond
Same, wrapped34.7 (36.2)0.057 (0.072)0.307 (0.523)InitPlan, tenant index

Postgres rewrote both subquery forms, the correlated EXISTS included, into a hashed lookup on every row of a sequential scan, so a user in one 544-row tenant paid for 1,000,000 rows. For the latest 20, the array forms used a bitmap heap scan of all 544 rows instead of reading 20: 0.312 ms, against 0.016 ms for the plain tenant policy on the same tenant and index. That scan covers every row the user can see, and we timed it only at 544 rows; if the app knows the user's active tenant, use the plain policy. The consultant's latest 20 was slow in every form (63.0 to 273.6 ms), because all 558,217 visible rows are read before the newest 20 can be picked.

The PostgreSQL 18 row security docs allow sub-SELECTs in policies but warn they "can create race conditions that could allow information leakage if care is not taken." We didn't time a membership table with its own policy.

When your own filter loses its index under RLS

A condition in your query that passes a column to a non-leakproof function can't use an index under RLS, and no policy shape we tested fixed that. From the catalog: texteq (text =) and int4eq are leakproof; lower(text), textlike and current_setting() are not.

PostgreSQL 18.7, direct policy, run 1, median (p95) in ms; the no-RLS query adds tenant_id = n:

QueryIndexWhale, no RLSWhale, RLSSmall, no RLSSmall, RLS
lower(email) = value(lower(email))0.010 (0.020)96.9 (97.6)0.010 (0.013)50.2 (50.9)
lower(email) = value(tenant_id, lower(email))0.010 (0.020)96.7 (98.3)0.009 (0.014)0.594 (0.743)
email = value(email)0.009 (0.012)0.011 (0.019)0.010 (0.017)0.009 (0.013)
email_lower = value, stored column(email_lower)0.009 (0.015)0.010 (0.016)0.010 (0.014)0.012 (0.022)

Under RLS, lower(email) = ... stayed in the Filter even with (tenant_id, lower(email)), which the no-RLS query used for both columns; the tenant prefix saved the small tenant, and the whale got a parallel sequential scan. Plain = on email or email_lower uses leakproof texteq and kept its index: whether the operator is leakproof decides it, not RLS.

So store a lowercased column and compare with =. Marking lower() LEAKPROOF needs a superuser and is a security promise, not a speed switch; we don't recommend it. LIKE and ILIKE run through textlike and texticlike, which the catalog also lists as not leakproof, so by the same rule a trigram or prefix search on a column in your query is held behind the policy; we didn't time a search index. A vector index is a different case: on PostgreSQL 18.7 with pgvector 0.8.7 and 500,000 vectors, an HNSW search under a tenant policy with a direct current_setting() returned the same plans, rows and recall as the query with an explicit WHERE.

The 18.7 release notes (2026-11-12) change how leakiness is judged for CaseTestExpr and internal Param nodes; on 18.6 the script gave the same plans.

count(*) and index-only scans under RLS

A count under RLS got an index-only scan when the index contained tenant_id, like the no-RLS count with a tenant WHERE.

PostgreSQL 18.7, count(*) where status = 'open', run 1, median (p95) in ms:

IndexFormWhaleSmallPlan
(status)No RLS + WHERE37.5 (40.3)37.7 (59.7)Parallel Bitmap Heap Scan
(status)RLS only37.3 (39.5)37.6 (45.1)Parallel Bitmap Heap Scan
(tenant_id, status)No RLS + WHERE4.264 (4.675)0.026 (0.036)Index Only Scan, Heap Fetches 0
(tenant_id, status)RLS only4.313 (4.423)0.017 (0.024)Index Only Scan, Heap Fetches 0

Tom Lane's 2023 reply: "When that's enforced, the query can no longer use an index-only scan (because it needs to fetch tenant_id too)." PostgreSQL 18.7 did the same with (status), and so did the hand-filtered query. Heap Fetches was 0 because the seed is vacuumed; a table with many recently changed pages gets less from an index-only scan.

What WITH CHECK costs on INSERT and UPDATE

A simple policy added little to 10,000-row writes; membership policies added more to updates. CREATE POLICY says an UPDATE also applies "the appropriate SELECT or ALL policies."

PostgreSQL 18.7, mid tenant, index (tenant_id, created_at), rolled back and vacuumed each time; run 1 median (p95) in ms, then the three-run median range:

PolicyInsert 10,000 rowsUpdate 10,000 rows
No RLS21.7 (22.6); 21.7 to 21.961.7 (67.2); 57.6 to 61.7
Simple tenant policy23.5 (24.3); 23.1 to 23.562.9 (68.4); 61.7 to 64.0
Membership IN subquery23.2 (24.8); 22.6 to 23.278.2 (92.9); 71.6 to 78.2
Definer int[] function, wrapped23.2 (24.9); 22.2 to 23.282.0 (94.0); 81.1 to 82.0

Updates ran five times, so their p95 is the maximum; every update WHERE included tenant_id = 2. The membership check was a hashed subplan built once, and the wrapped definer form estimated 93 rows instead of 10,000 and used a bitmap scan.

Why is my RLS policy slow? Finding it with EXPLAIN (ANALYZE, BUFFERS)

Every slow case we measured but the wrapped whale count ran a function, subquery or user filter per row in a Filter or SubPlan, so run EXPLAIN as the application role and look there first. The small tenant's count with the default plpgsql policy function, no tenant index, run 1, all 12 lines:

    Aggregate  (cost=280093.50..280093.51 rows=1 width=8) (actual time=531.737..531.738 rows=1.00 loops=1)
      Buffers: shared hit=16290 read=1301
      ->  Seq Scan on documents  (cost=0.00..280091.00 rows=1000 width=0) (actual time=1.698..531.621 rows=544.00 loops=1)
            Filter: (tenant_id = app_tenant_plpgsql())
            Rows Removed by Filter: 999456
            Buffers: shared hit=16290 read=1301
    Planning Time: 0.029 ms
    JIT:
      Functions: 4
      Options: Inlining false, Optimization false, Expressions true, Deforming true
      Timing: Generation 0.104 ms (Deform 0.020 ms), Inlining 0.000 ms, Optimization 0.108 ms, Emission 1.270 ms, Total 1.482 ms
    Execution Time: 531.894 ms
  • Filter: (tenant_id = app_tenant_plpgsql()): the function runs per row; the counter recorded 1,000,000 calls.
  • Rows Removed by Filter: 999456: every row read to keep 544.
  • No InitPlan (the value isn't computed once) and no Gather (the function is PARALLEL UNSAFE).
  • JIT took 1.482 ms of 531.894 ms, so JIT isn't where the time went.

PostgreSQL 18 prints buffers in EXPLAIN ANALYZE by default and Index Searches on index scans (18.0 release notes).

To get the app's plan, not the superuser's:

BEGIN;
SET LOCAL ROLE app_user;
SELECT set_config('app.tenant_id', '7', true);
EXPLAIN (ANALYZE, BUFFERS) SELECT count(*) FROM documents;
ROLLBACK;

Superusers, BYPASSRLS roles and an owner without FORCE skip the policy, so their plans hide it. Zhixuan Lai on the myhoai engineering blog (August 12, 2026): "Our EXPLAIN wasnโ€™t running under the same security context as the production query."

Symptoms, and where they lead:

  • Rows Removed by Filter in the hundreds of thousands, policy in Filter: the index doesn't lead with tenant_id.
  • SubPlan on a sequential scan for a membership policy: use an array form.
  • Your function in Filter, no InitPlan: wrap it or fix its volatility.
  • Your filter is Index Cond as owner but Filter under RLS: a non-leakproof function.

How to measure RLS overhead on your own database

  • Run as the app role, in a transaction like the one above.
  • Time a small and a big tenant. With only (created_at), the small tenant's latest 20 took 5.353 ms and the whale's 0.022 ms, so one tenant size can hide the problem.
  • Use TIMING OFF and the server's Execution Time, after warm-ups, as a median of many runs.
  • Count function calls with track_functions = 'all' and pg_stat_user_functions. Inlined SQL functions show 0 calls, and built-ins like current_setting() aren't counted.
  • Check Workers Launched. The wrapped whale count got no parallel workers and took 21.2 ms against 17.8 ms direct.
  • Rerun on a fresh container before trusting a small gap. The whale's "open since Dec 1" gap held in three 18.7 runs, stayed unexplained and reversed on 18.6.

What this benchmark doesn't prove

  • One machine, Docker Desktop's VM on an Apple M1 Max, loopback only, four unrelated containers running alongside; one connection, so no contention.
  • Synthetic data: 1,000,000 narrow rows, one skew pattern, warm cache, default settings (shared_buffers 128MB, JIT on). The 144,105,472-byte table is larger than shared_buffers, so sequential scans read part of it from the OS page cache.
  • PostgreSQL 18.7, plans checked on 18.6; no managed Postgres, Supabase, PostgREST, PgBouncer or ORM.
  • Not tested: partition pruning under a policy, prepared statements, the round trips of a per-request BEGIN and set_config (transaction-local for the reasons in how to carry tenant context to the database), multiple permissive policies, policies without a TO role clause, sharding.
  • Not a security review or a leak test, and not client or Keplaris product data; we run no multi-tenant SaaS of our own.

Designing policies, indexes and tenant context together is what the Keplaris API and SaaS development team does.

The full benchmark script and output

Save the script as rls-bench.mjs in an empty directory, start a throwaway Postgres 18 container, install the one dependency and run it:

docker run -d --name kep-rls-pg -e POSTGRES_PASSWORD=rls-throwaway -p 127.0.0.1:54333:5432 postgres@sha256:b9f6b8ff03b62f3cfd9d9ba3fe56226a9991c79d3fb46fd46536263bf02be553
npm install --save-exact pg@8.23.1
PGPASSWORD=rls-throwaway PGPORT=54333 node rls-bench.mjs
docker rm -f kep-rls-pg

The digest pins the 18.7 image we ran. The script drops and recreates the rlsbench database and two roles, so use a throwaway server. A run took about 131 seconds.

Run metadata (Node, pg, the full version() string, image digest, machine and settings) is in the output header. Runs started at 07:19, 07:21 and 07:23 UTC on 2026-11-13. A fourth run on postgres:18.6 (postgres@sha256:e3d24f6906d0760bf4da0dae872415391ededefad23fd471c47dc53b0ddf3c42) gave the same plans, counts and results. The counted runs came after three trial runs that found two script bugs: a wrapped array policy that failed with a type error, and call counts leaking between cells.

// rls-bench.mjs: what Postgres row-level security policies cost, timed on synthetic data.
// Synthetic, seeded data on a local server. Needs Node 24+, one npm install (pg) and a
// throwaway Postgres 18 you can drop a database and two roles on. Run:
//   docker run -d --name kep-rls-pg -e POSTGRES_PASSWORD=rls-throwaway -p 127.0.0.1:54333:5432 postgres:18
//   npm install --save-exact pg@8.23.1
//   PGPASSWORD=rls-throwaway PGPORT=54333 node rls-bench.mjs
// Optional env: PGHOST, PGPORT, RLS_IMAGE_DIGEST and RLS_MACHINE (printed in the header),
// RLS_JSON (path for a machine-readable copy of every cell).
import pg from "pg";
import { readFileSync, writeFileSync } from "node:fs";
import { performance } from "node:perf_hooks";

const SEED = 0.20261113; // setseed() for the data
const ROWS = 1_000_000; // documents rows (a test choice)
const WARMUPS = 3; // untimed executions per cell
const N_FAST = 21; // timed executions when the first warm-up ran under FAST_MS
const N_SLOW = 5; // otherwise; with N = 5 the p95 by nearest rank is the maximum
const FAST_MS = 50;
const TIMEOUT = "30s"; // statement_timeout for every measured statement
const WHALE = 1, MID = 2, SMALL = 7; // tenant ids (shares are set by the seed below)
const CONSULTANT = 1, SINGLE = 2; // user ids in memberships
const APP_PW = "rls-bench-app";

const host = process.env.PGHOST ?? "127.0.0.1";
const port = Number(process.env.PGPORT ?? 54333);
const adminCfg = { host, port, user: "postgres", password: process.env.PGPASSWORD };
const out = [];
const log = (s = "") => { out.push(s); console.log(s); };
const cells = [];
const t0 = performance.now();

const admin0 = new pg.Client({ ...adminCfg, database: "postgres" });
await admin0.connect();
await admin0.query("drop database if exists rlsbench");
await admin0.query("drop role if exists app_user");
await admin0.query("drop role if exists app_owner");
await admin0.query("create role app_owner nologin");
await admin0.query(`create role app_user login nobypassrls password '${APP_PW}'`);
await admin0.query("create database rlsbench");
await admin0.query("alter database rlsbench set track_functions = 'all'");
await admin0.end();

const admin = new pg.Client({ ...adminCfg, database: "rlsbench" });
await admin.connect();
const q1 = async (c, sql, args) => (await c.query(sql, args)).rows[0];

// ---------- header ----------
const pgPkg = JSON.parse(readFileSync(new URL("./node_modules/pg/package.json", import.meta.url)));
log("# rls-bench: Postgres row-level security policy cost");
log(`run started    ${new Date().toISOString()}`);
log(`node           ${process.version}`);
log(`pg (npm)       ${pgPkg.version}`);
log(`version()      ${(await q1(admin, "select version() v")).v}`);
log(`server_version ${(await q1(admin, "show server_version")).server_version}`);
log(`image          ${process.env.RLS_IMAGE_DIGEST ?? "(not given)"}`);
log(`machine        ${process.env.RLS_MACHINE ?? "(not given)"}`);
for (const s of ["shared_buffers", "work_mem", "effective_cache_size", "jit", "jit_above_cost",
  "max_parallel_workers_per_gather", "random_page_cost", "plan_cache_mode"]) {
  log(`setting        ${s} = ${Object.values(await q1(admin, `show ${s}`))[0]}`);
}

// ---------- seed ----------
let ts = performance.now();
await admin.query(`
  create table tenants (id int primary key);
  insert into tenants select generate_series(1, 1000);
  create table documents (
    id bigint primary key,
    tenant_id int not null,
    status text not null,
    email text not null,
    title text not null,
    created_at timestamptz not null,
    email_lower text generated always as (lower(email)) stored
  );
  create table memberships (user_id int, tenant_id int, primary key (user_id, tenant_id));
`);
await admin.query("select setseed($1)", [SEED]);
await admin.query(`
  insert into documents (id, tenant_id, status, email, title, created_at)
  select i, t,
         (array['open','pending','closed','archived','draft'])[1 + floor(r3 * 5)::int],
         'User' || i || '@Tenant' || t || '.Example.com',
         'Document ' || i,
         timestamptz '2026-01-01 00:00:00+00' + (i - 1) * interval '31.536 seconds'
  from (
    select i, r3,
           case when r1 < 0.40 then 1 when r1 < 0.45 then 2 else 3 + floor(r2 * 998)::int end as t
    from (select i, random() as r1, random() as r2, random() as r3
          from generate_series(1, ${ROWS}) i) g
  ) s`);
await admin.query(`create table documents_norls (like documents including all)`);
await admin.query(`insert into documents_norls (id, tenant_id, status, email, title, created_at)
  select id, tenant_id, status, email, title, created_at from documents order by id`);
await admin.query(`
  insert into memberships values (${CONSULTANT}, 1), (${CONSULTANT}, 2), (${SINGLE}, ${SMALL});
  insert into memberships select ${CONSULTANT}, t from generate_series(5, 990, 5) t;
  insert into memberships select u, 3 + (u % 998) from generate_series(3, 20000) u;
  insert into memberships select u, 3 + ((u * 7) % 998) from generate_series(3, 20000) u
    where u % 10 = 0 on conflict do nothing;
  insert into memberships select u, 3 + ((u * 13) % 998) from generate_series(3, 20000) u
    where u % 50 = 0 on conflict do nothing;
`);
await admin.query(`
  alter table tenants owner to app_owner;
  alter table documents owner to app_owner;
  alter table documents_norls owner to app_owner;
  alter table memberships owner to app_owner;
  alter table documents enable row level security;
  alter table documents force row level security;
  grant usage on schema public to app_user;
  grant select, insert, update on documents, documents_norls to app_user;
  grant select on memberships, tenants to app_user;
`);
// Policy helper functions. Each one is a shape people put in policies.
await admin.query(`
  create function app_tenant_sql() returns int language sql stable
    as $$ select nullif(current_setting('app.tenant_id', true), '')::int $$;
  create function app_tenant_sql_ps() returns int language sql stable parallel safe
    as $$ select nullif(current_setting('app.tenant_id', true), '')::int $$;
  create function app_tenant_plpgsql() returns int language plpgsql
    as $$ begin return nullif(current_setting('app.tenant_id', true), '')::int; end $$;
  create function app_tenant_plpgsql_stable() returns int language plpgsql stable parallel safe
    as $$ begin return nullif(current_setting('app.tenant_id', true), '')::int; end $$;
  create function app_tenant_definer() returns int language sql stable security definer
    set search_path = public, pg_temp
    as $$ select nullif(current_setting('app.tenant_id', true), '')::int $$;
  create function app_tenant_matches(tid int) returns boolean language plpgsql stable parallel safe
    as $$ begin return tid = nullif(current_setting('app.tenant_id', true), '')::int; end $$;
  create function app_user_tenants() returns int[] language sql stable security definer
    set search_path = public, pg_temp
    as $$ select array(select m.tenant_id from public.memberships m
                       where m.user_id = nullif(current_setting('app.user_id', true), '')::int) $$;
`);
const FUNCS = ["app_tenant_sql", "app_tenant_sql_ps", "app_tenant_plpgsql", "app_tenant_plpgsql_stable",
  "app_tenant_definer", "app_tenant_matches", "app_user_tenants"];
for (const f of FUNCS) await admin.query(`alter function ${f} owner to app_owner`);
await admin.query("vacuum (analyze) tenants, documents, documents_norls, memberships");
log(`seed built in  ${((performance.now() - ts) / 1000).toFixed(1)} s`);

// seed fingerprint, so run-to-run identity is checkable
const fp = await q1(admin, `
  select count(*) total,
         count(*) filter (where tenant_id = ${WHALE}) whale,
         count(*) filter (where tenant_id = ${MID}) mid,
         count(*) filter (where tenant_id = ${SMALL}) small,
         count(*) filter (where status = 'open') open,
         (select md5(string_agg(id || ':' || tenant_id || ':' || status || ':' || email, ',' order by id))
            from documents where id % 1000 = 0) sample_md5,
         (select count(*) from documents_norls) norls_total
  from documents`);
log(`seed           setseed(${SEED}), ${fp.total} rows (norls copy ${fp.norls_total}), open ${fp.open}`);
log(`tenants        whale t${WHALE} ${fp.whale} rows, mid t${MID} ${fp.mid} rows, small t${SMALL} ${fp.small} rows`);
const others = await q1(admin, `select min(c) mn, max(c) mx, round(avg(c), 1) av from
  (select count(*) c from documents where tenant_id >= 3 group by tenant_id) s`);
log(`tenants 3-1000 ${others.mn} to ${others.mx} rows each, mean ${others.av}`);
log(`sample md5     ${fp.sample_md5}`);
const mem = await q1(admin, `select count(*) n,
  (select count(*) from memberships where user_id = ${CONSULTANT}) c_tenants,
  (select count(*) from documents where tenant_id in (select tenant_id from memberships where user_id = ${CONSULTANT})) c_rows,
  (select count(*) from documents where tenant_id in (select tenant_id from memberships where user_id = ${SINGLE})) s_rows
  from memberships`);
log(`memberships    ${mem.n} rows; consultant u${CONSULTANT} in ${mem.c_tenants} tenants (${mem.c_rows} visible rows); single-tenant u${SINGLE} in t${SMALL} (${mem.s_rows} rows)`);
const sizes = await admin.query(`select c.relname, pg_relation_size(c.oid) b from pg_class c
  where c.relname in ('documents','documents_norls','memberships','documents_pkey','memberships_pkey') order by 1`);
for (const r of sizes.rows) log(`size           ${r.relname} ${r.b} bytes`);

// values the queries use, picked from the data
const pick = async (t) => q1(admin, `select id, email from documents where tenant_id = $1 order by id
  offset (select count(*) / 2 from documents where tenant_id = $1) limit 1`, [t]);
const P = { [WHALE]: await pick(WHALE), [MID]: await pick(MID), [SMALL]: await pick(SMALL) };
for (const t of [WHALE, MID, SMALL]) log(`pick           t${t} id ${P[t].id} email ${P[t].email}`);
const upd = await q1(admin, `select min(id) lo, max(id) hi from (select id from documents where tenant_id = ${MID}
  order by id offset 20000 limit 10000) s`);
log(`update range   t${MID} ids ${upd.lo} to ${upd.hi} (10000 rows of that tenant)`);

// ---------- app connection ----------
const app = new pg.Client({ host, port, user: "app_user", password: APP_PW, database: "rlsbench" });
await app.connect();
log(`app session    current_user = ${(await q1(app, "select current_user u")).u}, track_functions = ${(await q1(app, "show track_functions")).track_functions}`);

// ---------- catalog (T5c and the function table) ----------
log("");
log("## T5c catalog: leakproof and function attributes (pg_proc)");
const cat = await admin.query(`
  select p.oid::regprocedure::text sig, p.provolatile vol, p.proparallel par, p.proleakproof leak,
         p.prosecdef secdef, p.procost cost, l.lanname lang, coalesce(array_to_string(p.proconfig, ','), '') config
  from pg_proc p join pg_language l on l.oid = p.prolang
  where p.oid in ('lower(text)'::regprocedure, 'texteq(text,text)'::regprocedure, 'textlike(text,text)'::regprocedure,
                  'texticlike(text,text)'::regprocedure, 'int4eq(int4,int4)'::regprocedure,
                  'current_setting(text,boolean)'::regprocedure, 'int4in(cstring)'::regprocedure,
                  'textout(text)'::regprocedure, 'array_eq(anyarray,anyarray)'::regprocedure)
     or (p.proname = any($1) and p.pronamespace = 'public'::regnamespace)
  order by l.lanname = 'internal' desc, 1`, [FUNCS]);
log("function | provolatile | proparallel | proleakproof | prosecdef | procost | language | proconfig");
for (const r of cat.rows) log(`${r.sig} | ${r.vol} | ${r.par} | ${r.leak} | ${r.secdef} | ${r.cost} | ${r.lang} | ${r.config}`);
const LEAK_SQL = `select count(*) filter (where not p.proleakproof) as not_leakproof, count(*) as total
from pg_proc p
where p.oid in (select o.oprcode from pg_operator o where o.oprresult = 'boolean'::regtype)`;
const lk = await q1(admin, LEAK_SQL);
log(`boolean-returning operator functions: ${lk.not_leakproof} of ${lk.total} not leakproof`);
log(`query: ${LEAK_SQL.replace(/\n/g, " ")}`);

// ---------- helpers ----------
const ID = (t) => P[t].id;
async function inTx(c, ctx, fn) {
  await c.query("BEGIN");
  try {
    await c.query(`SET LOCAL statement_timeout = '${TIMEOUT}'`);
    await c.query("select set_config('app.tenant_id', $1, true), set_config('app.user_id', $2, true)",
      [ctx.tenant == null ? "" : String(ctx.tenant), ctx.user == null ? "" : String(ctx.user)]);
    return await fn();
  } finally {
    await c.query("ROLLBACK");
  }
}
const digest = (sql) => `select count(*)::int n, md5(coalesce(string_agg(id::text, ',' order by id), '')) h from (${sql}) s`;
async function result(c, ctx, kind, sql) {
  return inTx(c, ctx, async () => {
    if (kind === "count") return `count ${(await c.query(sql)).rows[0].count}`;
    if (kind === "write") return `${(await c.query(sql)).rowCount} rows written`;
    if (kind === "ordered") {
      const rows = (await c.query(sql)).rows; const ids = rows.map((r) => r.id).join(",");
      return `${rows.length} ids in order md5 ${(await c.query("select md5($1) h", [ids])).rows[0].h.slice(0, 12)}`;
    }
    const r = (await c.query(digest(sql))).rows[0];
    return `${r.n} rows md5 ${r.h.slice(0, 12)}`;
  });
}
const baselines = new Map();
async function baseline(key, kind, sql) {
  if (!baselines.has(key)) baselines.set(key, await result(app, {}, kind, sql));
  return baselines.get(key);
}
function walk(node, f, parentRel = null) {
  f(node, parentRel);
  for (const ch of node.Plans ?? []) walk(ch, f, ch["Parent Relationship"]);
}
function summarize(plan) {
  const root = plan.Plan;
  let scan = null; const subs = []; let workers = null;
  walk(root, (n) => {
    if (!scan && n["Node Type"] !== "ModifyTable" && (n["Relation Name"] === "documents" || n["Relation Name"] === "documents_norls")) scan = n;
    if (n["Subplan Name"]) subs.push(`${n["Subplan Name"]} loops ${n["Actual Loops"]}`);
    if (n["Workers Planned"] != null && workers == null) workers = `${n["Workers Planned"]}/${n["Workers Launched"] ?? 0}`;
  });
  const s = {};
  s.top = root["Node Type"];
  if (scan) {
    s.scan = `${scan["Node Type"]}${scan["Index Name"] ? " " + scan["Index Name"] : ""}`;
    s.cond = [scan["Index Cond"] ? "Index Cond" : null, scan["Recheck Cond"] ? "Recheck Cond" : null,
      scan["Filter"] ? "Filter" : null].filter(Boolean).join(" + ") || "no cond";
    s.est = scan["Plan Rows"];
    s.act = `${scan["Actual Rows"]}x${scan["Actual Loops"]}`;
    s.removed = scan["Rows Removed by Filter"] != null ? `${scan["Rows Removed by Filter"]}x${scan["Actual Loops"]}` : "0";
    if (scan["Heap Fetches"] != null) s.heap = scan["Heap Fetches"];
    if (scan["Index Searches"] != null) s.searches = scan["Index Searches"];
    if (scan["Exact Heap Blocks"] != null) s.bitmap = `exact ${scan["Exact Heap Blocks"]} lossy ${scan["Lossy Heap Blocks"]}`;
  }
  s.subs = subs.join(", ");
  s.workers = workers ?? "none";
  s.hit = root["Shared Hit Blocks"]; s.read = root["Shared Read Blocks"];
  s.jit = plan.JIT ? `JIT ${plan.JIT.Functions} fns` : "";
  return s;
}
function verboseConds(plan) {
  const parts = [];
  walk(plan.Plan, (n, rel) => {
    for (const k of ["Index Cond", "Recheck Cond", "Filter", "One-Time Filter", "Join Filter", "Hash Cond"]) {
      if (n[k]) parts.push(`${n["Subplan Name"] ? n["Subplan Name"] + " " : ""}${n["Node Type"]} ${k}: ${n[k]}`);
    }
  });
  return parts;
}
const ms = (x) => x.toFixed(3);
const nearest = (sorted, p) => sorted[Math.max(0, Math.ceil(p * sorted.length) - 1)];
let lastPolicy = null;

async function setPolicy(using, check = using) {
  await admin.query("drop policy if exists p on documents");
  if (using == null) return;
  await admin.query(`create policy p on documents for all to app_user using (${using}) with check (${check})`);
  const r = await q1(admin, "select qual, with_check from pg_policies where tablename = 'documents' and policyname = 'p'");
  lastPolicy = r.qual;
  log(`policy: USING ${r.qual}${r.with_check !== r.qual ? " WITH CHECK " + r.with_check : ""}`);
}
async function setIndexes(list) {
  for (const t of ["documents", "documents_norls"]) {
    const ix = await admin.query(`select indexrelid::regclass::text n from pg_index where indrelid = '${t}'::regclass and not indisprimary`);
    for (const r of ix.rows) await admin.query(`drop index ${r.n}`);
  }
  const names = [];
  for (const [name, cols] of list) {
    const s = performance.now();
    await admin.query(`create index ${name} on documents ${cols}`);
    const built = performance.now() - s;
    await admin.query(`create index ${name}_norls on documents_norls ${cols}`);
    names.push([name, cols, built]);
  }
  await admin.query("vacuum (analyze) documents, documents_norls");
  log(`indexes: ${list.length ? "" : "primary key only"}`);
  for (const [name, cols, built] of names) {
    const b = (await q1(admin, `select pg_relation_size('${name}') b`)).b;
    log(`  ${name} ON documents ${cols}: ${b} bytes, built in ${ms(built)} ms (same index on documents_norls)`);
  }
}
async function vacuumTables() { await admin.query("vacuum documents, documents_norls"); }

async function funcCalls(c, ctx, sql) {
  // flush this backend's pending stats from earlier cells before resetting the counters
  await c.query("select pg_stat_force_next_flush()");
  await c.query("select 1");
  await admin.query(`select pg_stat_reset_single_function_counters(p.oid) from pg_proc p
    where p.proname = any($1) and p.pronamespace = 'public'::regnamespace`, [FUNCS]);
  await inTx(c, ctx, () => c.query(sql));
  await c.query("select pg_stat_force_next_flush()");
  await admin.query("select pg_stat_clear_snapshot()");
  const r = await admin.query("select funcname, calls from pg_stat_user_functions where calls > 0 order by funcname");
  return r.rows.length ? r.rows.map((x) => `${x.funcname}=${x.calls}`).join(",") : "0";
}

async function cell(o) {
  // o: block, label, state, who, ctx, sql, kind, base: [key, sql], write (vacuum before each run), trace
  const c = app; const ctx = o.ctx ?? {};
  const before = o.write ? vacuumTables : async () => {};
  const rec = { block: o.block, label: o.label, state: o.state, who: o.who, sql: o.sql };
  try {
    const expect = await baseline(o.base[0], o.kind, o.base[1]);
    await before();
    const calls = o.write ? "n/a" : await funcCalls(c, ctx, o.sql);
    await before();
    const got = await result(c, ctx, o.kind, o.sql);
    rec.match = got === expect ? "match" : `MISMATCH got ${got} expected ${expect}`;
    rec.result = got; rec.calls = calls;
    const exp = `EXPLAIN (ANALYZE, BUFFERS, TIMING OFF, FORMAT JSON) ${o.sql}`;
    const runOnce = async () => { await before(); return inTx(c, ctx, async () => (await c.query(exp)).rows[0]["QUERY PLAN"][0]); };
    let first = null;
    for (let i = 0; i < WARMUPS; i++) { const p = await runOnce(); if (i === 0) first = p["Execution Time"]; }
    const N = first < FAST_MS ? N_FAST : N_SLOW;
    const times = [], plans = []; let plan = null;
    for (let i = 0; i < N; i++) { plan = await runOnce(); times.push(plan["Execution Time"]); plans.push(plan["Planning Time"]); }
    times.sort((a, b) => a - b); plans.sort((a, b) => a - b);
    rec.N = N; rec.median = nearest(times, 0.5); rec.p95 = nearest(times, 0.95);
    rec.min = times[0]; rec.max = times[N - 1]; rec.planMedian = nearest(plans, 0.5);
    rec.s = summarize(plan);
    const vplan = await inTx(c, ctx, async () => (await c.query(`EXPLAIN (VERBOSE, COSTS OFF, FORMAT JSON) ${o.sql}`)).rows[0]["QUERY PLAN"][0]);
    rec.verbose = verboseConds(vplan);
    if (o.trace) {
      await before();
      rec.trace = await inTx(c, ctx, async () => (await c.query(`EXPLAIN (ANALYZE, BUFFERS) ${o.sql}`)).rows.map((r) => r["QUERY PLAN"]));
    }
  } catch (e) {
    if (e.code === "57014") { rec.timeout = true; rec.match = "timeout"; } else throw e;
  }
  cells.push(rec);
  const s = rec.s ?? {};
  if (rec.timeout) {
    log(`${o.block} | ${o.label} | ${o.state} | ${o.who} | timeout (statement_timeout ${TIMEOUT})`);
  } else {
    log(`${o.block} | ${o.label} | ${o.state} | ${o.who} | ${s.top}; ${s.scan ?? "?"}; ${s.cond ?? ""}${s.subs ? "; " + s.subs : ""}` +
      ` | udf calls ${rec.calls} | est ${s.est} act ${s.act} removed ${s.removed}` +
      `${s.heap != null ? " heap fetches " + s.heap : ""}${s.searches != null ? " index searches " + s.searches : ""}` +
      ` | hit ${s.hit} read ${s.read} | workers ${s.workers}${s.jit ? " | " + s.jit : ""}` +
      ` | median ${ms(rec.median)} ms p95 ${ms(rec.p95)} ms (N=${rec.N}) plan ${ms(rec.planMedian)} ms | ${rec.result} | ${rec.match}`);
    for (const v of rec.verbose) log(`    ${v}`);
    if (rec.trace) { log("    --- EXPLAIN (ANALYZE, BUFFERS) ---"); for (const l of rec.trace) log(`    ${l}`); log("    ---"); }
  }
  return rec;
}
const blockTime = {};
const startBlock = (b, title) => { blockTime[b] = performance.now(); log(""); log(`## ${b} ${title}`); };
const endBlock = (b) => log(`(${b} took ${((performance.now() - blockTime[b]) / 1000).toFixed(1)} s)`);

const DIRECT = "tenant_id = nullif(current_setting('app.tenant_id', true), '')::int";
const WRAPPED = "tenant_id = (select nullif(current_setting('app.tenant_id', true), '')::int)";
const TENANTS = [[WHALE, "whale"], [MID, "mid"], [SMALL, "small"]];
const who = (t, n) => `${n} t${t}`;

// Queries. tbl is documents or documents_norls; w is an extra WHERE for the tenant (or "").
const Q = {
  Q1: { kind: "ordered", name: "Q1 latest 20", sql: (tbl, w) => `select id from ${tbl}${w ? " where " + w : ""} order by created_at desc limit 20` },
  Q2: { kind: "count", name: "Q2 count", sql: (tbl, w) => `select count(*) from ${tbl}${w ? " where " + w : ""}` },
  Q3: { kind: "rows", name: "Q3 lookup by id", sql: (tbl, w, t) => `select id, title from ${tbl} where id = ${ID(t)}${w ? " and " + w : ""}` },
  Q4: { kind: "rows", name: "Q4 open since Dec 1", sql: (tbl, w) => `select id, title from ${tbl} where ${w ? w + " and " : ""}status = 'open' and created_at >= '2026-12-01 00:00:00+00'` },
};
const baseOf = (qk, t) => [`${qk}:t${t}`, Q[qk].sql("documents_norls", `tenant_id = ${t}`, t)];

// ---------- T1: RLS vs explicit WHERE ----------
startBlock("T1", "RLS policy vs explicit WHERE, index (tenant_id, created_at)");
await setIndexes([["documents_tenant_created", "(tenant_id, created_at)"]]);
await setPolicy(DIRECT);
for (const qk of ["Q1", "Q2", "Q3", "Q4"]) {
  for (const [t, n] of TENANTS) {
    const base = baseOf(qk, t);
    await cell({ block: "T1", label: `${Q[qk].name}, no RLS + WHERE`, state: "tenant_created", who: who(t, n), sql: base[1], kind: Q[qk].kind, base });
    await cell({ block: "T1", label: `${Q[qk].name}, RLS policy only`, state: "tenant_created", who: who(t, n), ctx: { tenant: t }, sql: Q[qk].sql("documents", "", t), kind: Q[qk].kind, base });
    await cell({ block: "T1", label: `${Q[qk].name}, RLS policy + same WHERE`, state: "tenant_created", who: who(t, n), ctx: { tenant: t }, sql: Q[qk].sql("documents", `tenant_id = ${t}`, t), kind: Q[qk].kind, base });
  }
}
endBlock("T1");

// ---------- T2: policy expression and function attributes ----------
startBlock("T2", "policy expression and function attributes, Q2 count");
const T2 = [
  ["direct current_setting()", DIRECT],
  ["current_setting() wrapped in (select)", WRAPPED],
  ["SQL STABLE function", "tenant_id = app_tenant_sql()"],
  ["SQL STABLE function wrapped", "tenant_id = (select app_tenant_sql())"],
  ["SQL STABLE PARALLEL SAFE function", "tenant_id = app_tenant_sql_ps()"],
  ["plpgsql default (VOLATILE, PARALLEL UNSAFE)", "tenant_id = app_tenant_plpgsql()"],
  ["plpgsql default wrapped", "tenant_id = (select app_tenant_plpgsql())"],
  ["plpgsql STABLE PARALLEL SAFE", "tenant_id = app_tenant_plpgsql_stable()"],
  ["SQL SECURITY DEFINER", "tenant_id = app_tenant_definer()"],
  ["SQL SECURITY DEFINER wrapped", "tenant_id = (select app_tenant_definer())"],
  ["plpgsql STABLE taking tenant_id (row data)", "app_tenant_matches(tenant_id)"],
];
for (const [state, idx, tenants] of [
  ["no tenant index", [], [[SMALL, "small"]]],
  ["index (tenant_id)", [["documents_tenant", "(tenant_id)"]], [[WHALE, "whale"], [SMALL, "small"]]],
]) {
  await setIndexes(idx);
  await setPolicy(null);
  for (const [t, n] of tenants) {
    const base = baseOf("Q2", t);
    await cell({ block: "T2", label: "no RLS + WHERE", state, who: who(t, n), sql: base[1], kind: "count", base, trace: state === "no tenant index" });
  }
  for (const [label, expr] of T2) {
    await setPolicy(expr);
    for (const [t, n] of tenants) {
      const trace = state === "no tenant index" && (label.startsWith("plpgsql default") || label.startsWith("direct") || label === "current_setting() wrapped in (select)");
      await cell({ block: "T2", label, state, who: who(t, n), ctx: { tenant: t }, sql: Q.Q2.sql("documents", ""), kind: "count", base: baseOf("Q2", t), trace });
    }
  }
}
endBlock("T2");

// ---------- T3: index shape under a direct policy ----------
startBlock("T3", "index shape under the direct policy, Q1 and Q4");
await setPolicy(DIRECT);
for (const [state, idx] of [
  ["index (created_at)", [["documents_created", "(created_at)"]]],
  ["index (tenant_id)", [["documents_tenant", "(tenant_id)"]]],
  ["index (tenant_id, created_at)", [["documents_tenant_created", "(tenant_id, created_at)"]]],
]) {
  await setIndexes(idx);
  for (const qk of ["Q1", "Q4"]) for (const [t, n] of TENANTS) {
    await cell({ block: "T3", label: `${Q[qk].name}, RLS policy only`, state, who: who(t, n), ctx: { tenant: t }, sql: Q[qk].sql("documents", "", t), kind: Q[qk].kind, base: baseOf(qk, t) });
  }
}
endBlock("T3");

// ---------- T4: membership policies ----------
startBlock("T4", "membership-table policies, index (tenant_id, created_at)");
await setIndexes([["documents_tenant_created", "(tenant_id, created_at)"]]);
const UID = "nullif(current_setting('app.user_id', true), '')::int";
const T4 = [
  ["IN subquery", `tenant_id in (select m.tenant_id from memberships m where m.user_id = ${UID})`],
  ["EXISTS correlated", `exists (select 1 from memberships m where m.tenant_id = documents.tenant_id and m.user_id = ${UID})`],
  ["= ANY(array(select))", `tenant_id = any (array(select m.tenant_id from memberships m where m.user_id = ${UID}))`],
  ["SECURITY DEFINER int[] function", "tenant_id = any (app_user_tenants())"],
  ["SECURITY DEFINER int[] function wrapped", "tenant_id = any ((select app_user_tenants())::int[])"],
];
const USERS = [[CONSULTANT, "consultant u1 (200 tenants)"], [SINGLE, "single-tenant u2"]];
const memBase = (qk, u) => [`${qk}:u${u}`, Q[qk].sql("documents_norls", `tenant_id in (select tenant_id from memberships where user_id = ${u})`)];
for (const [label, expr] of T4) {
  await setPolicy(expr);
  for (const qk of ["Q1", "Q2"]) for (const [u, n] of USERS) {
    await cell({ block: "T4", label: `${Q[qk].name}, ${label}`, state: "tenant_created", who: n, ctx: { user: u }, sql: Q[qk].sql("documents", ""), kind: Q[qk].kind, base: memBase(qk, u) });
  }
}
endBlock("T4");

// ---------- T5: non-leakproof user filter ----------
startBlock("T5", "user filter with a non-leakproof function, direct policy");
await setPolicy(DIRECT);
const lowerOf = (t) => P[t].email.toLowerCase();
const Q5 = (tbl, w, t) => `select id from ${tbl} where ${w ? w + " and " : ""}lower(email) = '${lowerOf(t)}'`;
const Q6 = (tbl, w, t) => `select id from ${tbl} where ${w ? w + " and " : ""}email = '${P[t].email}'`;
const Q5b = (tbl, w, t) => `select id from ${tbl} where ${w ? w + " and " : ""}email_lower = '${lowerOf(t)}'`;
for (const [state, idx] of [
  ["indexes (lower(email)), (email), (email_lower)", [["documents_lower_email", "(lower(email))"], ["documents_email", "(email)"], ["documents_email_lower", "(email_lower)"]]],
  ["indexes (tenant_id, lower(email)), (tenant_id, email), (tenant_id, email_lower)", [["documents_tenant_lower_email", "(tenant_id, lower(email))"], ["documents_tenant_email", "(tenant_id, email)"], ["documents_tenant_email_lower", "(tenant_id, email_lower)"]]],
]) {
  await setIndexes(idx);
  for (const [qn, qf] of [["Q5 lower(email) = value", Q5], ["Q6 email = value", Q6], ["Q5b email_lower (stored generated column) = value", Q5b]]) for (const [t, n] of [[WHALE, "whale"], [SMALL, "small"]]) {
    const base = [`${qn}:t${t}`, qf("documents_norls", `tenant_id = ${t}`, t)];
    const trace = t === WHALE && qn.startsWith("Q5");
    await cell({ block: "T5", label: `${qn}, no RLS + WHERE`, state, who: who(t, n), sql: base[1], kind: "rows", base, trace });
    await cell({ block: "T5", label: `${qn}, RLS policy only`, state, who: who(t, n), ctx: { tenant: t }, sql: qf("documents", "", t), kind: "rows", base, trace });
  }
}
endBlock("T5");

// ---------- T6: count(*) and index-only scans ----------
startBlock("T6", "count(*) where status = 'open', index-only scans");
const Q7 = (tbl, w) => `select count(*) from ${tbl} where ${w ? w + " and " : ""}status = 'open'`;
for (const [state, idx] of [
  ["index (status)", [["documents_status", "(status)"]]],
  ["index (tenant_id, status)", [["documents_tenant_status", "(tenant_id, status)"]]],
]) {
  await setIndexes(idx);
  for (const [t, n] of [[WHALE, "whale"], [SMALL, "small"]]) {
    const base = [`Q7:t${t}`, Q7("documents_norls", `tenant_id = ${t}`)];
    await cell({ block: "T6", label: "Q7 count open, no RLS + WHERE", state, who: who(t, n), sql: base[1], kind: "count", base });
    await cell({ block: "T6", label: "Q7 count open, RLS policy only", state, who: who(t, n), ctx: { tenant: t }, sql: Q7("documents", ""), kind: "count", base });
  }
}
endBlock("T6");

// ---------- T7: writes under WITH CHECK ----------
startBlock("T7", "writes under WITH CHECK, tenant mid t2, index (tenant_id, created_at); every execution rolled back, VACUUM before each");
await setIndexes([["documents_tenant_created", "(tenant_id, created_at)"]]);
const W1 = (tbl) => `insert into ${tbl} (id, tenant_id, status, email, title, created_at)
  select 2000000 + g, ${MID}, 'open', 'Bulk' || g || '@Tenant${MID}.Example.com', 'Bulk ' || g,
         timestamptz '2026-12-31 00:00:00+00' + g * interval '1 second'
  from generate_series(1, 10000) g`;
const W2 = (tbl) => `update ${tbl} set title = title || ' edited' where tenant_id = ${MID} and id between ${upd.lo} and ${upd.hi}`;
const T7 = [
  ["no RLS", null, "documents_norls", { tenant: MID }],
  ["simple tenant policy", DIRECT, "documents", { tenant: MID }],
  ["membership IN subquery", `tenant_id in (select m.tenant_id from memberships m where m.user_id = ${UID})`, "documents", { user: CONSULTANT }],
  ["SECURITY DEFINER int[] function wrapped", "tenant_id = any ((select app_user_tenants())::int[])", "documents", { user: CONSULTANT }],
];
for (const [label, expr, tbl, ctx] of T7) {
  await setPolicy(expr);
  if (expr == null) log("policy: none (documents_norls has no RLS)");
  for (const [wn, wf] of [["W1 insert 10000 rows", W1], ["W2 update 10000 rows", W2]]) {
    await cell({ block: "T7", label: `${wn}, ${label}`, state: "tenant_created", who: ctx.user ? "consultant u1, writing t2" : "mid t2", ctx, sql: wf(tbl), kind: "write", base: [`${wn}`, wf("documents_norls")], write: true });
  }
}
endBlock("T7");

await setPolicy(null);
const total = (performance.now() - t0) / 1000;
log("");
const mism = cells.filter((c) => c.match.startsWith("MISMATCH")).length;
const tmo = cells.filter((c) => c.timeout).length;
log(`cells ${cells.length}, mismatches ${mism}, timeouts ${tmo}`);
log(`run finished   ${new Date().toISOString()}, total ${total.toFixed(1)} s`);
await app.end(); await admin.end();
if (process.env.RLS_JSON) writeFileSync(process.env.RLS_JSON, JSON.stringify(cells, null, 1));
# rls-bench: Postgres row-level security policy cost
run started    2026-11-13T07:19:21.552Z
node           v24.20.0
pg (npm)       8.23.1
version()      PostgreSQL 18.7 (Debian 18.7-1.pgdg13+2) on aarch64-unknown-linux-gnu, compiled by gcc (Debian 14.2.0-19) 14.2.0, 64-bit
server_version 18.7 (Debian 18.7-1.pgdg13+2)
image          postgres@sha256:b9f6b8ff03b62f3cfd9d9ba3fe56226a9991c79d3fb46fd46536263bf02be553
machine        Apple M1 Max, 10 cores, 64 GB RAM, macOS 27.2.1; Docker Desktop 4.90.0 (238679) engine 29.7.2, VM 10 CPUs, 15690960896 bytes
setting        shared_buffers = 128MB
setting        work_mem = 4MB
setting        effective_cache_size = 4GB
setting        jit = on
setting        jit_above_cost = 100000
setting        max_parallel_workers_per_gather = 2
setting        random_page_cost = 4
setting        plan_cache_mode = auto
seed built in  4.9 s
seed           setseed(0.20261113), 1000000 rows (norls copy 1000000), open 199744
tenants        whale t1 399015 rows, mid t2 49802 rows, small t7 544 rows
tenants 3-1000 479 to 631 rows each, mean 552.3
sample md5     e414e86e816ddb8f47535bb132184d0c
memberships    22595 rows; consultant u1 in 200 tenants (558217 visible rows); single-tenant u2 in t7 (544 rows)
size           documents 144105472 bytes
size           documents_norls 144105472 bytes
size           documents_pkey 22487040 bytes
size           memberships 819200 bytes
size           memberships_pkey 917504 bytes
pick           t1 id 500025 email User500025@Tenant1.Example.com
pick           t2 id 500591 email User500591@Tenant2.Example.com
pick           t7 id 485243 email User485243@Tenant7.Example.com
update range   t2 ids 401213 to 603024 (10000 rows of that tenant)
app session    current_user = app_user, track_functions = all

## T5c catalog: leakproof and function attributes (pg_proc)
function | provolatile | proparallel | proleakproof | prosecdef | procost | language | proconfig
array_eq(anyarray,anyarray) | i | s | false | false | 1 | internal | 
current_setting(text,boolean) | s | s | false | false | 1 | internal | 
int4eq(integer,integer) | i | s | true | false | 1 | internal | 
int4in(cstring) | i | s | false | false | 1 | internal | 
lower(text) | i | s | false | false | 1 | internal | 
texteq(text,text) | i | s | true | false | 1 | internal | 
texticlike(text,text) | i | s | false | false | 1 | internal | 
textlike(text,text) | i | s | false | false | 1 | internal | 
textout(text) | i | s | false | false | 1 | internal | 
app_tenant_definer() | s | u | false | true | 100 | sql | search_path=public, pg_temp
app_tenant_matches(integer) | s | s | false | false | 100 | plpgsql | 
app_tenant_plpgsql() | v | u | false | false | 100 | plpgsql | 
app_tenant_plpgsql_stable() | s | s | false | false | 100 | plpgsql | 
app_tenant_sql() | s | u | false | false | 100 | sql | 
app_tenant_sql_ps() | s | s | false | false | 100 | sql | 
app_user_tenants() | s | u | false | true | 100 | sql | search_path=public, pg_temp
boolean-returning operator functions: 264 of 524 not leakproof
query: select count(*) filter (where not p.proleakproof) as not_leakproof, count(*) as total from pg_proc p where p.oid in (select o.oprcode from pg_operator o where o.oprresult = 'boolean'::regtype)

## T1 RLS policy vs explicit WHERE, index (tenant_id, created_at)
indexes: 
  documents_tenant_created ON documents (tenant_id, created_at): 31563776 bytes, built in 327.326 ms (same index on documents_norls)
policy: USING (tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
T1 | Q1 latest 20, no RLS + WHERE | tenant_created | whale t1 | Limit; Index Scan documents_tenant_created_norls; Index Cond | udf calls 0 | est 403200 act 20x1 removed 0 index searches 1 | hit 5 read 0 | workers none | median 0.015 ms p95 0.021 ms (N=21) plan 0.023 ms | 20 ids in order md5 e71393c3c9dc | match
    Index Scan Index Cond: (documents_norls.tenant_id = 1)
T1 | Q1 latest 20, RLS policy only | tenant_created | whale t1 | Limit; Index Scan documents_tenant_created; Index Cond | udf calls 0 | est 397967 act 20x1 removed 0 index searches 1 | hit 5 read 0 | workers none | median 0.014 ms p95 0.019 ms (N=21) plan 0.024 ms | 20 ids in order md5 e71393c3c9dc | match
    Index Scan Index Cond: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
T1 | Q1 latest 20, RLS policy + same WHERE | tenant_created | whale t1 | Limit; Index Scan documents_tenant_created; Index Cond | udf calls 0 | est 397967 act 20x1 removed 0 index searches 1 | hit 5 read 0 | workers none | median 0.014 ms p95 0.019 ms (N=21) plan 0.020 ms | 20 ids in order md5 e71393c3c9dc | match
    Result One-Time Filter: ((NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer = 1)
    Index Scan Index Cond: (documents.tenant_id = 1)
T1 | Q1 latest 20, no RLS + WHERE | tenant_created | mid t2 | Limit; Index Scan documents_tenant_created_norls; Index Cond | udf calls 0 | est 50500 act 20x1 removed 0 index searches 1 | hit 10 read 0 | workers none | median 0.016 ms p95 0.026 ms (N=21) plan 0.019 ms | 20 ids in order md5 80fa8d5e2b13 | match
    Index Scan Index Cond: (documents_norls.tenant_id = 2)
T1 | Q1 latest 20, RLS policy only | tenant_created | mid t2 | Limit; Index Scan documents_tenant_created; Index Cond | udf calls 0 | est 51800 act 20x1 removed 0 index searches 1 | hit 10 read 0 | workers none | median 0.014 ms p95 0.023 ms (N=21) plan 0.023 ms | 20 ids in order md5 80fa8d5e2b13 | match
    Index Scan Index Cond: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
T1 | Q1 latest 20, RLS policy + same WHERE | tenant_created | mid t2 | Limit; Index Scan documents_tenant_created; Index Cond | udf calls 0 | est 51800 act 20x1 removed 0 index searches 1 | hit 10 read 0 | workers none | median 0.015 ms p95 0.021 ms (N=21) plan 0.020 ms | 20 ids in order md5 80fa8d5e2b13 | match
    Result One-Time Filter: ((NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer = 2)
    Index Scan Index Cond: (documents.tenant_id = 2)
T1 | Q1 latest 20, no RLS + WHERE | tenant_created | small t7 | Limit; Index Scan documents_tenant_created_norls; Index Cond | udf calls 0 | est 543 act 20x1 removed 0 index searches 1 | hit 23 read 0 | workers none | median 0.016 ms p95 0.018 ms (N=21) plan 0.017 ms | 20 ids in order md5 e07f44460e37 | match
    Index Scan Index Cond: (documents_norls.tenant_id = 7)
T1 | Q1 latest 20, RLS policy only | tenant_created | small t7 | Limit; Index Scan documents_tenant_created; Index Cond | udf calls 0 | est 550 act 20x1 removed 0 index searches 1 | hit 23 read 0 | workers none | median 0.016 ms p95 0.033 ms (N=21) plan 0.024 ms | 20 ids in order md5 e07f44460e37 | match
    Index Scan Index Cond: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
T1 | Q1 latest 20, RLS policy + same WHERE | tenant_created | small t7 | Limit; Index Scan documents_tenant_created; Index Cond | udf calls 0 | est 550 act 20x1 removed 0 index searches 1 | hit 23 read 0 | workers none | median 0.033 ms p95 0.042 ms (N=21) plan 0.037 ms | 20 ids in order md5 e07f44460e37 | match
    Result One-Time Filter: ((NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer = 7)
    Index Scan Index Cond: (documents.tenant_id = 7)
T1 | Q2 count, no RLS + WHERE | tenant_created | whale t1 | Aggregate; Index Only Scan documents_tenant_created_norls; Index Cond | udf calls 0 | est 168000 act 133005x3 removed 0 heap fetches 0 index searches 1 | hit 1535 read 0 | workers 2/2 | median 14.479 ms p95 15.856 ms (N=21) plan 0.045 ms | count 399015 | match
    Index Only Scan Index Cond: (documents_norls.tenant_id = 1)
T1 | Q2 count, RLS policy only | tenant_created | whale t1 | Aggregate; Index Only Scan documents_tenant_created; Index Cond | udf calls 0 | est 165820 act 133005x3 removed 0 heap fetches 0 index searches 1 | hit 1535 read 0 | workers 2/2 | median 13.374 ms p95 14.227 ms (N=21) plan 0.051 ms | count 399015 | match
    Index Only Scan Index Cond: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
T1 | Q2 count, RLS policy + same WHERE | tenant_created | whale t1 | Aggregate; Index Only Scan documents_tenant_created; Index Cond | udf calls 0 | est 165820 act 133005x3 removed 0 heap fetches 0 index searches 1 | hit 1535 read 0 | workers 2/2 | median 17.099 ms p95 17.718 ms (N=21) plan 0.039 ms | count 399015 | match
    Result One-Time Filter: ((NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer = 1)
    Index Only Scan Index Cond: (documents.tenant_id = 1)
T1 | Q2 count, no RLS + WHERE | tenant_created | mid t2 | Aggregate; Index Only Scan documents_tenant_created_norls; Index Cond | udf calls 0 | est 50500 act 49802x1 removed 0 heap fetches 0 index searches 1 | hit 195 read 0 | workers none | median 3.124 ms p95 3.422 ms (N=21) plan 0.019 ms | count 49802 | match
    Index Only Scan Index Cond: (documents_norls.tenant_id = 2)
T1 | Q2 count, RLS policy only | tenant_created | mid t2 | Aggregate; Index Only Scan documents_tenant_created; Index Cond | udf calls 0 | est 51800 act 49802x1 removed 0 heap fetches 0 index searches 1 | hit 195 read 0 | workers none | median 2.945 ms p95 3.463 ms (N=21) plan 0.027 ms | count 49802 | match
    Index Only Scan Index Cond: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
T1 | Q2 count, RLS policy + same WHERE | tenant_created | mid t2 | Aggregate; Index Only Scan documents_tenant_created; Index Cond | udf calls 0 | est 51800 act 49802x1 removed 0 heap fetches 0 index searches 1 | hit 195 read 0 | workers none | median 4.839 ms p95 5.063 ms (N=21) plan 0.029 ms | count 49802 | match
    Result One-Time Filter: ((NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer = 2)
    Index Only Scan Index Cond: (documents.tenant_id = 2)
T1 | Q2 count, no RLS + WHERE | tenant_created | small t7 | Aggregate; Index Only Scan documents_tenant_created_norls; Index Cond | udf calls 0 | est 543 act 544x1 removed 0 heap fetches 0 index searches 1 | hit 6 read 0 | workers none | median 0.042 ms p95 0.047 ms (N=21) plan 0.015 ms | count 544 | match
    Index Only Scan Index Cond: (documents_norls.tenant_id = 7)
T1 | Q2 count, RLS policy only | tenant_created | small t7 | Aggregate; Index Only Scan documents_tenant_created; Index Cond | udf calls 0 | est 550 act 544x1 removed 0 heap fetches 0 index searches 1 | hit 6 read 0 | workers none | median 0.042 ms p95 0.054 ms (N=21) plan 0.021 ms | count 544 | match
    Index Only Scan Index Cond: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
T1 | Q2 count, RLS policy + same WHERE | tenant_created | small t7 | Aggregate; Index Only Scan documents_tenant_created; Index Cond | udf calls 0 | est 550 act 544x1 removed 0 heap fetches 0 index searches 1 | hit 6 read 0 | workers none | median 0.062 ms p95 0.075 ms (N=21) plan 0.019 ms | count 544 | match
    Result One-Time Filter: ((NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer = 7)
    Index Only Scan Index Cond: (documents.tenant_id = 7)
T1 | Q3 lookup by id, no RLS + WHERE | tenant_created | whale t1 | Index Scan; Index Scan documents_norls_pkey; Index Cond + Filter | udf calls 0 | est 1 act 1x1 removed 0x1 index searches 1 | hit 4 read 0 | workers none | median 0.007 ms p95 0.010 ms (N=21) plan 0.016 ms | 1 rows md5 df85c0fe203c | match
    Index Scan Index Cond: (documents_norls.id = 500025)
    Index Scan Filter: (documents_norls.tenant_id = 1)
T1 | Q3 lookup by id, RLS policy only | tenant_created | whale t1 | Index Scan; Index Scan documents_pkey; Index Cond + Filter | udf calls 0 | est 1 act 1x1 removed 0x1 index searches 1 | hit 4 read 0 | workers none | median 0.010 ms p95 0.015 ms (N=21) plan 0.026 ms | 1 rows md5 df85c0fe203c | match
    Index Scan Index Cond: (documents.id = 500025)
    Index Scan Filter: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
T1 | Q3 lookup by id, RLS policy + same WHERE | tenant_created | whale t1 | Result; Index Scan documents_pkey; Index Cond + Filter | udf calls 0 | est 1 act 1x1 removed 0x1 index searches 1 | hit 4 read 0 | workers none | median 0.018 ms p95 0.025 ms (N=21) plan 0.037 ms | 1 rows md5 df85c0fe203c | match
    Result One-Time Filter: ((NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer = 1)
    Index Scan Index Cond: (documents.id = 500025)
    Index Scan Filter: (documents.tenant_id = 1)
T1 | Q3 lookup by id, no RLS + WHERE | tenant_created | mid t2 | Index Scan; Index Scan documents_norls_pkey; Index Cond + Filter | udf calls 0 | est 1 act 1x1 removed 0x1 index searches 1 | hit 4 read 0 | workers none | median 0.016 ms p95 0.026 ms (N=21) plan 0.032 ms | 1 rows md5 6c4e33d6bbca | match
    Index Scan Index Cond: (documents_norls.id = 500591)
    Index Scan Filter: (documents_norls.tenant_id = 2)
T1 | Q3 lookup by id, RLS policy only | tenant_created | mid t2 | Index Scan; Index Scan documents_pkey; Index Cond + Filter | udf calls 0 | est 1 act 1x1 removed 0x1 index searches 1 | hit 4 read 0 | workers none | median 0.008 ms p95 0.012 ms (N=21) plan 0.022 ms | 1 rows md5 6c4e33d6bbca | match
    Index Scan Index Cond: (documents.id = 500591)
    Index Scan Filter: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
T1 | Q3 lookup by id, RLS policy + same WHERE | tenant_created | mid t2 | Result; Index Scan documents_pkey; Index Cond + Filter | udf calls 0 | est 1 act 1x1 removed 0x1 index searches 1 | hit 4 read 0 | workers none | median 0.010 ms p95 0.017 ms (N=21) plan 0.020 ms | 1 rows md5 6c4e33d6bbca | match
    Result One-Time Filter: ((NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer = 2)
    Index Scan Index Cond: (documents.id = 500591)
    Index Scan Filter: (documents.tenant_id = 2)
T1 | Q3 lookup by id, no RLS + WHERE | tenant_created | small t7 | Index Scan; Index Scan documents_norls_pkey; Index Cond + Filter | udf calls 0 | est 1 act 1x1 removed 0x1 index searches 1 | hit 4 read 0 | workers none | median 0.007 ms p95 0.011 ms (N=21) plan 0.016 ms | 1 rows md5 0be1387a3a99 | match
    Index Scan Index Cond: (documents_norls.id = 485243)
    Index Scan Filter: (documents_norls.tenant_id = 7)
T1 | Q3 lookup by id, RLS policy only | tenant_created | small t7 | Index Scan; Index Scan documents_pkey; Index Cond + Filter | udf calls 0 | est 1 act 1x1 removed 0x1 index searches 1 | hit 4 read 0 | workers none | median 0.008 ms p95 0.017 ms (N=21) plan 0.023 ms | 1 rows md5 0be1387a3a99 | match
    Index Scan Index Cond: (documents.id = 485243)
    Index Scan Filter: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
T1 | Q3 lookup by id, RLS policy + same WHERE | tenant_created | small t7 | Result; Index Scan documents_pkey; Index Cond + Filter | udf calls 0 | est 1 act 1x1 removed 0x1 index searches 1 | hit 4 read 0 | workers none | median 0.010 ms p95 0.012 ms (N=21) plan 0.020 ms | 1 rows md5 0be1387a3a99 | match
    Result One-Time Filter: ((NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer = 7)
    Index Scan Index Cond: (documents.id = 485243)
    Index Scan Filter: (documents.tenant_id = 7)
T1 | Q4 open since Dec 1, no RLS + WHERE | tenant_created | whale t1 | Bitmap Heap Scan; Bitmap Heap Scan; Recheck Cond + Filter | udf calls 0 | est 6682 act 6715x1 removed 27154x1 | hit 1645 read 0 | workers none | median 3.466 ms p95 4.298 ms (N=21) plan 0.032 ms | 6715 rows md5 2776a4a6dd0e | match
    Bitmap Heap Scan Recheck Cond: ((documents_norls.tenant_id = 1) AND (documents_norls.created_at >= '2026-12-01 00:00:00+00'::timestamp with time zone))
    Bitmap Heap Scan Filter: (documents_norls.status = 'open'::text)
    Bitmap Index Scan Index Cond: ((documents_norls.tenant_id = 1) AND (documents_norls.created_at >= '2026-12-01 00:00:00+00'::timestamp with time zone))
T1 | Q4 open since Dec 1, RLS policy only | tenant_created | whale t1 | Bitmap Heap Scan; Bitmap Heap Scan; Recheck Cond + Filter | udf calls 0 | est 6729 act 6715x1 removed 27154x1 | hit 1645 read 0 | workers none | median 3.767 ms p95 4.654 ms (N=21) plan 0.037 ms | 6715 rows md5 2776a4a6dd0e | match
    Bitmap Heap Scan Recheck Cond: ((documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer) AND (documents.created_at >= '2026-12-01 00:00:00+00'::timestamp with time zone))
    Bitmap Heap Scan Filter: (documents.status = 'open'::text)
    Bitmap Index Scan Index Cond: ((documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer) AND (documents.created_at >= '2026-12-01 00:00:00+00'::timestamp with time zone))
T1 | Q4 open since Dec 1, RLS policy + same WHERE | tenant_created | whale t1 | Result; Bitmap Heap Scan; Recheck Cond + Filter | udf calls 0 | est 6729 act 6715x1 removed 27154x1 | hit 1645 read 0 | workers none | median 3.911 ms p95 4.953 ms (N=21) plan 0.044 ms | 6715 rows md5 2776a4a6dd0e | match
    Result One-Time Filter: ((NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer = 1)
    Bitmap Heap Scan Recheck Cond: ((documents.tenant_id = 1) AND (documents.created_at >= '2026-12-01 00:00:00+00'::timestamp with time zone))
    Bitmap Heap Scan Filter: (documents.status = 'open'::text)
    Bitmap Index Scan Index Cond: ((documents.tenant_id = 1) AND (documents.created_at >= '2026-12-01 00:00:00+00'::timestamp with time zone))
T1 | Q4 open since Dec 1, no RLS + WHERE | tenant_created | mid t2 | Bitmap Heap Scan; Bitmap Heap Scan; Recheck Cond + Filter | udf calls 0 | est 837 act 852x1 removed 3441x1 | hit 1433 read 0 | workers none | median 1.162 ms p95 1.476 ms (N=21) plan 0.034 ms | 852 rows md5 c77ba6a1d867 | match
    Bitmap Heap Scan Recheck Cond: ((documents_norls.tenant_id = 2) AND (documents_norls.created_at >= '2026-12-01 00:00:00+00'::timestamp with time zone))
    Bitmap Heap Scan Filter: (documents_norls.status = 'open'::text)
    Bitmap Index Scan Index Cond: ((documents_norls.tenant_id = 2) AND (documents_norls.created_at >= '2026-12-01 00:00:00+00'::timestamp with time zone))
T1 | Q4 open since Dec 1, RLS policy only | tenant_created | mid t2 | Bitmap Heap Scan; Bitmap Heap Scan; Recheck Cond + Filter | udf calls 0 | est 876 act 852x1 removed 3441x1 | hit 1433 read 0 | workers none | median 1.142 ms p95 1.476 ms (N=21) plan 0.036 ms | 852 rows md5 c77ba6a1d867 | match
    Bitmap Heap Scan Recheck Cond: ((documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer) AND (documents.created_at >= '2026-12-01 00:00:00+00'::timestamp with time zone))
    Bitmap Heap Scan Filter: (documents.status = 'open'::text)
    Bitmap Index Scan Index Cond: ((documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer) AND (documents.created_at >= '2026-12-01 00:00:00+00'::timestamp with time zone))
T1 | Q4 open since Dec 1, RLS policy + same WHERE | tenant_created | mid t2 | Result; Bitmap Heap Scan; Recheck Cond + Filter | udf calls 0 | est 876 act 852x1 removed 3441x1 | hit 1433 read 0 | workers none | median 1.259 ms p95 1.407 ms (N=21) plan 0.034 ms | 852 rows md5 c77ba6a1d867 | match
    Result One-Time Filter: ((NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer = 2)
    Bitmap Heap Scan Recheck Cond: ((documents.tenant_id = 2) AND (documents.created_at >= '2026-12-01 00:00:00+00'::timestamp with time zone))
    Bitmap Heap Scan Filter: (documents.status = 'open'::text)
    Bitmap Index Scan Index Cond: ((documents.tenant_id = 2) AND (documents.created_at >= '2026-12-01 00:00:00+00'::timestamp with time zone))
T1 | Q4 open since Dec 1, no RLS + WHERE | tenant_created | small t7 | Bitmap Heap Scan; Bitmap Heap Scan; Recheck Cond + Filter | udf calls 0 | est 9 act 10x1 removed 43x1 | hit 54 read 0 | workers none | median 0.038 ms p95 0.060 ms (N=21) plan 0.020 ms | 10 rows md5 8064f8315f1c | match
    Bitmap Heap Scan Recheck Cond: ((documents_norls.tenant_id = 7) AND (documents_norls.created_at >= '2026-12-01 00:00:00+00'::timestamp with time zone))
    Bitmap Heap Scan Filter: (documents_norls.status = 'open'::text)
    Bitmap Index Scan Index Cond: ((documents_norls.tenant_id = 7) AND (documents_norls.created_at >= '2026-12-01 00:00:00+00'::timestamp with time zone))
T1 | Q4 open since Dec 1, RLS policy only | tenant_created | small t7 | Bitmap Heap Scan; Bitmap Heap Scan; Recheck Cond + Filter | udf calls 0 | est 9 act 10x1 removed 43x1 | hit 54 read 0 | workers none | median 0.033 ms p95 0.064 ms (N=21) plan 0.024 ms | 10 rows md5 8064f8315f1c | match
    Bitmap Heap Scan Recheck Cond: ((documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer) AND (documents.created_at >= '2026-12-01 00:00:00+00'::timestamp with time zone))
    Bitmap Heap Scan Filter: (documents.status = 'open'::text)
    Bitmap Index Scan Index Cond: ((documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer) AND (documents.created_at >= '2026-12-01 00:00:00+00'::timestamp with time zone))
T1 | Q4 open since Dec 1, RLS policy + same WHERE | tenant_created | small t7 | Result; Bitmap Heap Scan; Recheck Cond + Filter | udf calls 0 | est 9 act 10x1 removed 43x1 | hit 54 read 0 | workers none | median 0.030 ms p95 0.038 ms (N=21) plan 0.020 ms | 10 rows md5 8064f8315f1c | match
    Result One-Time Filter: ((NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer = 7)
    Bitmap Heap Scan Recheck Cond: ((documents.tenant_id = 7) AND (documents.created_at >= '2026-12-01 00:00:00+00'::timestamp with time zone))
    Bitmap Heap Scan Filter: (documents.status = 'open'::text)
    Bitmap Index Scan Index Cond: ((documents.tenant_id = 7) AND (documents.created_at >= '2026-12-01 00:00:00+00'::timestamp with time zone))
(T1 took 5.7 s)

## T2 policy expression and function attributes, Q2 count
indexes: primary key only
T2 | no RLS + WHERE | no tenant index | small t7 | Aggregate; Seq Scan; Filter | udf calls 0 | est 230 act 181.33x3 removed 333152x3 | hit 8823 read 8768 | workers 2/2 | median 19.741 ms p95 20.128 ms (N=21) plan 0.040 ms | count 544 | match
    Seq Scan Filter: (documents_norls.tenant_id = 7)
    --- EXPLAIN (ANALYZE, BUFFERS) ---
    Finalize Aggregate  (cost=23800.12..23800.13 rows=1 width=8) (actual time=16.859..18.897 rows=1.00 loops=1)
      Buffers: shared hit=9105 read=8486
      ->  Gather  (cost=23799.91..23800.12 rows=2 width=8) (actual time=16.749..18.891 rows=3.00 loops=1)
            Workers Planned: 2
            Workers Launched: 2
            Buffers: shared hit=9105 read=8486
            ->  Partial Aggregate  (cost=22799.91..22799.92 rows=1 width=8) (actual time=15.259..15.259 rows=1.00 loops=3)
                  Buffers: shared hit=9105 read=8486
                  ->  Parallel Seq Scan on documents_norls  (cost=0.00..22799.33 rows=230 width=0) (actual time=0.489..15.240 rows=181.33 loops=3)
                        Filter: (tenant_id = 7)
                        Rows Removed by Filter: 333152
                        Buffers: shared hit=9105 read=8486
    Planning Time: 0.017 ms
    Execution Time: 18.908 ms
    ---
policy: USING (tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
T2 | direct current_setting() | no tenant index | small t7 | Aggregate; Seq Scan; Filter | udf calls 0 | est 229 act 181.33x3 removed 333152x3 | hit 13366 read 4225 | workers 2/2 | median 44.707 ms p95 45.427 ms (N=21) plan 0.051 ms | count 544 | match
    Seq Scan Filter: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
    --- EXPLAIN (ANALYZE, BUFFERS) ---
    Finalize Aggregate  (cost=27966.79..27966.80 rows=1 width=8) (actual time=41.548..44.597 rows=1.00 loops=1)
      Buffers: shared hit=13648 read=3943
      ->  Gather  (cost=27966.57..27966.78 rows=2 width=8) (actual time=41.448..44.593 rows=3.00 loops=1)
            Workers Planned: 2
            Workers Launched: 2
            Buffers: shared hit=13648 read=3943
            ->  Partial Aggregate  (cost=26966.57..26966.58 rows=1 width=8) (actual time=39.818..39.819 rows=1.00 loops=3)
                  Buffers: shared hit=13648 read=3943
                  ->  Parallel Seq Scan on documents  (cost=0.00..26966.00 rows=229 width=0) (actual time=0.305..39.796 rows=181.33 loops=3)
                        Filter: (tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
                        Rows Removed by Filter: 333152
                        Buffers: shared hit=13648 read=3943
    Planning Time: 0.031 ms
    Execution Time: 44.611 ms
    ---
policy: USING (tenant_id = ( SELECT (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer AS "nullif"))
T2 | current_setting() wrapped in (select) | no tenant index | small t7 | Aggregate; Seq Scan; Filter; InitPlan 1 loops 1 | udf calls 0 | est 417 act 181.33x3 removed 333152x3 | hit 15998 read 1593 | workers 2/2 | median 20.874 ms p95 21.844 ms (N=21) plan 0.048 ms | count 544 | match
    Seq Scan Filter: (documents.tenant_id = (InitPlan 1).col1)
    --- EXPLAIN (ANALYZE, BUFFERS) ---
    Finalize Aggregate  (cost=23800.61..23800.62 rows=1 width=8) (actual time=18.725..22.052 rows=1.00 loops=1)
      Buffers: shared hit=15998 read=1593
      InitPlan 1
        ->  Result  (cost=0.00..0.02 rows=1 width=4) (actual time=0.001..0.002 rows=1.00 loops=1)
      ->  Gather  (cost=23800.38..23800.59 rows=2 width=8) (actual time=18.649..22.048 rows=3.00 loops=1)
            Workers Planned: 2
            Workers Launched: 2
            Buffers: shared hit=15998 read=1593
            ->  Partial Aggregate  (cost=22800.38..22800.39 rows=1 width=8) (actual time=16.872..16.873 rows=1.00 loops=3)
                  Buffers: shared hit=15998 read=1593
                  ->  Parallel Seq Scan on documents  (cost=0.00..22799.33 rows=417 width=0) (actual time=0.304..16.850 rows=181.33 loops=3)
                        Filter: (tenant_id = (InitPlan 1).col1)
                        Rows Removed by Filter: 333152
                        Buffers: shared hit=15998 read=1593
    Planning Time: 0.018 ms
    Execution Time: 22.064 ms
    ---
policy: USING (tenant_id = app_tenant_sql())
T2 | SQL STABLE function | no tenant index | small t7 | Aggregate; Seq Scan; Filter | udf calls 0 | est 550 act 544x1 removed 999456x1 | hit 16290 read 1301 | workers none | median 110.230 ms p95 111.202 ms (N=5) plan 0.064 ms | count 544 | match
    Seq Scan Filter: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
policy: USING (tenant_id = ( SELECT app_tenant_sql() AS app_tenant_sql))
T2 | SQL STABLE function wrapped | no tenant index | small t7 | Aggregate; Seq Scan; Filter; InitPlan 1 loops 1 | udf calls 0 | est 1000 act 544x1 removed 999456x1 | hit 16290 read 1301 | workers none | median 40.059 ms p95 41.400 ms (N=21) plan 0.058 ms | count 544 | match
    Seq Scan Filter: (documents.tenant_id = (InitPlan 1).col1)
policy: USING (tenant_id = app_tenant_sql_ps())
T2 | SQL STABLE PARALLEL SAFE function | no tenant index | small t7 | Aggregate; Seq Scan; Filter | udf calls 0 | est 229 act 181.33x3 removed 333152x3 | hit 16004 read 1587 | workers 2/2 | median 44.843 ms p95 47.440 ms (N=21) plan 0.067 ms | count 544 | match
    Seq Scan Filter: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
policy: USING (tenant_id = app_tenant_plpgsql())
T2 | plpgsql default (VOLATILE, PARALLEL UNSAFE) | no tenant index | small t7 | Aggregate; Seq Scan; Filter | udf calls app_tenant_plpgsql=1000000 | est 1000 act 544x1 removed 999456x1 | hit 16290 read 1301 | workers none | JIT 4 fns | median 532.341 ms p95 537.273 ms (N=5) plan 0.037 ms | count 544 | match
    Seq Scan Filter: (documents.tenant_id = app_tenant_plpgsql())
    --- EXPLAIN (ANALYZE, BUFFERS) ---
    Aggregate  (cost=280093.50..280093.51 rows=1 width=8) (actual time=531.737..531.738 rows=1.00 loops=1)
      Buffers: shared hit=16290 read=1301
      ->  Seq Scan on documents  (cost=0.00..280091.00 rows=1000 width=0) (actual time=1.698..531.621 rows=544.00 loops=1)
            Filter: (tenant_id = app_tenant_plpgsql())
            Rows Removed by Filter: 999456
            Buffers: shared hit=16290 read=1301
    Planning Time: 0.029 ms
    JIT:
      Functions: 4
      Options: Inlining false, Optimization false, Expressions true, Deforming true
      Timing: Generation 0.104 ms (Deform 0.020 ms), Inlining 0.000 ms, Optimization 0.108 ms, Emission 1.270 ms, Total 1.482 ms
    Execution Time: 531.894 ms
    ---
policy: USING (tenant_id = ( SELECT app_tenant_plpgsql() AS app_tenant_plpgsql))
T2 | plpgsql default wrapped | no tenant index | small t7 | Aggregate; Seq Scan; Filter; InitPlan 1 loops 1 | udf calls app_tenant_plpgsql=1 | est 1000 act 544x1 removed 999456x1 | hit 16290 read 1301 | workers none | median 37.836 ms p95 38.997 ms (N=21) plan 0.040 ms | count 544 | match
    Seq Scan Filter: (documents.tenant_id = (InitPlan 1).col1)
    --- EXPLAIN (ANALYZE, BUFFERS) ---
    Aggregate  (cost=30093.76..30093.77 rows=1 width=8) (actual time=36.779..36.781 rows=1.00 loops=1)
      Buffers: shared hit=16290 read=1301
      InitPlan 1
        ->  Result  (cost=0.00..0.26 rows=1 width=4) (actual time=0.012..0.013 rows=1.00 loops=1)
      ->  Seq Scan on documents  (cost=0.00..30091.00 rows=1000 width=0) (actual time=0.249..36.740 rows=544.00 loops=1)
            Filter: (tenant_id = (InitPlan 1).col1)
            Rows Removed by Filter: 999456
            Buffers: shared hit=16290 read=1301
    Planning Time: 0.014 ms
    Execution Time: 36.790 ms
    ---
policy: USING (tenant_id = app_tenant_plpgsql_stable())
T2 | plpgsql STABLE PARALLEL SAFE | no tenant index | small t7 | Aggregate; Seq Scan; Filter | udf calls app_tenant_plpgsql_stable=1000001 | est 229 act 181.33x3 removed 333152x3 | hit 16250 read 1611 | workers 2/2 | JIT 14 fns | median 174.907 ms p95 177.795 ms (N=5) plan 0.051 ms | count 544 | match
    Seq Scan Filter: (documents.tenant_id = app_tenant_plpgsql_stable())
policy: USING (tenant_id = app_tenant_definer())
T2 | SQL SECURITY DEFINER | no tenant index | small t7 | Aggregate; Seq Scan; Filter | udf calls app_tenant_definer=1000001 | est 550 act 544x1 removed 999456x1 | hit 16290 read 1301 | workers none | JIT 4 fns | median 1184.571 ms p95 1190.640 ms (N=5) plan 0.039 ms | count 544 | match
    Seq Scan Filter: (documents.tenant_id = app_tenant_definer())
policy: USING (tenant_id = ( SELECT app_tenant_definer() AS app_tenant_definer))
T2 | SQL SECURITY DEFINER wrapped | no tenant index | small t7 | Aggregate; Seq Scan; Filter; InitPlan 1 loops 1 | udf calls app_tenant_definer=1 | est 1000 act 544x1 removed 999456x1 | hit 16290 read 1301 | workers none | median 39.110 ms p95 43.706 ms (N=21) plan 0.036 ms | count 544 | match
    Seq Scan Filter: (documents.tenant_id = (InitPlan 1).col1)
policy: USING app_tenant_matches(tenant_id)
T2 | plpgsql STABLE taking tenant_id (row data) | no tenant index | small t7 | Aggregate; Seq Scan; Filter | udf calls app_tenant_matches=1000000 | est 138889 act 181.33x3 removed 333152x3 | hit 16268 read 1611 | workers 2/2 | JIT 14 fns | median 187.772 ms p95 188.899 ms (N=5) plan 0.036 ms | count 544 | match
    Seq Scan Filter: app_tenant_matches(documents.tenant_id)
indexes: 
  documents_tenant ON documents (tenant_id): 7200768 bytes, built in 207.484 ms (same index on documents_norls)
T2 | no RLS + WHERE | index (tenant_id) | whale t1 | Aggregate; Index Only Scan documents_tenant_norls; Index Cond | udf calls 0 | est 166778 act 133005x3 removed 0 heap fetches 0 index searches 1 | hit 342 read 0 | workers 2/2 | median 17.183 ms p95 18.802 ms (N=21) plan 0.046 ms | count 399015 | match
    Index Only Scan Index Cond: (documents_norls.tenant_id = 1)
T2 | no RLS + WHERE | index (tenant_id) | small t7 | Aggregate; Index Only Scan documents_tenant_norls; Index Cond | udf calls 0 | est 548 act 544x1 removed 0 heap fetches 0 index searches 1 | hit 5 read 0 | workers none | median 0.040 ms p95 0.050 ms (N=21) plan 0.018 ms | count 544 | match
    Index Only Scan Index Cond: (documents_norls.tenant_id = 7)
policy: USING (tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
T2 | direct current_setting() | index (tenant_id) | whale t1 | Aggregate; Index Only Scan documents_tenant; Index Cond | udf calls 0 | est 166764 act 133005x3 removed 0 heap fetches 0 index searches 1 | hit 342 read 0 | workers 2/2 | median 17.750 ms p95 18.482 ms (N=21) plan 0.058 ms | count 399015 | match
    Index Only Scan Index Cond: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
T2 | direct current_setting() | index (tenant_id) | small t7 | Aggregate; Index Only Scan documents_tenant; Index Cond | udf calls 0 | est 547 act 544x1 removed 0 heap fetches 0 index searches 1 | hit 5 read 0 | workers none | median 0.045 ms p95 0.052 ms (N=21) plan 0.034 ms | count 544 | match
    Index Only Scan Index Cond: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
policy: USING (tenant_id = ( SELECT (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer AS "nullif"))
T2 | current_setting() wrapped in (select) | index (tenant_id) | whale t1 | Aggregate; Index Only Scan documents_tenant; Index Cond; InitPlan 1 loops 1 | udf calls 0 | est 1000 act 399015x1 removed 0 heap fetches 0 index searches 1 | hit 339 read 0 | workers none | median 21.249 ms p95 22.087 ms (N=21) plan 0.053 ms | count 399015 | match
    Index Only Scan Index Cond: (documents.tenant_id = (InitPlan 1).col1)
T2 | current_setting() wrapped in (select) | index (tenant_id) | small t7 | Aggregate; Index Only Scan documents_tenant; Index Cond; InitPlan 1 loops 1 | udf calls 0 | est 1000 act 544x1 removed 0 heap fetches 0 index searches 1 | hit 5 read 0 | workers none | median 0.046 ms p95 0.055 ms (N=21) plan 0.031 ms | count 544 | match
    Index Only Scan Index Cond: (documents.tenant_id = (InitPlan 1).col1)
policy: USING (tenant_id = app_tenant_sql())
T2 | SQL STABLE function | index (tenant_id) | whale t1 | Aggregate; Index Only Scan documents_tenant; Index Cond | udf calls 0 | est 400233 act 399015x1 removed 0 heap fetches 0 index searches 1 | hit 339 read 0 | workers none | median 21.742 ms p95 22.194 ms (N=21) plan 0.067 ms | count 399015 | match
    Index Only Scan Index Cond: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
T2 | SQL STABLE function | index (tenant_id) | small t7 | Aggregate; Index Only Scan documents_tenant; Index Cond | udf calls 0 | est 547 act 544x1 removed 0 heap fetches 0 index searches 1 | hit 5 read 0 | workers none | median 0.041 ms p95 0.050 ms (N=21) plan 0.032 ms | count 544 | match
    Index Only Scan Index Cond: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
policy: USING (tenant_id = ( SELECT app_tenant_sql() AS app_tenant_sql))
T2 | SQL STABLE function wrapped | index (tenant_id) | whale t1 | Aggregate; Index Only Scan documents_tenant; Index Cond; InitPlan 1 loops 1 | udf calls 0 | est 1000 act 399015x1 removed 0 heap fetches 0 index searches 1 | hit 339 read 0 | workers none | median 21.076 ms p95 21.289 ms (N=21) plan 0.059 ms | count 399015 | match
    Index Only Scan Index Cond: (documents.tenant_id = (InitPlan 1).col1)
T2 | SQL STABLE function wrapped | index (tenant_id) | small t7 | Aggregate; Index Only Scan documents_tenant; Index Cond; InitPlan 1 loops 1 | udf calls 0 | est 1000 act 544x1 removed 0 heap fetches 0 index searches 1 | hit 5 read 0 | workers none | median 0.040 ms p95 0.053 ms (N=21) plan 0.030 ms | count 544 | match
    Index Only Scan Index Cond: (documents.tenant_id = (InitPlan 1).col1)
policy: USING (tenant_id = app_tenant_sql_ps())
T2 | SQL STABLE PARALLEL SAFE function | index (tenant_id) | whale t1 | Aggregate; Index Only Scan documents_tenant; Index Cond | udf calls 0 | est 166764 act 133005x3 removed 0 heap fetches 0 index searches 1 | hit 342 read 0 | workers 2/2 | median 17.275 ms p95 18.112 ms (N=21) plan 0.072 ms | count 399015 | match
    Index Only Scan Index Cond: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
T2 | SQL STABLE PARALLEL SAFE function | index (tenant_id) | small t7 | Aggregate; Index Only Scan documents_tenant; Index Cond | udf calls 0 | est 547 act 544x1 removed 0 heap fetches 0 index searches 1 | hit 5 read 0 | workers none | median 0.047 ms p95 0.052 ms (N=21) plan 0.051 ms | count 544 | match
    Index Only Scan Index Cond: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
policy: USING (tenant_id = app_tenant_plpgsql())
T2 | plpgsql default (VOLATILE, PARALLEL UNSAFE) | index (tenant_id) | whale t1 | Aggregate; Index Only Scan documents_tenant; Filter | udf calls app_tenant_plpgsql=1000000 | est 1000 act 399015x1 removed 600985x1 heap fetches 0 index searches 1 | hit 875 read 0 | workers none | JIT 3 fns | median 530.966 ms p95 546.801 ms (N=5) plan 0.042 ms | count 399015 | match
    Index Only Scan Filter: (documents.tenant_id = app_tenant_plpgsql())
T2 | plpgsql default (VOLATILE, PARALLEL UNSAFE) | index (tenant_id) | small t7 | Aggregate; Index Only Scan documents_tenant; Filter | udf calls app_tenant_plpgsql=1000000 | est 1000 act 544x1 removed 999456x1 heap fetches 0 index searches 1 | hit 875 read 0 | workers none | JIT 3 fns | median 518.509 ms p95 528.380 ms (N=5) plan 0.034 ms | count 544 | match
    Index Only Scan Filter: (documents.tenant_id = app_tenant_plpgsql())
policy: USING (tenant_id = ( SELECT app_tenant_plpgsql() AS app_tenant_plpgsql))
T2 | plpgsql default wrapped | index (tenant_id) | whale t1 | Aggregate; Index Only Scan documents_tenant; Index Cond; InitPlan 1 loops 1 | udf calls app_tenant_plpgsql=1 | est 1000 act 399015x1 removed 0 heap fetches 0 index searches 1 | hit 339 read 0 | workers none | median 20.804 ms p95 21.288 ms (N=21) plan 0.037 ms | count 399015 | match
    Index Only Scan Index Cond: (documents.tenant_id = (InitPlan 1).col1)
T2 | plpgsql default wrapped | index (tenant_id) | small t7 | Aggregate; Index Only Scan documents_tenant; Index Cond; InitPlan 1 loops 1 | udf calls app_tenant_plpgsql=1 | est 1000 act 544x1 removed 0 heap fetches 0 index searches 1 | hit 5 read 0 | workers none | median 0.045 ms p95 0.053 ms (N=21) plan 0.019 ms | count 544 | match
    Index Only Scan Index Cond: (documents.tenant_id = (InitPlan 1).col1)
policy: USING (tenant_id = app_tenant_plpgsql_stable())
T2 | plpgsql STABLE PARALLEL SAFE | index (tenant_id) | whale t1 | Aggregate; Index Only Scan documents_tenant; Index Cond | udf calls app_tenant_plpgsql_stable=4 | est 166764 act 133005x3 removed 0 heap fetches 0 index searches 1 | hit 618 read 0 | workers 2/2 | median 16.543 ms p95 17.685 ms (N=21) plan 0.057 ms | count 399015 | match
    Index Only Scan Index Cond: (documents.tenant_id = app_tenant_plpgsql_stable())
T2 | plpgsql STABLE PARALLEL SAFE | index (tenant_id) | small t7 | Aggregate; Index Only Scan documents_tenant; Index Cond | udf calls app_tenant_plpgsql_stable=2 | est 547 act 544x1 removed 0 heap fetches 0 index searches 1 | hit 5 read 0 | workers none | median 0.038 ms p95 0.049 ms (N=21) plan 0.021 ms | count 544 | match
    Index Only Scan Index Cond: (documents.tenant_id = app_tenant_plpgsql_stable())
policy: USING (tenant_id = app_tenant_definer())
T2 | SQL SECURITY DEFINER | index (tenant_id) | whale t1 | Aggregate; Index Only Scan documents_tenant; Index Cond | udf calls app_tenant_definer=2 | est 400233 act 399015x1 removed 0 heap fetches 0 index searches 1 | hit 339 read 0 | workers none | median 21.020 ms p95 22.500 ms (N=21) plan 0.041 ms | count 399015 | match
    Index Only Scan Index Cond: (documents.tenant_id = app_tenant_definer())
T2 | SQL SECURITY DEFINER | index (tenant_id) | small t7 | Aggregate; Index Only Scan documents_tenant; Index Cond | udf calls app_tenant_definer=2 | est 547 act 544x1 removed 0 heap fetches 0 index searches 1 | hit 5 read 0 | workers none | median 0.047 ms p95 0.056 ms (N=21) plan 0.039 ms | count 544 | match
    Index Only Scan Index Cond: (documents.tenant_id = app_tenant_definer())
policy: USING (tenant_id = ( SELECT app_tenant_definer() AS app_tenant_definer))
T2 | SQL SECURITY DEFINER wrapped | index (tenant_id) | whale t1 | Aggregate; Index Only Scan documents_tenant; Index Cond; InitPlan 1 loops 1 | udf calls app_tenant_definer=1 | est 1000 act 399015x1 removed 0 heap fetches 0 index searches 1 | hit 339 read 0 | workers none | median 20.729 ms p95 21.555 ms (N=21) plan 0.034 ms | count 399015 | match
    Index Only Scan Index Cond: (documents.tenant_id = (InitPlan 1).col1)
T2 | SQL SECURITY DEFINER wrapped | index (tenant_id) | small t7 | Aggregate; Index Only Scan documents_tenant; Index Cond; InitPlan 1 loops 1 | udf calls app_tenant_definer=1 | est 1000 act 544x1 removed 0 heap fetches 0 index searches 1 | hit 5 read 0 | workers none | median 0.044 ms p95 0.056 ms (N=21) plan 0.018 ms | count 544 | match
    Index Only Scan Index Cond: (documents.tenant_id = (InitPlan 1).col1)
policy: USING app_tenant_matches(tenant_id)
T2 | plpgsql STABLE taking tenant_id (row data) | index (tenant_id) | whale t1 | Aggregate; Index Only Scan documents_tenant; Filter | udf calls app_tenant_matches=1000000 | est 138889 act 133005x3 removed 200328x3 heap fetches 0 index searches 1 | hit 1171 read 0 | workers 2/2 | JIT 11 fns | median 182.190 ms p95 183.722 ms (N=5) plan 0.046 ms | count 399015 | match
    Index Only Scan Filter: app_tenant_matches(documents.tenant_id)
T2 | plpgsql STABLE taking tenant_id (row data) | index (tenant_id) | small t7 | Aggregate; Index Only Scan documents_tenant; Filter | udf calls app_tenant_matches=1000000 | est 138889 act 181.33x3 removed 333152x3 heap fetches 0 index searches 1 | hit 1171 read 0 | workers 2/2 | JIT 11 fns | median 180.338 ms p95 181.582 ms (N=5) plan 0.041 ms | count 544 | match
    Index Only Scan Filter: app_tenant_matches(documents.tenant_id)
(T2 took 52.5 s)

## T3 index shape under the direct policy, Q1 and Q4
policy: USING (tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
indexes: 
  documents_created ON documents (created_at): 22487040 bytes, built in 175.569 ms (same index on documents_norls)
T3 | Q1 latest 20, RLS policy only | index (created_at) | whale t1 | Limit; Index Scan documents_created; Filter | udf calls 0 | est 390867 act 20x1 removed 36x1 index searches 1 | hit 5 read 0 | workers none | median 0.022 ms p95 0.026 ms (N=21) plan 0.029 ms | 20 ids in order md5 e71393c3c9dc | match
    Index Scan Filter: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
T3 | Q1 latest 20, RLS policy only | index (created_at) | mid t2 | Limit; Index Scan documents_created; Filter | udf calls 0 | est 50200 act 20x1 removed 392x1 index searches 1 | hit 12 read 0 | workers none | median 0.074 ms p95 0.085 ms (N=21) plan 0.035 ms | 20 ids in order md5 80fa8d5e2b13 | match
    Index Scan Filter: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
T3 | Q1 latest 20, RLS policy only | index (created_at) | small t7 | Limit; Index Scan documents_created; Filter | udf calls 0 | est 558 act 20x1 removed 36399x1 index searches 1 | hit 797 read 0 | workers none | median 5.353 ms p95 5.664 ms (N=21) plan 0.050 ms | 20 ids in order md5 e07f44460e37 | match
    Index Scan Filter: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
T3 | Q4 open since Dec 1, RLS policy only | index (created_at) | whale t1 | Index Scan; Index Scan documents_created; Index Cond + Filter | udf calls 0 | est 6752 act 6715x1 removed 78216x1 index searches 1 | hit 1858 read 0 | workers none | median 8.698 ms p95 9.264 ms (N=21) plan 0.050 ms | 6715 rows md5 2776a4a6dd0e | match
    Index Scan Index Cond: (documents.created_at >= '2026-12-01 00:00:00+00'::timestamp with time zone)
    Index Scan Filter: ((documents.status = 'open'::text) AND (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer))
T3 | Q4 open since Dec 1, RLS policy only | index (created_at) | mid t2 | Gather; Index Scan documents_created; Index Cond + Filter | udf calls 0 | est 361 act 284x3 removed 28026x3 index searches 1 | hit 1858 read 0 | workers 2/2 | median 12.975 ms p95 13.818 ms (N=21) plan 0.052 ms | 852 rows md5 c77ba6a1d867 | match
    Index Scan Index Cond: (documents.created_at >= '2026-12-01 00:00:00+00'::timestamp with time zone)
    Index Scan Filter: ((documents.status = 'open'::text) AND (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer))
T3 | Q4 open since Dec 1, RLS policy only | index (created_at) | small t7 | Gather; Index Scan documents_created; Index Cond + Filter | udf calls 0 | est 4 act 3.33x3 removed 28307x3 index searches 1 | hit 1858 read 0 | workers 2/2 | median 13.574 ms p95 14.257 ms (N=21) plan 0.052 ms | 10 rows md5 8064f8315f1c | match
    Index Scan Index Cond: (documents.created_at >= '2026-12-01 00:00:00+00'::timestamp with time zone)
    Index Scan Filter: ((documents.status = 'open'::text) AND (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer))
indexes: 
  documents_tenant ON documents (tenant_id): 7200768 bytes, built in 209.472 ms (same index on documents_norls)
T3 | Q1 latest 20, RLS policy only | index (tenant_id) | whale t1 | Limit; Bitmap Heap Scan; Recheck Cond | udf calls 0 | est 165305 act 133005x3 removed 0 | hit 4719 read 13266 | workers 2/2 | median 43.468 ms p95 46.433 ms (N=21) plan 0.056 ms | 20 ids in order md5 e71393c3c9dc | match
    Bitmap Heap Scan Recheck Cond: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
    Bitmap Index Scan Index Cond: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
T3 | Q1 latest 20, RLS policy only | index (tenant_id) | mid t2 | Limit; Bitmap Heap Scan; Recheck Cond | udf calls 0 | est 20542 act 16600.67x3 removed 0 | hit 5976 read 10722 | workers 2/2 | median 29.589 ms p95 31.900 ms (N=21) plan 0.058 ms | 20 ids in order md5 80fa8d5e2b13 | match
    Bitmap Heap Scan Recheck Cond: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
    Bitmap Index Scan Index Cond: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
T3 | Q1 latest 20, RLS policy only | index (tenant_id) | small t7 | Limit; Bitmap Heap Scan; Recheck Cond | udf calls 0 | est 554 act 544x1 removed 0 | hit 538 read 0 | workers none | median 0.300 ms p95 0.562 ms (N=21) plan 0.025 ms | 20 ids in order md5 e07f44460e37 | match
    Bitmap Heap Scan Recheck Cond: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
    Bitmap Index Scan Index Cond: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
T3 | Q4 open since Dec 1, RLS policy only | index (tenant_id) | whale t1 | Gather; Bitmap Heap Scan; Recheck Cond + Filter | udf calls 0 | est 2838 act 2238.33x3 removed 130767x3 | hit 4859 read 13110 | workers 2/2 | median 38.147 ms p95 47.276 ms (N=21) plan 0.056 ms | 6715 rows md5 2776a4a6dd0e | match
    Bitmap Heap Scan Recheck Cond: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
    Bitmap Heap Scan Filter: ((documents.created_at >= '2026-12-01 00:00:00+00'::timestamp with time zone) AND (documents.status = 'open'::text))
    Bitmap Index Scan Index Cond: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
T3 | Q4 open since Dec 1, RLS policy only | index (tenant_id) | mid t2 | Bitmap Heap Scan; Bitmap Heap Scan; Recheck Cond + Filter | udf calls 0 | est 846 act 852x1 removed 48950x1 | hit 3674 read 12968 | workers none | median 25.224 ms p95 26.804 ms (N=21) plan 0.057 ms | 852 rows md5 c77ba6a1d867 | match
    Bitmap Heap Scan Recheck Cond: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
    Bitmap Heap Scan Filter: ((documents.created_at >= '2026-12-01 00:00:00+00'::timestamp with time zone) AND (documents.status = 'open'::text))
    Bitmap Index Scan Index Cond: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
T3 | Q4 open since Dec 1, RLS policy only | index (tenant_id) | small t7 | Bitmap Heap Scan; Bitmap Heap Scan; Recheck Cond + Filter | udf calls 0 | est 10 act 10x1 removed 534x1 | hit 538 read 0 | workers none | median 0.331 ms p95 0.435 ms (N=21) plan 0.029 ms | 10 rows md5 8064f8315f1c | match
    Bitmap Heap Scan Recheck Cond: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
    Bitmap Heap Scan Filter: ((documents.created_at >= '2026-12-01 00:00:00+00'::timestamp with time zone) AND (documents.status = 'open'::text))
    Bitmap Index Scan Index Cond: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
indexes: 
  documents_tenant_created ON documents (tenant_id, created_at): 31563776 bytes, built in 279.389 ms (same index on documents_norls)
T3 | Q1 latest 20, RLS policy only | index (tenant_id, created_at) | whale t1 | Limit; Index Scan documents_tenant_created; Index Cond | udf calls 0 | est 397233 act 20x1 removed 0 index searches 1 | hit 5 read 0 | workers none | median 0.014 ms p95 0.019 ms (N=21) plan 0.026 ms | 20 ids in order md5 e71393c3c9dc | match
    Index Scan Index Cond: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
T3 | Q1 latest 20, RLS policy only | index (tenant_id, created_at) | mid t2 | Limit; Index Scan documents_tenant_created; Index Cond | udf calls 0 | est 49100 act 20x1 removed 0 index searches 1 | hit 10 read 0 | workers none | median 0.015 ms p95 0.021 ms (N=21) plan 0.025 ms | 20 ids in order md5 80fa8d5e2b13 | match
    Index Scan Index Cond: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
T3 | Q1 latest 20, RLS policy only | index (tenant_id, created_at) | small t7 | Limit; Index Scan documents_tenant_created; Index Cond | udf calls 0 | est 554 act 20x1 removed 0 index searches 1 | hit 23 read 0 | workers none | median 0.018 ms p95 0.023 ms (N=21) plan 0.024 ms | 20 ids in order md5 e07f44460e37 | match
    Index Scan Index Cond: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
T3 | Q4 open since Dec 1, RLS policy only | index (tenant_id, created_at) | whale t1 | Bitmap Heap Scan; Bitmap Heap Scan; Recheck Cond + Filter | udf calls 0 | est 6639 act 6715x1 removed 27154x1 | hit 1645 read 0 | workers none | median 3.149 ms p95 3.269 ms (N=21) plan 0.041 ms | 6715 rows md5 2776a4a6dd0e | match
    Bitmap Heap Scan Recheck Cond: ((documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer) AND (documents.created_at >= '2026-12-01 00:00:00+00'::timestamp with time zone))
    Bitmap Heap Scan Filter: (documents.status = 'open'::text)
    Bitmap Index Scan Index Cond: ((documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer) AND (documents.created_at >= '2026-12-01 00:00:00+00'::timestamp with time zone))
T3 | Q4 open since Dec 1, RLS policy only | index (tenant_id, created_at) | mid t2 | Bitmap Heap Scan; Bitmap Heap Scan; Recheck Cond + Filter | udf calls 0 | est 821 act 852x1 removed 3441x1 | hit 1433 read 0 | workers none | median 1.069 ms p95 1.218 ms (N=21) plan 0.033 ms | 852 rows md5 c77ba6a1d867 | match
    Bitmap Heap Scan Recheck Cond: ((documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer) AND (documents.created_at >= '2026-12-01 00:00:00+00'::timestamp with time zone))
    Bitmap Heap Scan Filter: (documents.status = 'open'::text)
    Bitmap Index Scan Index Cond: ((documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer) AND (documents.created_at >= '2026-12-01 00:00:00+00'::timestamp with time zone))
T3 | Q4 open since Dec 1, RLS policy only | index (tenant_id, created_at) | small t7 | Bitmap Heap Scan; Bitmap Heap Scan; Recheck Cond + Filter | udf calls 0 | est 9 act 10x1 removed 43x1 | hit 54 read 0 | workers none | median 0.038 ms p95 0.070 ms (N=21) plan 0.029 ms | 10 rows md5 8064f8315f1c | match
    Bitmap Heap Scan Recheck Cond: ((documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer) AND (documents.created_at >= '2026-12-01 00:00:00+00'::timestamp with time zone))
    Bitmap Heap Scan Filter: (documents.status = 'open'::text)
    Bitmap Index Scan Index Cond: ((documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer) AND (documents.created_at >= '2026-12-01 00:00:00+00'::timestamp with time zone))
(T3 took 8.9 s)

## T4 membership-table policies, index (tenant_id, created_at)
indexes: 
  documents_tenant_created ON documents (tenant_id, created_at): 31563776 bytes, built in 281.454 ms (same index on documents_norls)
policy: USING (tenant_id IN ( SELECT m.tenant_id
   FROM memberships m
  WHERE (m.user_id = (NULLIF(current_setting('app.user_id'::text, true), ''::text))::integer)))
T4 | Q1 latest 20, IN subquery | tenant_created | consultant u1 (200 tenants) | Limit; Seq Scan; Filter; SubPlan 1 loops 3 | udf calls 0 | est 208333 act 186072.33x3 removed 147261x3 | hit 16014 read 1604 | workers 2/2 | median 63.009 ms p95 65.661 ms (N=5) plan 0.057 ms | 20 ids in order md5 6ec424fdfae2 | match
    Seq Scan Filter: (ANY (documents.tenant_id = (hashed SubPlan 1).col1))
    SubPlan 1 Index Only Scan Index Cond: (m.user_id = (NULLIF(current_setting('app.user_id'::text, true), ''::text))::integer)
T4 | Q1 latest 20, IN subquery | tenant_created | single-tenant u2 | Limit; Seq Scan; Filter; SubPlan 1 loops 3 | udf calls 0 | est 208333 act 181.33x3 removed 333152x3 | hit 16042 read 1576 | workers 2/2 | median 35.905 ms p95 39.915 ms (N=21) plan 0.068 ms | 20 ids in order md5 e07f44460e37 | match
    Seq Scan Filter: (ANY (documents.tenant_id = (hashed SubPlan 1).col1))
    SubPlan 1 Index Only Scan Index Cond: (m.user_id = (NULLIF(current_setting('app.user_id'::text, true), ''::text))::integer)
T4 | Q2 count, IN subquery | tenant_created | consultant u1 (200 tenants) | Aggregate; Seq Scan; Filter; SubPlan 1 loops 3 | udf calls 0 | est 208333 act 186072.33x3 removed 147261x3 | hit 15793 read 1809 | workers 2/2 | median 50.874 ms p95 51.403 ms (N=5) plan 0.069 ms | count 558217 | match
    Seq Scan Filter: (ANY (documents.tenant_id = (hashed SubPlan 1).col1))
    SubPlan 1 Index Only Scan Index Cond: (m.user_id = (NULLIF(current_setting('app.user_id'::text, true), ''::text))::integer)
T4 | Q2 count, IN subquery | tenant_created | single-tenant u2 | Aggregate; Seq Scan; Filter; SubPlan 1 loops 3 | udf calls 0 | est 208333 act 181.33x3 removed 333152x3 | hit 16005 read 1597 | workers 2/2 | median 34.772 ms p95 37.133 ms (N=21) plan 0.068 ms | count 544 | match
    Seq Scan Filter: (ANY (documents.tenant_id = (hashed SubPlan 1).col1))
    SubPlan 1 Index Only Scan Index Cond: (m.user_id = (NULLIF(current_setting('app.user_id'::text, true), ''::text))::integer)
policy: USING (EXISTS ( SELECT 1
   FROM memberships m
  WHERE ((m.tenant_id = documents.tenant_id) AND (m.user_id = (NULLIF(current_setting('app.user_id'::text, true), ''::text))::integer))))
T4 | Q1 latest 20, EXISTS correlated | tenant_created | consultant u1 (200 tenants) | Limit; Seq Scan; Filter; SubPlan 2 loops 1 | udf calls 0 | est 500000 act 558217x1 removed 441783x1 | hit 16290 read 1304 | workers none | JIT 19 fns | median 203.928 ms p95 212.060 ms (N=5) plan 0.090 ms | 20 ids in order md5 6ec424fdfae2 | match
    Seq Scan Filter: (ANY (documents.tenant_id = (hashed SubPlan 2).col1))
    SubPlan 2 Index Only Scan Index Cond: (m.user_id = (NULLIF(current_setting('app.user_id'::text, true), ''::text))::integer)
T4 | Q1 latest 20, EXISTS correlated | tenant_created | single-tenant u2 | Limit; Seq Scan; Filter; SubPlan 2 loops 1 | udf calls 0 | est 500000 act 544x1 removed 999456x1 | hit 16290 read 1304 | workers none | JIT 19 fns | median 129.530 ms p95 131.141 ms (N=5) plan 0.081 ms | 20 ids in order md5 e07f44460e37 | match
    Seq Scan Filter: (ANY (documents.tenant_id = (hashed SubPlan 2).col1))
    SubPlan 2 Index Only Scan Index Cond: (m.user_id = (NULLIF(current_setting('app.user_id'::text, true), ''::text))::integer)
T4 | Q2 count, EXISTS correlated | tenant_created | consultant u1 (200 tenants) | Aggregate; Seq Scan; Filter; SubPlan 2 loops 1 | udf calls 0 | est 500000 act 558217x1 removed 441783x1 | hit 16290 read 1304 | workers none | JIT 18 fns | median 159.752 ms p95 165.622 ms (N=5) plan 0.092 ms | count 558217 | match
    Seq Scan Filter: (ANY (documents.tenant_id = (hashed SubPlan 2).col1))
    SubPlan 2 Index Only Scan Index Cond: (m.user_id = (NULLIF(current_setting('app.user_id'::text, true), ''::text))::integer)
T4 | Q2 count, EXISTS correlated | tenant_created | single-tenant u2 | Aggregate; Seq Scan; Filter; SubPlan 2 loops 1 | udf calls 0 | est 500000 act 544x1 removed 999456x1 | hit 16290 read 1304 | workers none | JIT 18 fns | median 128.188 ms p95 136.645 ms (N=5) plan 0.088 ms | count 544 | match
    Seq Scan Filter: (ANY (documents.tenant_id = (hashed SubPlan 2).col1))
    SubPlan 2 Index Only Scan Index Cond: (m.user_id = (NULLIF(current_setting('app.user_id'::text, true), ''::text))::integer)
policy: USING (tenant_id = ANY (ARRAY( SELECT m.tenant_id
   FROM memberships m
  WHERE (m.user_id = (NULLIF(current_setting('app.user_id'::text, true), ''::text))::integer))))
T4 | Q1 latest 20, = ANY(array(select)) | tenant_created | consultant u1 (200 tenants) | Limit; Bitmap Heap Scan; Recheck Cond; InitPlan 1 loops 1 | udf calls 0 | est 9955 act 558217x1 removed 0 | hit 398 read 20127 | workers none | median 103.186 ms p95 108.043 ms (N=5) plan 0.079 ms | 20 ids in order md5 6ec424fdfae2 | match
    InitPlan 1 Index Only Scan Index Cond: (m.user_id = (NULLIF(current_setting('app.user_id'::text, true), ''::text))::integer)
    Bitmap Heap Scan Recheck Cond: (documents.tenant_id = ANY ((InitPlan 1).col1))
    Bitmap Index Scan Index Cond: (documents.tenant_id = ANY ((InitPlan 1).col1))
T4 | Q1 latest 20, = ANY(array(select)) | tenant_created | single-tenant u2 | Limit; Bitmap Heap Scan; Recheck Cond; InitPlan 1 loops 1 | udf calls 0 | est 9955 act 544x1 removed 0 | hit 542 read 0 | workers none | median 0.312 ms p95 0.538 ms (N=21) plan 0.035 ms | 20 ids in order md5 e07f44460e37 | match
    InitPlan 1 Index Only Scan Index Cond: (m.user_id = (NULLIF(current_setting('app.user_id'::text, true), ''::text))::integer)
    Bitmap Heap Scan Recheck Cond: (documents.tenant_id = ANY ((InitPlan 1).col1))
    Bitmap Index Scan Index Cond: (documents.tenant_id = ANY ((InitPlan 1).col1))
T4 | Q2 count, = ANY(array(select)) | tenant_created | consultant u1 (200 tenants) | Aggregate; Index Only Scan documents_tenant_created; Index Cond; InitPlan 1 loops 1 | udf calls 0 | est 9955 act 558217x1 removed 0 heap fetches 0 index searches 199 | hit 2935 read 0 | workers none | median 34.008 ms p95 35.883 ms (N=21) plan 0.055 ms | count 558217 | match
    InitPlan 1 Index Only Scan Index Cond: (m.user_id = (NULLIF(current_setting('app.user_id'::text, true), ''::text))::integer)
    Index Only Scan Index Cond: (documents.tenant_id = ANY ((InitPlan 1).col1))
T4 | Q2 count, = ANY(array(select)) | tenant_created | single-tenant u2 | Aggregate; Index Only Scan documents_tenant_created; Index Cond; InitPlan 1 loops 1 | udf calls 0 | est 9955 act 544x1 removed 0 heap fetches 0 index searches 1 | hit 9 read 0 | workers none | median 0.049 ms p95 0.059 ms (N=21) plan 0.029 ms | count 544 | match
    InitPlan 1 Index Only Scan Index Cond: (m.user_id = (NULLIF(current_setting('app.user_id'::text, true), ''::text))::integer)
    Index Only Scan Index Cond: (documents.tenant_id = ANY ((InitPlan 1).col1))
policy: USING (tenant_id = ANY (app_user_tenants()))
T4 | Q1 latest 20, SECURITY DEFINER int[] function | tenant_created | consultant u1 (200 tenants) | Limit; Index Scan documents_tenant_created; Index Cond | udf calls app_user_tenants=2 | est 560972 act 558217x1 removed 0 index searches 199 | hit 120728 read 25501 | workers none | JIT 6 fns | median 273.611 ms p95 285.231 ms (N=5) plan 0.167 ms | 20 ids in order md5 6ec424fdfae2 | match
    Index Scan Index Cond: (documents.tenant_id = ANY (app_user_tenants()))
T4 | Q1 latest 20, SECURITY DEFINER int[] function | tenant_created | single-tenant u2 | Limit; Bitmap Heap Scan; Recheck Cond | udf calls app_user_tenants=2 | est 546 act 544x1 removed 0 | hit 542 read 0 | workers none | median 0.312 ms p95 0.429 ms (N=21) plan 0.035 ms | 20 ids in order md5 e07f44460e37 | match
    Bitmap Heap Scan Recheck Cond: (documents.tenant_id = ANY (app_user_tenants()))
    Bitmap Index Scan Index Cond: (documents.tenant_id = ANY (app_user_tenants()))
T4 | Q2 count, SECURITY DEFINER int[] function | tenant_created | consultant u1 (200 tenants) | Aggregate; Index Only Scan documents_tenant_created; Index Cond | udf calls app_user_tenants=2 | est 560972 act 558217x1 removed 0 heap fetches 0 index searches 199 | hit 2935 read 0 | workers none | median 34.163 ms p95 35.750 ms (N=21) plan 0.116 ms | count 558217 | match
    Index Only Scan Index Cond: (documents.tenant_id = ANY (app_user_tenants()))
T4 | Q2 count, SECURITY DEFINER int[] function | tenant_created | single-tenant u2 | Aggregate; Index Only Scan documents_tenant_created; Index Cond | udf calls app_user_tenants=2 | est 546 act 544x1 removed 0 heap fetches 0 index searches 1 | hit 9 read 0 | workers none | median 0.047 ms p95 0.056 ms (N=21) plan 0.028 ms | count 544 | match
    Index Only Scan Index Cond: (documents.tenant_id = ANY (app_user_tenants()))
policy: USING (tenant_id = ANY (( SELECT app_user_tenants() AS app_user_tenants)::integer[]))
T4 | Q1 latest 20, SECURITY DEFINER int[] function wrapped | tenant_created | consultant u1 (200 tenants) | Limit; Bitmap Heap Scan; Recheck Cond; InitPlan 1 loops 1 | udf calls app_user_tenants=1 | est 9955 act 558217x1 removed 0 | hit 397 read 20128 | workers none | median 101.933 ms p95 103.591 ms (N=5) plan 0.057 ms | 20 ids in order md5 6ec424fdfae2 | match
    Bitmap Heap Scan Recheck Cond: (documents.tenant_id = ANY ((InitPlan 1).col1))
    Bitmap Index Scan Index Cond: (documents.tenant_id = ANY ((InitPlan 1).col1))
T4 | Q1 latest 20, SECURITY DEFINER int[] function wrapped | tenant_created | single-tenant u2 | Limit; Bitmap Heap Scan; Recheck Cond; InitPlan 1 loops 1 | udf calls app_user_tenants=1 | est 9955 act 544x1 removed 0 | hit 542 read 0 | workers none | median 0.307 ms p95 0.523 ms (N=21) plan 0.021 ms | 20 ids in order md5 e07f44460e37 | match
    Bitmap Heap Scan Recheck Cond: (documents.tenant_id = ANY ((InitPlan 1).col1))
    Bitmap Index Scan Index Cond: (documents.tenant_id = ANY ((InitPlan 1).col1))
T4 | Q2 count, SECURITY DEFINER int[] function wrapped | tenant_created | consultant u1 (200 tenants) | Aggregate; Index Only Scan documents_tenant_created; Index Cond; InitPlan 1 loops 1 | udf calls app_user_tenants=1 | est 9955 act 558217x1 removed 0 heap fetches 0 index searches 199 | hit 2935 read 0 | workers none | median 34.699 ms p95 36.191 ms (N=21) plan 0.040 ms | count 558217 | match
    Index Only Scan Index Cond: (documents.tenant_id = ANY ((InitPlan 1).col1))
T4 | Q2 count, SECURITY DEFINER int[] function wrapped | tenant_created | single-tenant u2 | Aggregate; Index Only Scan documents_tenant_created; Index Cond; InitPlan 1 loops 1 | udf calls app_user_tenants=1 | est 9955 act 544x1 removed 0 heap fetches 0 index searches 1 | hit 9 read 0 | workers none | median 0.057 ms p95 0.072 ms (N=21) plan 0.018 ms | count 544 | match
    Index Only Scan Index Cond: (documents.tenant_id = ANY ((InitPlan 1).col1))
(T4 took 19.2 s)

## T5 user filter with a non-leakproof function, direct policy
policy: USING (tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
indexes: 
  documents_lower_email ON documents (lower(email)): 53854208 bytes, built in 1603.314 ms (same index on documents_norls)
  documents_email ON documents (email): 53854208 bytes, built in 1427.826 ms (same index on documents_norls)
  documents_email_lower ON documents (email_lower): 53854208 bytes, built in 1439.319 ms (same index on documents_norls)
T5 | Q5 lower(email) = value, no RLS + WHERE | indexes (lower(email)), (email), (email_lower) | whale t1 | Index Scan; Index Scan documents_lower_email_norls; Index Cond + Filter | udf calls 0 | est 1 act 1x1 removed 0x1 index searches 1 | hit 4 read 0 | workers none | median 0.010 ms p95 0.020 ms (N=21) plan 0.019 ms | 1 rows md5 df85c0fe203c | match
    Index Scan Index Cond: (lower(documents_norls.email) = 'user500025@tenant1.example.com'::text)
    Index Scan Filter: (documents_norls.tenant_id = 1)
    --- EXPLAIN (ANALYZE, BUFFERS) ---
    Index Scan using documents_lower_email_norls on documents_norls  (cost=0.42..8.45 rows=1 width=8) (actual time=0.005..0.005 rows=1.00 loops=1)
      Index Cond: (lower(email) = 'user500025@tenant1.example.com'::text)
      Filter: (tenant_id = 1)
      Index Searches: 1
      Buffers: shared hit=4
    Planning Time: 0.016 ms
    Execution Time: 0.008 ms
    ---
T5 | Q5 lower(email) = value, RLS policy only | indexes (lower(email)), (email), (email_lower) | whale t1 | Gather; Seq Scan; Filter | udf calls 0 | est 1 act 0.33x3 removed 333333x3 | hit 15874 read 1717 | workers 2/2 | median 96.896 ms p95 97.617 ms (N=5) plan 0.055 ms | 1 rows md5 df85c0fe203c | match
    Seq Scan Filter: ((documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer) AND (lower(documents.email) = 'user500025@tenant1.example.com'::text))
    --- EXPLAIN (ANALYZE, BUFFERS) ---
    Gather  (cost=1000.00..30049.43 rows=1 width=8) (actual time=93.739..96.945 rows=1.00 loops=1)
      Workers Planned: 2
      Workers Launched: 2
      Buffers: shared hit=16009 read=1582
      ->  Parallel Seq Scan on documents  (cost=0.00..29049.33 rows=1 width=8) (actual time=71.808..86.078 rows=0.33 loops=3)
            Filter: ((tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer) AND (lower(email) = 'user500025@tenant1.example.com'::text))
            Rows Removed by Filter: 333333
            Buffers: shared hit=16009 read=1582
    Planning Time: 0.050 ms
    Execution Time: 96.956 ms
    ---
T5 | Q5 lower(email) = value, no RLS + WHERE | indexes (lower(email)), (email), (email_lower) | small t7 | Index Scan; Index Scan documents_lower_email_norls; Index Cond + Filter | udf calls 0 | est 1 act 1x1 removed 0x1 index searches 1 | hit 4 read 0 | workers none | median 0.010 ms p95 0.013 ms (N=21) plan 0.017 ms | 1 rows md5 0be1387a3a99 | match
    Index Scan Index Cond: (lower(documents_norls.email) = 'user485243@tenant7.example.com'::text)
    Index Scan Filter: (documents_norls.tenant_id = 7)
T5 | Q5 lower(email) = value, RLS policy only | indexes (lower(email)), (email), (email_lower) | small t7 | Gather; Seq Scan; Filter | udf calls 0 | est 1 act 0.33x3 removed 333333x3 | hit 16009 read 1582 | workers 2/2 | median 50.186 ms p95 50.874 ms (N=5) plan 0.053 ms | 1 rows md5 0be1387a3a99 | match
    Seq Scan Filter: ((documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer) AND (lower(documents.email) = 'user485243@tenant7.example.com'::text))
T5 | Q6 email = value, no RLS + WHERE | indexes (lower(email)), (email), (email_lower) | whale t1 | Index Scan; Index Scan documents_email_norls; Index Cond + Filter | udf calls 0 | est 1 act 1x1 removed 0x1 index searches 1 | hit 4 read 0 | workers none | median 0.009 ms p95 0.012 ms (N=21) plan 0.017 ms | 1 rows md5 df85c0fe203c | match
    Index Scan Index Cond: (documents_norls.email = 'User500025@Tenant1.Example.com'::text)
    Index Scan Filter: (documents_norls.tenant_id = 1)
T5 | Q6 email = value, RLS policy only | indexes (lower(email)), (email), (email_lower) | whale t1 | Index Scan; Index Scan documents_email; Index Cond + Filter | udf calls 0 | est 1 act 1x1 removed 0x1 index searches 1 | hit 4 read 0 | workers none | median 0.011 ms p95 0.019 ms (N=21) plan 0.024 ms | 1 rows md5 df85c0fe203c | match
    Index Scan Index Cond: (documents.email = 'User500025@Tenant1.Example.com'::text)
    Index Scan Filter: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
T5 | Q6 email = value, no RLS + WHERE | indexes (lower(email)), (email), (email_lower) | small t7 | Index Scan; Index Scan documents_email_norls; Index Cond + Filter | udf calls 0 | est 1 act 1x1 removed 0x1 index searches 1 | hit 4 read 0 | workers none | median 0.010 ms p95 0.017 ms (N=21) plan 0.019 ms | 1 rows md5 0be1387a3a99 | match
    Index Scan Index Cond: (documents_norls.email = 'User485243@Tenant7.Example.com'::text)
    Index Scan Filter: (documents_norls.tenant_id = 7)
T5 | Q6 email = value, RLS policy only | indexes (lower(email)), (email), (email_lower) | small t7 | Index Scan; Index Scan documents_email; Index Cond + Filter | udf calls 0 | est 1 act 1x1 removed 0x1 index searches 1 | hit 4 read 0 | workers none | median 0.009 ms p95 0.013 ms (N=21) plan 0.021 ms | 1 rows md5 0be1387a3a99 | match
    Index Scan Index Cond: (documents.email = 'User485243@Tenant7.Example.com'::text)
    Index Scan Filter: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
T5 | Q5b email_lower (stored generated column) = value, no RLS + WHERE | indexes (lower(email)), (email), (email_lower) | whale t1 | Index Scan; Index Scan documents_email_lower_norls; Index Cond + Filter | udf calls 0 | est 1 act 1x1 removed 0x1 index searches 1 | hit 4 read 0 | workers none | median 0.009 ms p95 0.015 ms (N=21) plan 0.016 ms | 1 rows md5 df85c0fe203c | match
    Index Scan Index Cond: (documents_norls.email_lower = 'user500025@tenant1.example.com'::text)
    Index Scan Filter: (documents_norls.tenant_id = 1)
    --- EXPLAIN (ANALYZE, BUFFERS) ---
    Index Scan using documents_email_lower_norls on documents_norls  (cost=0.42..8.45 rows=1 width=8) (actual time=0.008..0.009 rows=1.00 loops=1)
      Index Cond: (email_lower = 'user500025@tenant1.example.com'::text)
      Filter: (tenant_id = 1)
      Index Searches: 1
      Buffers: shared hit=4
    Planning Time: 0.024 ms
    Execution Time: 0.012 ms
    ---
T5 | Q5b email_lower (stored generated column) = value, RLS policy only | indexes (lower(email)), (email), (email_lower) | whale t1 | Index Scan; Index Scan documents_email_lower; Index Cond + Filter | udf calls 0 | est 1 act 1x1 removed 0x1 index searches 1 | hit 4 read 0 | workers none | median 0.010 ms p95 0.016 ms (N=21) plan 0.023 ms | 1 rows md5 df85c0fe203c | match
    Index Scan Index Cond: (documents.email_lower = 'user500025@tenant1.example.com'::text)
    Index Scan Filter: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
    --- EXPLAIN (ANALYZE, BUFFERS) ---
    Index Scan using documents_email_lower on documents  (cost=0.42..8.46 rows=1 width=8) (actual time=0.007..0.007 rows=1.00 loops=1)
      Index Cond: (email_lower = 'user500025@tenant1.example.com'::text)
      Filter: (tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
      Index Searches: 1
      Buffers: shared hit=4
    Planning Time: 0.021 ms
    Execution Time: 0.010 ms
    ---
T5 | Q5b email_lower (stored generated column) = value, no RLS + WHERE | indexes (lower(email)), (email), (email_lower) | small t7 | Index Scan; Index Scan documents_email_lower_norls; Index Cond + Filter | udf calls 0 | est 1 act 1x1 removed 0x1 index searches 1 | hit 4 read 0 | workers none | median 0.010 ms p95 0.014 ms (N=21) plan 0.019 ms | 1 rows md5 0be1387a3a99 | match
    Index Scan Index Cond: (documents_norls.email_lower = 'user485243@tenant7.example.com'::text)
    Index Scan Filter: (documents_norls.tenant_id = 7)
T5 | Q5b email_lower (stored generated column) = value, RLS policy only | indexes (lower(email)), (email), (email_lower) | small t7 | Index Scan; Index Scan documents_email_lower; Index Cond + Filter | udf calls 0 | est 1 act 1x1 removed 0x1 index searches 1 | hit 4 read 0 | workers none | median 0.012 ms p95 0.022 ms (N=21) plan 0.024 ms | 1 rows md5 0be1387a3a99 | match
    Index Scan Index Cond: (documents.email_lower = 'user485243@tenant7.example.com'::text)
    Index Scan Filter: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
indexes: 
  documents_tenant_lower_email ON documents (tenant_id, lower(email)): 59039744 bytes, built in 1337.550 ms (same index on documents_norls)
  documents_tenant_email ON documents (tenant_id, email): 59039744 bytes, built in 1255.523 ms (same index on documents_norls)
  documents_tenant_email_lower ON documents (tenant_id, email_lower): 59039744 bytes, built in 1227.740 ms (same index on documents_norls)
T5 | Q5 lower(email) = value, no RLS + WHERE | indexes (tenant_id, lower(email)), (tenant_id, email), (tenant_id, email_lower) | whale t1 | Index Scan; Index Scan documents_tenant_lower_email_norls; Index Cond | udf calls 0 | est 1 act 1x1 removed 0 index searches 1 | hit 4 read 0 | workers none | median 0.010 ms p95 0.020 ms (N=21) plan 0.021 ms | 1 rows md5 df85c0fe203c | match
    Index Scan Index Cond: ((documents_norls.tenant_id = 1) AND (lower(documents_norls.email) = 'user500025@tenant1.example.com'::text))
    --- EXPLAIN (ANALYZE, BUFFERS) ---
    Index Scan using documents_tenant_lower_email_norls on documents_norls  (cost=0.42..8.45 rows=1 width=8) (actual time=0.006..0.007 rows=1.00 loops=1)
      Index Cond: ((tenant_id = 1) AND (lower(email) = 'user500025@tenant1.example.com'::text))
      Index Searches: 1
      Buffers: shared hit=4
    Planning Time: 0.021 ms
    Execution Time: 0.010 ms
    ---
T5 | Q5 lower(email) = value, RLS policy only | indexes (tenant_id, lower(email)), (tenant_id, email), (tenant_id, email_lower) | whale t1 | Gather; Seq Scan; Filter | udf calls 0 | est 1 act 0.33x3 removed 333333x3 | hit 16009 read 1582 | workers 2/2 | median 96.749 ms p95 98.326 ms (N=5) plan 0.063 ms | 1 rows md5 df85c0fe203c | match
    Seq Scan Filter: ((documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer) AND (lower(documents.email) = 'user500025@tenant1.example.com'::text))
    --- EXPLAIN (ANALYZE, BUFFERS) ---
    Gather  (cost=1000.00..30049.43 rows=1 width=8) (actual time=92.685..96.187 rows=1.00 loops=1)
      Workers Planned: 2
      Workers Launched: 2
      Buffers: shared hit=16009 read=1582
      ->  Parallel Seq Scan on documents  (cost=0.00..29049.33 rows=1 width=8) (actual time=71.287..85.510 rows=0.33 loops=3)
            Filter: ((tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer) AND (lower(email) = 'user500025@tenant1.example.com'::text))
            Rows Removed by Filter: 333333
            Buffers: shared hit=16009 read=1582
    Planning Time: 0.030 ms
    Execution Time: 96.195 ms
    ---
T5 | Q5 lower(email) = value, no RLS + WHERE | indexes (tenant_id, lower(email)), (tenant_id, email), (tenant_id, email_lower) | small t7 | Index Scan; Index Scan documents_tenant_lower_email_norls; Index Cond | udf calls 0 | est 1 act 1x1 removed 0 index searches 1 | hit 4 read 0 | workers none | median 0.009 ms p95 0.014 ms (N=21) plan 0.025 ms | 1 rows md5 0be1387a3a99 | match
    Index Scan Index Cond: ((documents_norls.tenant_id = 7) AND (lower(documents_norls.email) = 'user485243@tenant7.example.com'::text))
T5 | Q5 lower(email) = value, RLS policy only | indexes (tenant_id, lower(email)), (tenant_id, email), (tenant_id, email_lower) | small t7 | Bitmap Heap Scan; Bitmap Heap Scan; Recheck Cond + Filter | udf calls 0 | est 1 act 1x1 removed 543x1 | hit 541 read 0 | workers none | median 0.594 ms p95 0.743 ms (N=21) plan 0.045 ms | 1 rows md5 0be1387a3a99 | match
    Bitmap Heap Scan Recheck Cond: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
    Bitmap Heap Scan Filter: (lower(documents.email) = 'user485243@tenant7.example.com'::text)
    Bitmap Index Scan Index Cond: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
T5 | Q6 email = value, no RLS + WHERE | indexes (tenant_id, lower(email)), (tenant_id, email), (tenant_id, email_lower) | whale t1 | Index Scan; Index Scan documents_tenant_email_norls; Index Cond | udf calls 0 | est 1 act 1x1 removed 0 index searches 1 | hit 4 read 0 | workers none | median 0.017 ms p95 0.026 ms (N=21) plan 0.038 ms | 1 rows md5 df85c0fe203c | match
    Index Scan Index Cond: ((documents_norls.tenant_id = 1) AND (documents_norls.email = 'User500025@Tenant1.Example.com'::text))
T5 | Q6 email = value, RLS policy only | indexes (tenant_id, lower(email)), (tenant_id, email), (tenant_id, email_lower) | whale t1 | Index Scan; Index Scan documents_tenant_email; Index Cond | udf calls 0 | est 1 act 1x1 removed 0 index searches 1 | hit 4 read 0 | workers none | median 0.010 ms p95 0.016 ms (N=21) plan 0.025 ms | 1 rows md5 df85c0fe203c | match
    Index Scan Index Cond: ((documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer) AND (documents.email = 'User500025@Tenant1.Example.com'::text))
T5 | Q6 email = value, no RLS + WHERE | indexes (tenant_id, lower(email)), (tenant_id, email), (tenant_id, email_lower) | small t7 | Index Scan; Index Scan documents_tenant_email_norls; Index Cond | udf calls 0 | est 1 act 1x1 removed 0 index searches 1 | hit 4 read 0 | workers none | median 0.011 ms p95 0.017 ms (N=21) plan 0.027 ms | 1 rows md5 0be1387a3a99 | match
    Index Scan Index Cond: ((documents_norls.tenant_id = 7) AND (documents_norls.email = 'User485243@Tenant7.Example.com'::text))
T5 | Q6 email = value, RLS policy only | indexes (tenant_id, lower(email)), (tenant_id, email), (tenant_id, email_lower) | small t7 | Index Scan; Index Scan documents_tenant_email; Index Cond | udf calls 0 | est 1 act 1x1 removed 0 index searches 1 | hit 4 read 0 | workers none | median 0.015 ms p95 0.022 ms (N=21) plan 0.034 ms | 1 rows md5 0be1387a3a99 | match
    Index Scan Index Cond: ((documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer) AND (documents.email = 'User485243@Tenant7.Example.com'::text))
T5 | Q5b email_lower (stored generated column) = value, no RLS + WHERE | indexes (tenant_id, lower(email)), (tenant_id, email), (tenant_id, email_lower) | whale t1 | Index Scan; Index Scan documents_tenant_email_lower_norls; Index Cond | udf calls 0 | est 1 act 1x1 removed 0 index searches 1 | hit 4 read 0 | workers none | median 0.015 ms p95 0.022 ms (N=21) plan 0.031 ms | 1 rows md5 df85c0fe203c | match
    Index Scan Index Cond: ((documents_norls.tenant_id = 1) AND (documents_norls.email_lower = 'user500025@tenant1.example.com'::text))
    --- EXPLAIN (ANALYZE, BUFFERS) ---
    Index Scan using documents_tenant_email_lower_norls on documents_norls  (cost=0.42..8.45 rows=1 width=8) (actual time=0.010..0.010 rows=1.00 loops=1)
      Index Cond: ((tenant_id = 1) AND (email_lower = 'user500025@tenant1.example.com'::text))
      Index Searches: 1
      Buffers: shared hit=4
    Planning Time: 0.022 ms
    Execution Time: 0.013 ms
    ---
T5 | Q5b email_lower (stored generated column) = value, RLS policy only | indexes (tenant_id, lower(email)), (tenant_id, email), (tenant_id, email_lower) | whale t1 | Index Scan; Index Scan documents_tenant_email_lower; Index Cond | udf calls 0 | est 1 act 1x1 removed 0 index searches 1 | hit 4 read 0 | workers none | median 0.011 ms p95 0.020 ms (N=21) plan 0.026 ms | 1 rows md5 df85c0fe203c | match
    Index Scan Index Cond: ((documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer) AND (documents.email_lower = 'user500025@tenant1.example.com'::text))
    --- EXPLAIN (ANALYZE, BUFFERS) ---
    Index Scan using documents_tenant_email_lower on documents  (cost=0.43..8.46 rows=1 width=8) (actual time=0.006..0.006 rows=1.00 loops=1)
      Index Cond: ((tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer) AND (email_lower = 'user500025@tenant1.example.com'::text))
      Index Searches: 1
      Buffers: shared hit=4
    Planning Time: 0.023 ms
    Execution Time: 0.010 ms
    ---
T5 | Q5b email_lower (stored generated column) = value, no RLS + WHERE | indexes (tenant_id, lower(email)), (tenant_id, email), (tenant_id, email_lower) | small t7 | Index Scan; Index Scan documents_tenant_email_lower_norls; Index Cond | udf calls 0 | est 1 act 1x1 removed 0 index searches 1 | hit 4 read 0 | workers none | median 0.008 ms p95 0.016 ms (N=21) plan 0.020 ms | 1 rows md5 0be1387a3a99 | match
    Index Scan Index Cond: ((documents_norls.tenant_id = 7) AND (documents_norls.email_lower = 'user485243@tenant7.example.com'::text))
T5 | Q5b email_lower (stored generated column) = value, RLS policy only | indexes (tenant_id, lower(email)), (tenant_id, email), (tenant_id, email_lower) | small t7 | Index Scan; Index Scan documents_tenant_email_lower; Index Cond | udf calls 0 | est 1 act 1x1 removed 0 index searches 1 | hit 4 read 0 | workers none | median 0.010 ms p95 0.012 ms (N=21) plan 0.024 ms | 1 rows md5 0be1387a3a99 | match
    Index Scan Index Cond: ((documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer) AND (documents.email_lower = 'user485243@tenant7.example.com'::text))
(T5 took 21.5 s)

## T6 count(*) where status = 'open', index-only scans
indexes: 
  documents_status ON documents (status): 6979584 bytes, built in 303.252 ms (same index on documents_norls)
T6 | Q7 count open, no RLS + WHERE | index (status) | whale t1 | Aggregate; Bitmap Heap Scan; Recheck Cond + Filter | udf calls 0 | est 33171 act 26626.67x3 removed 39955x3 | hit 40 read 17762 | workers 2/2 | median 37.505 ms p95 40.338 ms (N=21) plan 0.058 ms | count 79880 | match
    Bitmap Heap Scan Recheck Cond: (documents_norls.status = 'open'::text)
    Bitmap Heap Scan Filter: (documents_norls.tenant_id = 1)
    Bitmap Index Scan Index Cond: (documents_norls.status = 'open'::text)
T6 | Q7 count open, RLS policy only | index (status) | whale t1 | Aggregate; Bitmap Heap Scan; Recheck Cond + Filter | udf calls 0 | est 33039 act 26626.67x3 removed 39955x3 | hit 40 read 17762 | workers 2/2 | median 37.319 ms p95 39.505 ms (N=21) plan 0.058 ms | count 79880 | match
    Bitmap Heap Scan Recheck Cond: (documents.status = 'open'::text)
    Bitmap Heap Scan Filter: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
    Bitmap Index Scan Index Cond: (documents.status = 'open'::text)
T6 | Q7 count open, no RLS + WHERE | index (status) | small t7 | Aggregate; Bitmap Heap Scan; Recheck Cond + Filter | udf calls 0 | est 46 act 37.67x3 removed 66544x3 | hit 40 read 17762 | workers 2/2 | median 37.731 ms p95 59.663 ms (N=21) plan 0.062 ms | count 113 | match
    Bitmap Heap Scan Recheck Cond: (documents_norls.status = 'open'::text)
    Bitmap Heap Scan Filter: (documents_norls.tenant_id = 7)
    Bitmap Index Scan Index Cond: (documents_norls.status = 'open'::text)
T6 | Q7 count open, RLS policy only | index (status) | small t7 | Aggregate; Bitmap Heap Scan; Recheck Cond + Filter | udf calls 0 | est 45 act 37.67x3 removed 66544x3 | hit 40 read 17762 | workers 2/2 | median 37.614 ms p95 45.124 ms (N=21) plan 0.068 ms | count 113 | match
    Bitmap Heap Scan Recheck Cond: (documents.status = 'open'::text)
    Bitmap Heap Scan Filter: (documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
    Bitmap Index Scan Index Cond: (documents.status = 'open'::text)
indexes: 
  documents_tenant_status ON documents (tenant_id, status): 7200768 bytes, built in 343.298 ms (same index on documents_norls)
T6 | Q7 count open, no RLS + WHERE | index (tenant_id, status) | whale t1 | Aggregate; Index Only Scan documents_tenant_status_norls; Index Cond | udf calls 0 | est 80692 act 79880x1 removed 0 heap fetches 0 index searches 1 | hit 72 read 0 | workers none | median 4.264 ms p95 4.675 ms (N=21) plan 0.039 ms | count 79880 | match
    Index Only Scan Index Cond: ((documents_norls.tenant_id = 1) AND (documents_norls.status = 'open'::text))
T6 | Q7 count open, RLS policy only | index (tenant_id, status) | whale t1 | Aggregate; Index Only Scan documents_tenant_status; Index Cond | udf calls 0 | est 80407 act 79880x1 removed 0 heap fetches 0 index searches 1 | hit 72 read 0 | workers none | median 4.313 ms p95 4.423 ms (N=21) plan 0.048 ms | count 79880 | match
    Index Only Scan Index Cond: ((documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer) AND (documents.status = 'open'::text))
T6 | Q7 count open, no RLS + WHERE | index (tenant_id, status) | small t7 | Aggregate; Index Only Scan documents_tenant_status_norls; Index Cond | udf calls 0 | est 109 act 113x1 removed 0 heap fetches 0 index searches 1 | hit 4 read 0 | workers none | median 0.026 ms p95 0.036 ms (N=21) plan 0.034 ms | count 113 | match
    Index Only Scan Index Cond: ((documents_norls.tenant_id = 7) AND (documents_norls.status = 'open'::text))
T6 | Q7 count open, RLS policy only | index (tenant_id, status) | small t7 | Aggregate; Index Only Scan documents_tenant_status; Index Cond | udf calls 0 | est 110 act 113x1 removed 0 heap fetches 0 index searches 1 | hit 4 read 0 | workers none | median 0.017 ms p95 0.024 ms (N=21) plan 0.025 ms | count 113 | match
    Index Only Scan Index Cond: ((documents.tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer) AND (documents.status = 'open'::text))
(T6 took 7.2 s)

## T7 writes under WITH CHECK, tenant mid t2, index (tenant_id, created_at); every execution rolled back, VACUUM before each
indexes: 
  documents_tenant_created ON documents (tenant_id, created_at): 31563776 bytes, built in 275.926 ms (same index on documents_norls)
policy: none (documents_norls has no RLS)
T7 | W1 insert 10000 rows, no RLS | tenant_created | mid t2 | ModifyTable; ?;  | udf calls n/a | est undefined act undefined removed undefined | hit 52813 read 0 | workers none | median 21.663 ms p95 22.618 ms (N=21) plan 0.043 ms | 10000 rows written | match
T7 | W2 update 10000 rows, no RLS | tenant_created | mid t2 | ModifyTable; Index Scan documents_norls_pkey; Index Cond + Filter | udf calls n/a | est 9329 act 10000x1 removed 191812x1 index searches 1 | hit 136412 read 0 | workers none | median 61.736 ms p95 67.200 ms (N=5) plan 0.063 ms | 10000 rows written | match
    Index Scan Index Cond: ((documents_norls.id >= 401213) AND (documents_norls.id <= 603024))
    Index Scan Filter: (documents_norls.tenant_id = 2)
policy: USING (tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
T7 | W1 insert 10000 rows, simple tenant policy | tenant_created | mid t2 | ModifyTable; ?;  | udf calls n/a | est undefined act undefined removed undefined | hit 52814 read 0 | workers none | median 23.475 ms p95 24.310 ms (N=21) plan 0.043 ms | 10000 rows written | match
T7 | W2 update 10000 rows, simple tenant policy | tenant_created | mid t2 | ModifyTable; Index Scan documents_pkey; Index Cond + Filter | udf calls n/a | est 9367 act 10000x1 removed 191812x1 index searches 1 | hit 136412 read 0 | workers none | median 62.943 ms p95 68.371 ms (N=5) plan 0.064 ms | 10000 rows written | match
    Result One-Time Filter: ((NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer = 2)
    Index Scan Index Cond: ((documents.id >= 401213) AND (documents.id <= 603024))
    Index Scan Filter: (documents.tenant_id = 2)
policy: USING (tenant_id IN ( SELECT m.tenant_id
   FROM memberships m
  WHERE (m.user_id = (NULLIF(current_setting('app.user_id'::text, true), ''::text))::integer)))
T7 | W1 insert 10000 rows, membership IN subquery | tenant_created | consultant u1, writing t2 | ModifyTable; ?; ; SubPlan 1 loops 1 | udf calls n/a | est undefined act undefined removed undefined | hit 52817 read 0 | workers none | median 23.204 ms p95 24.764 ms (N=21) plan 0.082 ms | 10000 rows written | match
    SubPlan 1 Index Only Scan Index Cond: (m.user_id = (NULLIF(current_setting('app.user_id'::text, true), ''::text))::integer)
T7 | W2 update 10000 rows, membership IN subquery | tenant_created | consultant u1, writing t2 | ModifyTable; Index Scan documents_pkey; Index Cond + Filter; SubPlan 2 loops 1, SubPlan 1 loops 1 | udf calls n/a | est 4684 act 10000x1 removed 191812x1 index searches 1 | hit 136418 read 0 | workers none | median 78.183 ms p95 92.881 ms (N=5) plan 0.103 ms | 10000 rows written | match
    Index Scan Index Cond: ((documents.id >= 401213) AND (documents.id <= 603024))
    Index Scan Filter: ((ANY (documents.tenant_id = (hashed SubPlan 2).col1)) AND (documents.tenant_id = 2))
    SubPlan 2 Index Only Scan Index Cond: (m_1.user_id = (NULLIF(current_setting('app.user_id'::text, true), ''::text))::integer)
    SubPlan 1 Index Only Scan Index Cond: (m.user_id = (NULLIF(current_setting('app.user_id'::text, true), ''::text))::integer)
policy: USING (tenant_id = ANY (( SELECT app_user_tenants() AS app_user_tenants)::integer[]))
T7 | W1 insert 10000 rows, SECURITY DEFINER int[] function wrapped | tenant_created | consultant u1, writing t2 | ModifyTable; ?; ; InitPlan 1 loops 1 | udf calls n/a | est undefined act undefined removed undefined | hit 52817 read 0 | workers none | median 23.216 ms p95 24.935 ms (N=21) plan 0.049 ms | 10000 rows written | match
T7 | W2 update 10000 rows, SECURITY DEFINER int[] function wrapped | tenant_created | consultant u1, writing t2 | ModifyTable; Bitmap Heap Scan; Recheck Cond + Filter; InitPlan 1 loops 1, InitPlan 2 loops 1 | udf calls n/a | est 93 act 10000x1 removed 39802x1 | hit 115208 read 13568 | workers none | median 81.962 ms p95 94.039 ms (N=5) plan 0.074 ms | 10000 rows written | match
    Bitmap Heap Scan Recheck Cond: ((documents.tenant_id = ANY ((InitPlan 2).col1)) AND (documents.tenant_id = 2))
    Bitmap Heap Scan Filter: ((documents.id >= 401213) AND (documents.id <= 603024))
    Bitmap Index Scan Index Cond: ((documents.tenant_id = ANY ((InitPlan 2).col1)) AND (documents.tenant_id = 2))
(T7 took 10.2 s)

cells 150, mismatches 0, timeouts 0
run finished   2026-11-13T07:21:32.194Z, total 130.7 s

Frequently asked questions

Does row-level security slow down Postgres queries?

Not when the policy compares tenant_id to a per-statement value and an index leads with tenant_id: in our PostgreSQL 18.7 test on 1,000,000 seeded rows, the largest tenant's latest-20 query had a median of 0.014 ms under the policy and 0.015 ms with a WHERE clause on a copy without RLS. RLS gets slow when the policy calls a function once per row, uses an IN or EXISTS membership subquery that forces a full scan, or when your own filter passes a column to a non-leakproof function such as lower().

Why is my Postgres RLS policy slow?

Usually because the policy, or a function in it, runs per row in a Filter instead of as an Index Cond. In our PostgreSQL 18.7 test on 1,000,000 rows, four causes showed up: an index that does not lead with tenant_id (a 544-row tenant's latest 20 took 5.353 ms against 0.018 ms with one that does), a default VOLATILE plpgsql policy function (532.3 ms for that tenant's count with no tenant index, against 37.8 ms wrapped), an IN or EXISTS membership subquery (34.8 and 128.2 ms against 0.049 ms for an array form), and a non-leakproof function such as lower() in your own WHERE (96.9 ms against 0.010 ms without RLS for the largest tenant). Run EXPLAIN (ANALYZE, BUFFERS) as the application role to see which one you have.

Should the app still add WHERE tenant_id when RLS is on?

Not for speed, in our test. With a policy comparing tenant_id to current_setting() and an index on (tenant_id, created_at), PostgreSQL 18.7 used the app's WHERE as the index condition and moved the policy into a One-Time Filter. On 1,000,000 rows, the largest tenant's count had a median of 17.1 ms with both, against 13.4 ms with the policy alone, and the gap held in all three runs on 18.7. The latest-20 query was 0.014 ms either way. We didn't test a policy that can't use the index.

Should I wrap current_setting() or auth.uid() in a SELECT in my RLS policy?

Wrap helper function calls, and wrap a bare current_setting() when no index leads with tenant_id. With no tenant index, a count for a 544-row tenant on 1,000,000 rows had a median of 44.7 ms with a direct current_setting() call and 20.9 ms wrapped, in our PostgreSQL 18.7 run. With a tenant_id index both were index conditions, and the wrap made the largest tenant's count slower, 21.2 ms against 17.8 ms; the wrapped form estimated 1,000 rows instead of 399,015 and got no parallel workers. We timed current_setting(), not auth.uid() on Supabase.

Why does Postgres ignore my index when RLS is on?

Two causes showed up in our test: a condition in your own WHERE clause that passes a column to a function not marked leakproof, which Postgres keeps behind the policy and cannot use in an index scan, or an index that does not lead with tenant_id. On PostgreSQL 18.7, lower(email) = a value used its expression index without RLS (median 0.010 ms) and became a parallel sequential scan under RLS (96.9 ms) for the largest tenant. Plain equality on a stored lowercased column kept its index under RLS (0.010 ms).

Should RLS helper functions be STABLE, SECURITY DEFINER or LEAKPROOF?

Mark them STABLE and PARALLEL SAFE when that is true, call them inside a SELECT, and leave LEAKPROOF alone. A default plpgsql function is VOLATILE and was called 1,000,000 times for one count in our PostgreSQL 18.7 test, a median of 532.3 ms against 37.8 ms wrapped, and it stayed a per-row Filter even with a tenant index (531.0 ms against 20.8 ms wrapped for the largest tenant). A SECURITY DEFINER SQL function was not inlined and took 1,184.6 ms unwrapped with no tenant index. LEAKPROOF can only be set by a superuser, and in our test the policy never needed it to use an index.

Is a membership-table RLS policy slow, and which form is fastest?

The IN and EXISTS subquery forms were the slow ones in our test, because both turned into a sequential scan with a hashed subplan. For a user in one 544-row tenant on 1,000,000 rows in PostgreSQL 18.7, a count had a median of 34.8 ms with IN and 128.2 ms with EXISTS, against 0.049 ms with tenant_id = any(array(select ...)) and 0.047 ms with a SECURITY DEFINER function returning the user's tenant ids as an array. The array forms were fastest for counts only: that user's latest 20 took 0.307 to 0.312 ms through a bitmap scan of all 544 rows, against 0.016 ms with a plain tenant_id policy on the same tenant.

Does RLS slow down inserts and updates?

A simple tenant policy added little in our PostgreSQL 18.7 test: inserting 10,000 rows had a median of 23.5 ms under the policy and 21.7 ms on a copy without RLS, and updating 10,000 rows 62.9 ms against 61.7 ms. Membership policies cost more on the update, 78.2 ms with an IN subquery and 82.0 ms with a wrapped SECURITY DEFINER array function. Each statement was rolled back and the table vacuumed before every execution.

How do I run EXPLAIN ANALYZE as the RLS role?

Open a transaction, switch to the application role with SET LOCAL ROLE, set the tenant with set_config and the third argument true, run EXPLAIN (ANALYZE, BUFFERS) on the query, then roll back. A superuser, a role with BYPASSRLS and a table owner without FORCE ROW LEVEL SECURITY all skip the policy, so their plan is not the plan your app gets. Look at whether the policy appears as an Index Cond or a Filter, and at Rows Removed by Filter.

Next articleWordPress Developer Cost in 2026: Sourced Hourly Rates and Project Prices

Get in touch.

Whether you have questions or just want to explore what's possible, we're here to help.