Supabase Architecture: Row Level Security and Realtime at Scale
By: Md Tarek · 20 Oct 2026
Executive Summary & Key Takeaways
- Policy predicates must be rewritten for the planner, not just for correctness. On a 10M-row multi-tenant
orderstable, replacing an inline per-rowapp_private.is_org_member(org_id)call with a set-returningorg_id in (select app_private.authorized_org_ids())predicate dropped the same query from 6,400 ms p50 to 41 ms p50 (~156x) because Postgres materialises the membership set once as a Hashed SubPlan instead of executing aSECURITY DEFINERfunction 10 million times. - `auth.uid()` belongs inside a scalar subquery.
(select auth.uid())forces an InitPlan, so the JWT is parsed fromrequest.jwt.claimsonce per statement rather than once per candidate row; on wide scans and RLS-filtered joins this is routinely a 3-8x p95 improvement and it changes the plan shape from a Filter to an Index Cond. - Postgres Changes fan-out is O(subscribers) with a per-row RLS re-check. Above roughly a few hundred concurrent listeners on a hot table, switch to
realtime.broadcast_changes()inside a trigger: one row write produces one fan-out, RLS is evaluated once at write time, and measured p95 delivery fell from 240 ms to 11 ms at 500 subscribers. - Database webhooks are fire-and-forget.
supabase_functions.http_request(backed bypg_net) has no retries, no ordering guarantee, and a bounded timeout. Production systems need a transactional outbox claimed withFOR UPDATE SKIP LOCKED, exponential backoff with jitter, a dead-letter state, and anIdempotency-Keyheader equal to the outbox row id. - Edge Functions sign and orchestrate; they do not re-implement authorization. Always forward the caller's
Authorizationheader intocreateClient()soauth.uid()populates and RLS still binds, and reserveSUPABASE_SERVICE_ROLE_KEYfor the outbox dispatcher and audit writers. Budget for ~420 ms p95 cold start and keep bundles under ~1.5 MB.
---
The Enterprise Request Path: Where Authorization Actually Happens
Supabase is not a monolith with one auth check. It is four independent data planes, each with its own authorization model, and most "RLS is broken" incident reports are really "we assumed plane A enforced what plane B enforces."
Browser / Mobile (supabase-js v2)
| apikey + JWT (ES256 or HS256)
|
+--> Kong / API gateway --> PostgREST --> Postgres 15
| | |-- RLS policies (auth.uid())
| | |-- WAL (pgoutput)
| | |
+--> Realtime (Elixir/Phoenix) <--------------------+
| |-- Postgres Changes (RLS re-check per subscriber, per row)
| |-- Broadcast (RLS on realtime.messages, private topics)
| |-- Presence (Phoenix Presence CRDT, heartbeat)
|
+--> Edge Functions (Deno) ---> third-party SaaS
^
|
pg_cron --> pg_net --> outbox dispatcher (database webhooks)1. PostgREST + Postgres RLS is the only plane where the database itself is the policy engine. It is authoritative and cannot be bypassed by a malicious client. 2. Realtime is a separate Elixir application with its own Postgres connection. For postgres_changes it re-evaluates your RLS policies *as the subscribing user* for every row it considers broadcasting. For private Broadcast/Presence channels it evaluates RLS on realtime.messages. 3. Database webhooks run inside the transaction's Postgres session via pg_net; they have no user context at all and typically carry a service-level credential. 4. Edge Functions inherit whatever identity you hand them. Forget to forward the JWT and your function silently runs as anon; reach for the service-role key and you silently bypass every policy you wrote.
> War story. A fintech tenant shipped an admin flag into auth.users.raw_user_meta_data (the user_metadata claim) and gated a SELECT policy on auth.jwt() -> 'user_metadata' ->> 'role' = 'admin'. user_metadata is writable by the end user through supabase.auth.updateUser(). A pen-test escalated to full cross-tenant read in under ten minutes. Authorization claims must live in raw_app_meta_data / app_metadata, which only the service role can write.
---
Row Level Security: Policies That Stay Fast at 10M Rows
RLS conditions are injected into the query as ordinary predicates. That means every performance property of a policy is a performance property of a `WHERE` clause — index alignment, selectivity, and evaluation count all matter.
1. Collapse membership checks into a set, not a scalar function
The intuitive policy is a boolean helper called per row. It is also the classic slow path: Postgres calls the function once per candidate row, each call doing its own index probe on org_members.
-- SLOW: one SECURITY DEFINER call per candidate row create policy orders_select_slow on public.orders for select to authenticated using ( app_private.is_org_member(org_id) );
The fix is to make the policy a semi-join against a once-evaluated set:
-- FAST: single hashed SubPlan, then a hash probe per row using ( org_id in (select app_private.authorized_org_ids()) )
Postgres plans this as Hash Semi Join with the subquery as the build side. The membership query runs once; the outer scan does hash probes. Confirm with EXPLAIN (ANALYZE, BUFFERS) that you see Hashed SubPlan / Hash Semi Join and a loops=1 on the inner node.
2. `(select auth.uid())` is not cosmetic
auth.uid() reads the request.jwt.claims GUC and parses JSON. Wrapped in a scalar subquery, the planner hoists it to an InitPlan — one evaluation per statement. Unwrapped, it can be evaluated per row and, more importantly, blocks the predicate from being recognised as an indexable Index Cond. Supabase's own lint (auth_rls_initplan) flags this.
3. Force RLS and revoke the obvious paths
ENABLE ROW LEVEL SECURITY does not apply to the table owner. Migrations run as postgres, which is a superuser in Supabase and also has BYPASSRLS on service_role. Use FORCE ROW LEVEL SECURITY so a stray postgres-owned view or function cannot leak rows, and never expose a table with zero policies and assume it is "locked" — zero policies means deny-all for non-bypass roles, which is correct, but a single accidental to public using (true) opens it to the internet.
4. Recursion is the #1 production outage
A policy on org_members that queries org_members (directly or via a helper that is not SECURITY DEFINER) triggers ERROR 42P17: infinite recursion detected in policy. The escape hatch is a SECURITY DEFINER function owned by postgres — it runs outside RLS — with set search_path = '' and fully qualified names, which also neutralises search_path injection.
---
Realtime: Presence Channels, Authorization, and Fan-Out Economics
Realtime has three primitives with radically different cost models. Choosing the wrong one is the single most common scaling mistake on Supabase.
| Primitive | Delivery | Authorization | Cost model | |---|---|---|---| | postgres_changes | WAL replay per subscriber | RLS re-checked per subscriber, per row | O(rows x subscribers) | | broadcast (DB trigger) | One message to a topic | RLS on realtime.messages at join + send | O(subscribers) fan-out | | presence | CRDT state sync | RLS on realtime.messages | O(state size x subscribers) |
Presence mechanics
Presence is Phoenix Presence: each client holds a keyed entry in a replicated CRDT, and the server reconciles presence_state / presence_diff messages. Clients send a heartbeat; a missed heartbeat window produces a leave. Two rules follow directly from this design:
- Set `presence: { key: userId }`. The default key is random per connection, so a user with three tabs appears three times and your "who is online" counter is wrong by a factor of N.
- Keep the tracked payload small. Every tracked entry is replicated to every subscriber on every diff. Tracking a 4 KB cursor blob in a 500-member room is 2 MB of egress per cursor move.
Private channels and `realtime.messages` RLS
Public channels are unauthenticated. For tenant-scoped presence you must open a private channel, call supabase.realtime.setAuth(jwt) before subscribe(), and write policies against realtime.topic(). Encode the tenant in the topic (org:<uuid>:presence) and parse it defensively — a bad split_part(...)::uuid cast inside a policy will throw on any malformed topic and turn into a 500 at the Realtime gateway.
Why `postgres_changes` gets expensive
When RLS is enabled, Realtime cannot simply forward the WAL record — it must prove the subscribing user is allowed to see that row. It does this by checking the policy for each subscriber. With 40 rows/second and 800 subscribers on a busy table you are asking Postgres to perform 32,000 policy evaluations per second, on top of your application traffic. The symptoms are Realtime lag, postgres_changes backpressure, and WAL retaining longer than expected.
The remedy is to stop using RLS-filtered Postgres Changes as a fan-out mechanism. Broadcast from a trigger instead: the policy is evaluated once, at write time, by the application role, and Realtime only has to route a message.
Also note: for DELETE events you receive only the primary key unless the table is set to REPLICA IDENTITY FULL. Teams regularly ship an optimistic-UI delete that silently no-ops because the payload lacked the columns their reducer needed.
---
Database Webhooks and Edge Functions: Building Durable Delivery
The webhook primitive truth
A Supabase database webhook is a trigger that calls supabase_functions.http_request(...), which enqueues a request into pg_net's background worker. Key properties you must design around:
- It is asynchronous — the HTTP call happens after the transaction, so it cannot roll back the write and cannot see uncommitted data.
- It has no retries. A 503 from your CRM is gone. The response is persisted to
net._http_responsefor debugging, which is useful for forensics but is not a delivery guarantee. - It has a bounded timeout (pg_net default 5,000 ms; Supabase's helper defaults lower). Slow endpoints become silent data loss.
- It has no ordering guarantee across concurrent transactions.
The enterprise answer is the transactional outbox: write the event intent into a table in the *same* transaction as the business change, then drain it from a scheduled worker. Delivery becomes at-least-once, ordering becomes explicit, and failures become observable rows rather than missing side effects.
> War story. A logistics platform lost ~6,300 shipment-status events during a 40-minute downstream outage. The pg_net queue drained, every request 502'd, and nothing recorded the failure. After moving to an outbox, the same outage produced zero lost events and a 4-minute catch-up once the downstream recovered — the visible cost was a dead state on nine poisoned payloads that a human triaged.
Edge Functions as the dispatcher
Deno-based edge functions are a good fit for the drain loop: they run close to the database, they can hold secrets, and they can sign payloads with Web Crypto. Two constraints drive the design: ~420 ms p95 cold start and a 150 s (free) / 400 s (paid) wall-clock cap. That means batch small, never block on a single slow endpoint, and always pass an AbortSignal.timeout() to fetch so a hung connection cannot consume the whole invocation.
---
Practical Implementation
Step 1 — RLS foundation (migration `0001`)
-- ============================================================
-- 0001_rls_foundation.sql | Postgres 15 (Supabase)
-- ============================================================
create schema if not exists app_private;
revoke all on schema app_private from public;
grant usage on schema app_private to authenticated, service_role;
-- Evaluated ONCE per statement. SECURITY DEFINER so it is not
-- itself filtered by RLS on org_members (avoids 42P17 recursion).
create or replace function app_private.authorized_org_ids()
returns setof uuid
language sql
stable
security definer
set search_path = ''
as $$
select m.org_id
from public.org_members m
where m.user_id = (select auth.uid())
and m.revoked_at is null;
$$;
revoke all on function app_private.authorized_org_ids() from public;
grant execute on function app_private.authorized_org_ids() to authenticated;
alter table public.orders enable row level security;
alter table public.orders force row level security;
create policy orders_select on public.orders
for select to authenticated
using ( org_id in (select app_private.authorized_org_ids()) );
create policy orders_insert on public.orders
for insert to authenticated
with check ( org_id in (select app_private.authorized_org_ids()) );
create policy orders_update on public.orders
for update to authenticated
using ( org_id in (select app_private.authorized_org_ids()) )
with check ( org_id in (select app_private.authorized_org_ids()) );
-- Indexes aligned with the policy predicate AND the app access path.
create index if not exists orders_org_created_idx
on public.orders (org_id, created_at desc);
create index if not exists org_members_user_org_live_idx
on public.org_members (user_id, org_id)
where revoked_at is null;Step 2 — Realtime publication, private-topic policies, DB broadcast
-- Publish only tables that actually need Postgres Changes.
alter publication supabase_realtime add table public.orders;
-- Needed so DELETE events carry the full old row, not just the PK.
alter table public.orders replica identity full;
-- Safe topic -> tenant parser: never let a malformed topic raise inside a policy.
create or replace function app_private.topic_org_id(topic text)
returns uuid
language plpgsql
immutable
set search_path = ''
as $$
begin
return (regexp_match(
topic,
'^org:([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}):'
))[1]::uuid;
exception when others then
return null;
end;
$$;
-- Realtime Authorization for private Broadcast / Presence channels.
create policy realtime_org_receive on realtime.messages
for select to authenticated
using (
app_private.topic_org_id(realtime.topic())
in (select app_private.authorized_org_ids())
);
create policy realtime_org_send on realtime.messages
for insert to authenticated
with check (
app_private.topic_org_id(realtime.topic())
in (select app_private.authorized_org_ids())
);
-- One write -> one fan-out. RLS decided once, at write time.
create or replace function public.on_order_status_change()
returns trigger
language plpgsql
security definer
set search_path = ''
as $$
begin
perform realtime.broadcast_changes(
topic_name => 'org:' || new.org_id::text || ':orders',
event => 'order_status',
operation => tg_op,
table_name => tg_table_name,
table_schema => tg_table_schema,
new => new,
old => old
);
return null;
end;
$$;
create trigger order_status_broadcast
after insert or update of status or delete on public.orders
for each row execute function public.on_order_status_change();Step 3 — Transactional outbox + SKIP LOCKED claim
create type public.outbox_status as enum ('pending','processing','delivered','dead');
create table public.outbox (
id uuid primary key default gen_random_uuid(),
payload jsonb not null, -- { target_url, body }
status public.outbox_status not null default 'pending',
attempts int not null default 0,
max_attempts int not null default 8,
next_attempt_at timestamptz not null default now(),
locked_until timestamptz,
last_error text,
created_at timestamptz not null default now()
);
create index outbox_due_idx on public.outbox (next_attempt_at)
where status in ('pending','processing');
alter table public.outbox enable row level security;
-- Intentionally zero policies: deny-all for anon/authenticated.
-- Must live in an exposed schema to be reachable via PostgREST RPC.
create or replace function public.claim_outbox(
p_batch int default 50,
p_lease interval default '30 seconds'
)
returns setof public.outbox
language sql
security definer
set search_path = ''
as $$
update public.outbox o
set status = 'processing',
attempts = o.attempts + 1,
locked_until = now() + p_lease
where o.id in (
select id
from public.outbox
where status in ('pending','processing')
and next_attempt_at <= now()
and (locked_until is null or locked_until < now())
order by next_attempt_at
limit p_batch
for update skip locked
)
returning o.*;
$$;
revoke all on function public.claim_outbox(int, interval) from public, anon, authenticated;
grant execute on function public.claim_outbox(int, interval) to service_role;
-- Business write + event intent are atomic.
create or replace function public.enqueue_webhook(p_url text, p_body jsonb)
returns uuid
language plpgsql
security definer
set search_path = ''
as $$
insert into public.outbox (payload) values (jsonb_build_object('target_url', p_url, 'body', p_body))
returning id;
$$;
-- Drain every 10 seconds via pg_cron + pg_net (service-role bearer).
select cron.schedule('outbox-dispatch', '10 seconds', $$
select net.http_post(
url := 'https://<project-ref>.supabase.co/functions/v1/outbox-dispatch',
headers := jsonb_build_object('content-type','application/json','authorization','Bearer <OUTBOX_DISPATCH_SECRET>'),
body := '{}'::jsonb,
timeout_milliseconds := 20000
);
$$);Step 4 — Edge Function dispatcher (Deno, production-ready)
// supabase/functions/outbox-dispatch/index.ts
// Deploy: supabase functions deploy outbox-dispatch --no-verify-jwt
// (pg_cron cannot mint a Supabase JWT; the shared secret below is the gate.)
import { createClient } from 'jsr:@supabase/supabase-js@2'
const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!
const SERVICE_ROLE = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!
const DISPATCH_TOKEN = Deno.env.get('OUTBOX_DISPATCH_SECRET')!
const WEBHOOK_SECRET = Deno.env.get('WEBHOOK_SIGNING_SECRET')!
const admin = createClient(SUPABASE_URL, SERVICE_ROLE, {
auth: { persistSession: false, autoRefreshToken: false },
})
const BATCH = 50
const TIMEOUT_MS = 5_000
interface OutboxRow {
id: string
attempts: number
max_attempts: number
payload: { target_url: string; body: unknown }
}
const backoffMs = (attempt: number): number =>
Math.min(2 ** attempt * 1_000 + Math.floor(Math.random() * 250), 15 * 60_000)
async function hmacHex(secret: string, message: string): Promise<string> {
const key = await crypto.subtle.importKey(
'raw', new TextEncoder().encode(secret),
{ name: 'HMAC', hash: 'SHA-256' }, false, ['sign'],
)
const sig = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(message))
return Array.from(new Uint8Array(sig)).map((b) => b.toString(16).padStart(2, '0')).join('')
}
async function settle(id: string, patch: Record<string, unknown>): Promise<void> {
const { error } = await admin.from('outbox').update(patch).eq('id', id)
if (error) console.error('outbox_settle_failed', id, error.message)
}
Deno.serve(async (req: Request): Promise<Response> => {
if (req.method !== 'POST') return new Response('method_not_allowed', { status: 405 })
if (req.headers.get('authorization') !== `Bearer ${DISPATCH_TOKEN}`) {
return new Response('unauthorized', { status: 401 })
}
const { data, error } = await admin.rpc('claim_outbox', { p_batch: BATCH })
if (error) {
console.error('claim_outbox_failed', error.message)
return new Response('claim_failed', { status: 500 })
}
const rows = (data ?? []) as OutboxRow[]
if (rows.length === 0) return Response.json({ claimed: 0 })
await Promise.allSettled(rows.map(async (row) => {
const { target_url, body } = row.payload
if (!target_url) {
await settle(row.id, { status: 'dead', last_error: 'missing_target_url' })
return
}
try {
const raw = JSON.stringify(body)
const res = await fetch(target_url, {
method: 'POST',
headers: {
'content-type': 'application/json',
'idempotency-key': row.id,
'x-signature': await hmacHex(WEBHOOK_SECRET, raw),
},
body: raw,
signal: AbortSignal.timeout(TIMEOUT_MS),
})
if (res.ok) {
await settle(row.id, { status: 'delivered', locked_until: null, last_error: null })
return
}
// 4xx (except 429) will never succeed on retry: poison payload.
if (res.status >= 400 && res.status < 500 && res.status !== 429) {
await settle(row.id, { status: 'dead', locked_until: null, last_error: `http_${res.status}` })
return
}
throw new Error(`http_${res.status}`)
} catch (err) {
const message = err instanceof Error ? err.message : 'unknown_error'
const exhausted = row.attempts >= row.max_attempts
await settle(row.id, {
status: exhausted ? 'dead' : 'pending',
locked_until: null,
last_error: message.slice(0, 500),
next_attempt_at: new Date(Date.now() + backoffMs(row.attempts)).toISOString(),
})
}
}))
return Response.json({ claimed: rows.length })
})Step 5 — Client presence channel (supabase-js v2)
import { createClient, type RealtimeChannel } from '@supabase/supabase-js'
const supabase = createClient(
import.meta.env.VITE_SUPABASE_URL,
import.meta.env.VITE_SUPABASE_ANON_KEY,
)
interface Cursor { x: number; y: number; doc: string }
/** Private, tenant-scoped presence. Requires realtime.messages RLS policies. */
export async function joinOrgPresence(
orgId: string,
userId: string,
accessToken: string,
): Promise<RealtimeChannel> {
// MUST precede subscribe() or private channels reject with CHANNEL_ERROR.
await supabase.realtime.setAuth(accessToken)
const channel = supabase.channel(`org:${orgId}:presence`, {
config: {
private: true,
presence: { key: userId }, // one entry per user, not per tab
broadcast: { self: false, ack: true },
},
})
channel
.on('presence', { event: 'sync' }, () => {
const state = channel.presenceState<{ cursor: Cursor; name: string }>()
renderOnline(Object.values(state).flat().map((p) => p.name))
})
.on('presence', { event: 'join' }, ({ key, newPresences }) => {
console.debug('presence_join', key, newPresences.length)
})
.on('presence', { event: 'leave' }, ({ key }) => console.debug('presence_leave', key))
.on('broadcast', { event: 'cursor' }, ({ payload }) => renderCursor(payload as Cursor))
channel.subscribe(async (status, err) => {
if (status === 'SUBSCRIBED') {
await channel.track({ cursor: { x: 0, y: 0, doc: 'default' }, name: 'me' })
}
if (status === 'CHANNEL_ERROR' || status === 'TIMED_OUT') {
// Usually: JWT missing/expired, or realtime.messages RLS denied the topic.
console.error('realtime_subscribe_failed', status, err)
}
})
return channel
}
declare function renderOnline(names: string[]): void
declare function renderCursor(c: Cursor): void---
Performance Benchmarks & Trade-Offs
Measured on Supabase-hosted Postgres 15, 8 vCPU / 32 GB, orders = 10,000,000 rows across 4,000 tenants, org_members = 240,000 rows. Each figure is the median of 50 runs after warmup; p95 across the same 50 runs. Postgres Changes figures at 500 concurrent subscribers, 40 writes/sec, 2 KB payload.
| Layer | Technique | Workload | p50 | p95 | Trade-off | |---|---|---|---|---|---| | RLS | user_id = auth.uid() (unwrapped) | 10M-row scan, single-user filter | 3,180 ms | 6,940 ms | Per-row JWT parse; predicate not pushed into Index Cond | | RLS | user_id = (select auth.uid()) | same | 3.4 ms | 9.1 ms | InitPlan + index scan; requires index on user_id | | RLS | app_private.is_org_member(org_id) per row | tenant aggregate over 10M rows | 6,400 ms | 9,100 ms | Simple to write, catastrophic at scale | | RLS | org_id in (select app_private.authorized_org_ids()) | same | 41 ms | 96 ms | Hashed SubPlan; needs (user_id, org_id) partial index | | Realtime | postgres_changes with RLS | 500 subscribers, 40 writes/s | 95 ms | 240 ms | Per-subscriber, per-row policy check; O(rows x subs) | | Realtime | realtime.broadcast_changes() trigger | same | 4 ms | 11 ms | One fan-out; RLS decided at write time; needs private-topic policies | | Realtime | Presence sync at 500 members | 1 KB tracked payload | 18 ms | 47 ms | O(state x subscribers) egress; keep payloads tiny | | Edge Fn | Cold start (bundle ~1.1 MB) | single invocation | 310 ms | 420 ms | Mitigate with cron warmup and smaller imports | | Edge Fn | Warm invocation, 2 DB round trips | single invocation | 24 ms | 38 ms | Dominated by network RTT to Postgres | | Webhooks | pg_net enqueue inside transaction | adds to write path | <1 ms | 2 ms | Async, no retries, bounded timeout | | Webhooks | Outbox claim (SKIP LOCKED, batch 50) | 50 rows/invocation | 6 ms | 15 ms | At-least-once; needs idempotent consumers |
Decision guide. Use postgres_changes only for low-cardinality admin dashboards (a handful of listeners) or tables you cannot trigger on. Use trigger-driven broadcast_changes for anything user-facing with more than ~100 listeners. Use presence only for coordination state (cursors, typing, online), never as a message bus.
---
Pro-Tips & Common Pitfalls
- Never authorize from `user_metadata`. It is end-user writable via
updateUser(). Useapp_metadata/raw_app_meta_data, writable only by the service role. - Ship the `auth_rls_initplan` and `multiple_permissive_policies` lints in CI. The Supabase CLI exposes them via
supabase db lint; failing the build on new policy warnings catches 80% of slow-policy regressions before merge. - Index every column referenced by a policy predicate, ideally as a composite leading with the tenant key, and verify with
EXPLAIN (ANALYZE, BUFFERS)that you see anIndex Cond, not aFilterwithRows Removed by Filter: 9,99x,xxx. - Always use `set search_path = ''` on `SECURITY DEFINER` functions. Otherwise a caller-controlled
search_pathcan hijack unqualified object references and escalate to superuser context. - `ENABLE` is not enough. Add
FORCE ROW LEVEL SECURITYso the table owner is also constrained; otherwise a view or function owned bypostgresleaks rows outside the policy. - Zero policies means deny-all, not allow-all. Still, audit for
to public using (true)— one permissive policy ORs with everything else and silently opens the table. - **Never
select *into a Realtime payload handler.** Stream row identifiers and re-fetch under RLS; it prevents stale-state bugs and cuts egress materially. - `REPLICA IDENTITY FULL` before you ship optimistic deletes. Without it,
DELETEpayloads contain only the primary key. - Call `realtime.setAuth()` before `subscribe()`. On token refresh, call it again — otherwise private channels start returning
CHANNEL_ERRORan hour into the session. - Realtime reconnects are not resumable. Treat every
SUBSCRIBEDtransition as a cold start: re-track()presence and re-fetch missed state via REST. - Never put `SUPABASE_SERVICE_ROLE_KEY` in a browser bundle or a public edge function. It has
BYPASSRLS. Scope it to the outbox dispatcher and audit writers. - Do not forward the JWT incorrectly. Pass the caller's header verbatim:
createClient(url, anonKey, { global: { headers: { Authorization: req.headers.get('Authorization')! } } }). Omit it and RLS silently evaluates asanon. - Webhooks are not a queue. If you need retries, ordering, or observability, you need an outbox —
net._http_responseis forensics, not a delivery contract. - Set an explicit `AbortSignal.timeout()` on every `fetch` in an edge function. A hung upstream otherwise burns the full 150 s / 400 s wall clock and stalls the batch.
- Poison-payload detection saves your queue. Treat 4xx (except 429) as terminal and mark the row
deadso one malformed payload cannot loop forever.
---
Frequently Asked Questions (FAQ)
Does Supabase Realtime respect Row Level Security?
Yes, but only where you have configured it. For postgres_changes, Realtime evaluates your table's RLS policies as the subscribing user and only delivers rows that user could SELECT. For private Broadcast and Presence channels, RLS policies on the realtime.messages table gate who may join and who may publish, keyed off realtime.topic(). Public channels are unauthenticated and have no RLS — never put tenant data on them. The important caveat is cost, not correctness: RLS-checked Postgres Changes run one policy evaluation per subscriber per row, so migrate high-fan-out feeds to realtime.broadcast_changes() triggers where the policy is evaluated once at write time.
Are Supabase database webhooks retried on failure?
No. supabase_functions.http_request enqueues a request through the pg_net extension, which fires asynchronously with a bounded timeout (pg_net default 5,000 ms) and does not retry, reorder, or guarantee delivery. The response is stored in net._http_response for debugging, which is useful for incident forensics but is not a delivery contract. For anything that must not be lost, write an outbox row inside the same transaction as the business change, drain it with a FOR UPDATE SKIP LOCKED claim plus exponential-backoff-with-jitter retries, mark terminal failures as dead for human triage, and send an Idempotency-Key header so consumers can deduplicate on retries.
Should I write `auth.uid()` or `(select auth.uid())` in RLS policies?
Use (select auth.uid()). auth.uid() parses the request.jwt.claims GUC, and without the scalar subquery wrapper the planner may evaluate it once per candidate row and fail to push the predicate into an index condition. Wrapping it in a subquery forces an InitPlan, so the JWT is parsed exactly once per statement. Apply the same reasoning to any expensive helper: prefer a set-returning function consumed as col in (select helper()) (Hashed SubPlan, one build) over a scalar boolean helper invoked per row. Verify the resulting plan has loops=1 on the inner node using EXPLAIN (ANALYZE, BUFFERS).
