Supabase Architecture: Row Level Security, Realtime & Edge Functions
By: Md Tarek · 18 Oct 2026
Executive Summary & Key Takeaways
- One authorization layer, not three. PostgREST, Realtime, and Edge Functions all resolve to the same Postgres roles (
anon,authenticated,service_role). If your RLS policies are correct, every surface is correct; if they are wrong, every surface leaks at the same time. - Wrap `auth.uid()` in a scalar subquery.
using ((select auth.uid()) = user_id)converts a per-row function call into a single InitPlan. On a 2.1M-row table we measured p95 drop from 182 ms to 6.4 ms once a matching composite index existed. - Postgres Changes does a per-subscriber RLS check; Broadcast-from-Database does not. Above roughly 500 concurrent subscribers on a hot table, fan-out via
realtime.broadcast_changes()plus arealtime.messagespolicy is 5-8x cheaper and lower-latency than per-row replication with per-subscriber authorization. - Presence is ephemeral and reconnect amplification is real. A 25s heartbeat with
presence.keycollapsed touser_idkeeps a 2,000-member channel near 1.4 MB of resident state and prevents ghost users from duplicate browser tabs. - Database Webhooks are fire-and-forget.
pg_netdispatches asynchronously with a hard 5s timeout and no built-in retries or dead-letter queue. Pair every webhook with a transactional outbox table and an idempotency key on the receiver.
Enterprise Supabase architecture is deceptively simple at the surface: one managed Postgres, four data planes, and a JWT. The complexity lives entirely in the authorization model. Below is the internals-level view we use when reviewing production Supabase deployments handling 10M+ requests per day.
The Request Path: One Postgres, Four Data Planes
browser / mobile (anon key + user JWT)
|
+----------------+----------------+-----------------+
| | | |
PostgREST GoTrue Realtime Supabase Storage
/rest/v1 /auth/v1 /realtime/v1 /storage/v1
| | |
| | Elixir / Phoenix Channels
| | + WAL replication reader (Postgres Changes)
| | + Presence (CRDT-style, in-memory, no replay)
| | |
Edge Functions ---+ | |
(Deno isolates, | | |
region pinned) | | |
+-----------+----+----------------+
v
+--------------------------------------------------+
| Postgres 15/16 (managed) |
| roles: anon / authenticated / service_role |
| GUC: request.jwt.claims, request.method |
| RLS: policies -> single source of truth |
| publication supabase_realtime |
| pg_net: async HTTP queue for webhooks |
+--------------------------------------------------+Every HTTP request that reaches PostgREST runs inside a transaction that begins with something morally equivalent to:
set local role authenticated;
set local request.jwt.claims = '{"sub":"<uuid>","role":"authenticated","app_metadata":{"tenant_id":"<uuid>"}}';That is the entire trick. auth.uid() is a thin wrapper over current_setting('request.jwt.claims', true)::jsonb ->> 'sub'. PostgREST never invents authorization logic of its own; it delegates to RLS. Realtime does the same for Postgres Changes: when a subscriber joins a channel bound to a table, Realtime evaluates the table's SELECT policy under that subscriber's claims for each changed row before delivering it. Edge Functions are the outlier, because a function holding service_role bypasses RLS entirely and becomes its own trust boundary.
This is the architectural reason Supabase is safe by default and dangerous by configuration. A single missing policy on public.projects is not a PostgREST bug, a Realtime bug, and an RPC bug; it is one bug with three symptoms.
Production war story. A B2B analytics product shipped a policy of the form using (tenant_id = (auth.jwt() -> 'user_metadata' ->> 'tenant_id')::uuid). It passed every functional test. Under load, p99 on GET /rest/v1/events hit 4.1 s and the read replica saturated. explain (analyze, buffers) showed a sequential scan over 4.2M rows plus a JSONB cast evaluated per row. Three fixes compounded: cast the claim once via (select ...), add (tenant_id, created_at desc) as a covering index, and move the tenant claim out of user_metadata (which users can rewrite through auth.updateUser) into the memberships table. p99 fell to 41 ms.
Designing Multi-Tenant RLS That Actually Scales
Policy anatomy that matters
| Clause | Behaviour | Gotcha | |---|---|---| | USING | Filters rows visible to SELECT, UPDATE, DELETE | Not applied to INSERT | | WITH CHECK | Validates rows written by INSERT/UPDATE | Omit it and a user can move a row into another tenant | | TO authenticated | Restricts the policy to a role | Omitting it evaluates the policy for anon too, wasting cycles | | AS RESTRICTIVE | ANDs with all permissive policies | One stray restrictive policy silently returns zero rows | | FORCE ROW LEVEL SECURITY | Applies RLS to the table owner | Without it, dashboard/migration roles bypass RLS |
Never let a policy query the table it protects
A policy on memberships that joins memberships recurses: Postgres raises 42P17 infinite recursion detected in policy. The fix is a security definer helper in a schema that is not exposed through PostgREST, with a locked-down search_path:
create schema if not exists app_private; create or replace function app_private.current_tenant_ids() returns setof uuid language sql stable security definer set search_path = '' -- prevents search_path hijacking as $$ select m.tenant_id from public.memberships m where m.user_id = (select auth.uid()) $$; revoke execute on function app_private.current_tenant_ids() from public, anon; grant execute on function app_private.current_tenant_ids() to authenticated;
Note stable, not volatile: a stable function is evaluated once per statement and can be inlined by the planner, while a volatile one is re-executed per row. This single keyword is frequently the difference between a 6 ms and a 180 ms query.
Indexes must mirror predicates, not just foreign keys
If your predicate is tenant_id in (select app_private.current_tenant_ids()), then create index on public.projects (tenant_id) is mandatory. For soft-delete or time-series tables, a partial index is better: create index on public.events (tenant_id, created_at desc) where deleted_at is null;. Verify with explain (analyze, buffers) on the *generated* PostgREST query, not on your hand-written SQL.
Claims: choose the source deliberately
| Claim source | Set by | User-writable? | Safe for authorization | |---|---|---|---| | app_metadata | Admin API / server | No | Yes | | user_metadata | auth.updateUser() from the client | Yes | No | | memberships table | Your application | No (RLS-protected) | Yes - preferred for multi-tenant | | Custom tenant_id JWT claim | Custom Access Token Hook | No | Yes, but stale until token refresh |
Test policies in CI, per role, per operation
Ship a pgTAP suite that impersonates each role inside a transaction and rolls back:
begin;
set local role authenticated;
set local request.jwt.claims = '{"sub":"<member-uuid>","role":"authenticated"}';
select results_eq(
$$ select count(*) from public.projects where tenant_id = '<tenant-a>' $$,
$$ values (3::bigint) $$,
'member sees exactly their tenant rows'
);
rollback;Run the matrix (anon, authenticated, service_role) x (select, insert, update, delete) x (own tenant, foreign tenant) on every migration. A missing policy is a compile error in this model; make it a CI failure too.
Realtime at Scale: Presence Channels and Broadcast-from-Database
How Realtime is built
Supabase Realtime is an Elixir application on Phoenix Channels. Each client holds one WebSocket and multiplexes many logical channels over it. Three primitives ride on top:
1. Postgres Changes - a replication reader tails the supabase_realtime publication and, for each change, evaluates the table's SELECT policy under each subscriber's JWT claims before delivering. Authorization cost is O(changes x subscribers). 2. Broadcast - pure pub/sub on a topic, with no database read. Authorization happens once at join, via RLS on realtime.messages, for private channels. 3. Presence - Phoenix.Presence semantics: a presence_state snapshot on join, then presence_diff deltas containing joins and leaves. State is in-memory, has no replay, and is never persisted to Postgres.
Heartbeats default to roughly 25s from realtime-js (heartbeatIntervalMs), with a server-side reaper that evicts members whose heartbeat lapses. Presence keys are last-write-wins with a logical clock, which is why two browser tabs from the same user produce two presence entries unless you set presence.key to a stable identifier.
The scaling move: authorize in SQL, broadcast from a trigger
Postgres Changes is the ergonomic default and the wrong default above a few hundred subscribers on a hot table. The alternative is realtime.broadcast_changes(), which pushes the change from inside the transaction into an already-authorized topic, so Realtime performs zero per-row authorization queries:
-- Private channels must be enabled for realtime.messages RLS to apply.
create policy tenant_members_can_read_topic
on realtime.messages for select to authenticated
using (
(select realtime.topic()) like 'tenant:%'
and split_part((select realtime.topic()), ':', 2)::uuid
in (select app_private.current_tenant_ids())
);
create policy tenant_members_can_publish
on realtime.messages for insert to authenticated
with check (
split_part((select realtime.topic()), ':', 2)::uuid
in (select app_private.current_tenant_ids())
);Now projects changes fan out at object-graph cost rather than auth cost. In our load tests (500 steady subscribers, 50 writes/s on a hot table, single 4 vCPU Realtime node), p95 delivery latency was 38 ms with broadcast-from-database versus 210 ms with Postgres Changes, and Postgres CPU time per delivered change dropped by roughly 85% because the per-subscriber SELECT disappeared.
Presence sizing arithmetic
Presence cost is driven by member count and metadata size, and it is quadratic on reconnect because every client receives the full diff. A 2,000-member channel with 700-byte roster entries means roughly 1.4 MB resident in the Realtime node, plus a 1.4 MB sync event per joining client. Keep metadata to an ID, display name, and a status enum; never store a serialized object graph.
Production war story. A deploy forced 3,000 WebSocket reconnects inside 20 seconds. Join rate limiting kicked in, clients retried immediately, and the connection storm displaced presence state for users who never disconnected. The fix was three lines of client code: exponential backoff with full jitter (base * 2^attempt * random()), presence.key set to user_id, and a visibilitychange listener that unsubscribes on tab hide. Throughput of the deploy went from a 6-minute brownout to a non-event.
Webhooks and Edge Functions: Durable Compute at the Boundary
Database Webhooks are not a message queue
A Supabase Database Webhook is a trigger calling supabase_functions.http_request(...), which enqueues into pg_net. Dispatch is asynchronous and does not block your transaction, which is excellent. What it does not give you: retries, exponential backoff, ordering guarantees, or a dead-letter queue. The request times out at 5s and failures surface only in net._http_response, which almost nobody monitors.
For anything with a financial or customer-visible side effect, write to an outbox table in the same transaction and let a pg_cron dispatcher drain it. You keep transactional consistency, gain retries, and can reconcile every request against net._http_response.
Edge Functions: Deno isolates with sharp edges
Edge Functions run on Deno with V8 isolates, region-pinned, with a 256 MB memory ceiling and a wall-clock limit measured in tens of seconds (150s at the time of writing). Cold starts p95 around 200-300 ms; warm invocations in-region land near 11-27 ms. Two failure modes dominate production incidents:
1. Connection exhaustion. Opening a direct connection to Postgres on port 5432 per invocation melts the ~200-connection ceiling at a few hundred requests per second. Always go through Supavisor in transaction mode (port 6543) with prepare: false, because transaction pooling does not support prepared statements. 2. Trust confusion. A function with service_role can read every tenant. It must verify its caller explicitly - a user JWT via auth.getUser(), or a signature/shared secret for machine callers - and it must never return raw service-role data without re-applying the tenant filter.
Practical Implementation
1. Schema, RLS policies, and Realtime authorization
-- ============================================================
-- Tenant core
-- ============================================================
create table public.memberships (
tenant_id uuid not null references public.tenants(id) on delete cascade,
user_id uuid not null references auth.users(id) on delete cascade,
role text not null check (role in ('owner','admin','member','viewer')),
primary key (tenant_id, user_id)
);
create table public.projects (
id uuid primary key default gen_random_uuid(),
tenant_id uuid not null references public.tenants(id) on delete cascade,
owner_id uuid not null references auth.users(id),
name text not null,
deleted_at timestamptz,
created_at timestamptz not null default now()
);
create index projects_tenant_created_idx
on public.projects (tenant_id, created_at desc)
where deleted_at is null;
create index memberships_user_tenant_idx
on public.memberships (user_id, tenant_id);
-- ============================================================
-- Policies
-- ============================================================
alter table public.projects enable row level security;
alter table public.projects force row level security; -- owner included
create policy projects_select on public.projects
for select to authenticated
using ( tenant_id in (select app_private.current_tenant_ids()) );
create policy projects_insert on public.projects
for insert to authenticated
with check (
tenant_id in (select app_private.current_tenant_ids())
and owner_id = (select auth.uid())
);
create policy projects_update on public.projects
for update to authenticated
using ( app_private.has_tenant_role(tenant_id, array['owner','admin']) )
with check ( app_private.has_tenant_role(tenant_id, array['owner','admin']) );
-- Soft delete only: nobody gets a hard DELETE policy.
create policy projects_soft_delete on public.projects
for update to authenticated
using ( app_private.has_tenant_role(tenant_id, array['owner']) );
-- ============================================================
-- Supabase Realtime authorization (private channels)
-- ============================================================
create policy tenants_read_realtime
on realtime.messages for select to authenticated
using (
(select realtime.topic()) like 'tenant:%'
and split_part((select realtime.topic()), ':', 2)::uuid
in (select app_private.current_tenant_ids())
);
create policy tenants_publish_realtime
on realtime.messages for insert to authenticated
with check (
split_part((select realtime.topic()), ':', 2)::uuid
in (select app_private.current_tenant_ids())
);
-- Broadcast from the database: no per-subscriber authorization query.
create or replace function public.on_project_change()
returns trigger
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant uuid := coalesce(new.tenant_id, old.tenant_id);
begin
perform realtime.broadcast_changes(
'tenant:' || v_tenant::text, -- topic
tg_op, -- event name
tg_op, -- operation
tg_table_name,
tg_table_schema,
new,
old
);
return null; -- AFTER trigger
end;
$$;
create trigger projects_broadcast
after insert or update or delete on public.projects
for each row execute function public.on_project_change();2. Transactional outbox + webhook dispatch
create table public.webhook_outbox (
id bigint generated always as identity primary key,
tenant_id uuid not null,
event_type text not null,
payload jsonb not null,
status text not null default 'pending'
check (status in ('pending','dispatched','delivered','failed')),
attempts int not null default 0,
request_id bigint, -- pg_net request id for reconciliation
next_attempt_at timestamptz not null default now(),
created_at timestamptz not null default now()
);
create index webhook_outbox_due_idx
on public.webhook_outbox (next_attempt_at)
where status = 'pending';
-- Enqueue in the SAME transaction as the business write.
create or replace function public.enqueue_project_webhook()
returns trigger
language plpgsql
security definer
set search_path = ''
as $$
begin
insert into public.webhook_outbox (tenant_id, event_type, payload)
values (
new.tenant_id,
'project.created',
jsonb_build_object('id', new.id, 'tenant_id', new.tenant_id, 'name', new.name)
);
return null;
end;
$$;
create trigger projects_enqueue_webhook
after insert on public.projects
for each row execute function public.enqueue_project_webhook();
-- Dispatch worker: run under pg_cron every 10 seconds.
create or replace function public.dispatch_webhook_outbox()
returns void
language plpgsql
security definer
set search_path = ''
as $$
declare
r record;
v_request_id bigint;
begin
for r in
select * from public.webhook_outbox
where status = 'pending' and next_attempt_at <= now()
order by id
limit 50
for update skip locked -- safe under concurrent workers
loop
v_request_id := net.http_post(
url := 'https://<project-ref>.supabase.co/functions/v1/project-events',
headers := jsonb_build_object(
'Content-Type', 'application/json',
'x-idempotency-key', r.id::text
),
body := jsonb_build_object('type', r.event_type, 'tenant_id', r.tenant_id, 'data', r.payload),
timeout_milliseconds := 5000
);
update public.webhook_outbox
set status = 'dispatched',
request_id = v_request_id,
attempts = attempts + 1
where id = r.id;
end loop;
end;
$$;A second reconciler function joins net._http_response on request_id to promote rows to delivered or to reschedule with backoff (next_attempt_at = now() + make_interval(secs => least(300, power(2, attempts)::int))).
3. Edge Function with explicit trust boundary and idempotency
// supabase/functions/project-events/index.ts
// Deploy: supabase functions deploy project-events --no-verify-jwt
// JWT/secret verification happens below so that both human callers and
// pg_net webhooks (which carry a shared secret) can reach the same handler.
import { createClient } from 'npm:@supabase/[email protected]';
import postgres from 'npm:[email protected]';
declare const EdgeRuntime: { waitUntil(p: Promise<unknown>): void };
const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
const WEBHOOK_SHARED_SECRET = Deno.env.get('WEBHOOK_SHARED_SECRET')!;
const DOWNSTREAM_URL = Deno.env.get('DOWNSTREAM_URL')!;
const DB_POOLER_URL = Deno.env.get('SUPABASE_DB_POOLER_URL')!; // Supavisor :6543
// Transaction pooling mode does not support prepared statements.
const sql = postgres(DB_POOLER_URL, {
prepare: false,
max: 5,
idle_timeout: 20,
connect_timeout: 5,
});
const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
auth: { persistSession: false, autoRefreshToken: false },
});
class HttpError extends Error {
constructor(readonly status: number, message: string, readonly code = 'bad_request') {
super(message);
}
}
const json = (body: unknown, status = 200) =>
new Response(JSON.stringify(body), {
status,
headers: { 'content-type': 'application/json' },
});
async function authorize(req: Request): Promise<void> {
const shared = req.headers.get('x-webhook-secret');
if (shared !== null) {
if (shared !== WEBHOOK_SHARED_SECRET) {
throw new HttpError(401, 'invalid_secret', 'unauthorized');
}
return;
}
const header = req.headers.get('authorization') ?? '';
const jwt = header.replace(/^Bearer /i, '');
if (!jwt) throw new HttpError(401, 'missing_token', 'unauthorized');
const { data, error } = await admin.auth.getUser(jwt);
if (error || !data.user) throw new HttpError(401, 'invalid_token', 'unauthorized');
}
type ProjectEvent = {
type: 'project.created' | 'project.updated';
tenant_id: string;
data: Record<string, unknown>;
};
Deno.serve(async (req: Request): Promise<Response> => {
const startedAt = performance.now();
if (req.method !== 'POST') return json({ error: 'method_not_allowed' }, 405);
try {
await authorize(req);
const body = (await req.json()) as ProjectEvent;
if (!body?.type || !body?.tenant_id) {
throw new HttpError(400, 'invalid_payload');
}
const idempotencyKey = req.headers.get('x-idempotency-key') ?? crypto.randomUUID();
// Atomic claim: a duplicate delivery inserts zero rows and short-circuits.
const claimed = await sql<{ id: string }[]>`
insert into public.webhook_deliveries (idempotency_key, event_type, tenant_id, status)
values (${idempotencyKey}, ${body.type}, ${body.tenant_id}, 'processing')
on conflict (idempotency_key) do nothing
returning id
`;
if (claimed.length === 0) return json({ ok: true, deduplicated: true });
const deliveryId = claimed[0].id;
const res = await fetch(DOWNSTREAM_URL, {
method: 'POST',
headers: { 'content-type': 'application/json', 'idempotency-key': idempotencyKey },
body: JSON.stringify(body),
signal: AbortSignal.timeout(4000),
});
if (!res.ok) {
await sql`
update public.webhook_deliveries
set status = 'failed', last_error = ${'upstream_' + res.status}
where id = ${deliveryId}
`;
throw new HttpError(502, 'downstream_failed', 'upstream_error');
}
await sql`
update public.webhook_deliveries
set status = 'delivered', delivered_at = now()
where id = ${deliveryId}
`;
// Must not block the response. Fire-and-forget audit trail.
EdgeRuntime.waitUntil(
admin
.from('audit_log')
.insert({
tenant_id: body.tenant_id,
action: body.type,
latency_ms: Math.round(performance.now() - startedAt),
})
.then(() => undefined),
);
return json({ ok: true, delivery_id: deliveryId });
} catch (err) {
const status = err instanceof HttpError ? err.status : 500;
const code = err instanceof HttpError ? err.code : 'internal_error';
console.error(JSON.stringify({ level: 'error', code, msg: String(err) }));
return json({ error: code }, status);
}
});4. Client-side presence with a stable key
import { createClient } from '@supabase/supabase-js';
const supabase = createClient(import.meta.env.VITE_SUPABASE_URL, import.meta.env.VITE_SUPABASE_ANON_KEY, {
realtime: {
heartbeatIntervalMs: 25_000,
params: { eventsPerSecond: 10 },
},
});
export function joinTenantRoom(tenantId: string, user: { id: string; name: string }) {
const channel = supabase.channel(`tenant:${tenantId}`, {
config: {
private: true, // required for realtime.messages RLS to apply
presence: { key: user.id }, // one presence entry per user, not per tab
broadcast: { self: false, ack: true },
},
});
channel
.on('presence', { event: 'sync' }, () => {
renderRoster(Object.values(channel.presenceState()).flat());
})
.on('presence', { event: 'join' }, ({ key }) => markOnline(key))
.on('presence', { event: 'leave' }, ({ key }) => markOffline(key))
.on('broadcast', { event: 'cursor' }, ({ payload }) => paintCursor(payload))
.subscribe(async (status) => {
if (status === 'SUBSCRIBED') {
await channel.track({ name: user.name, at: Date.now() });
}
});
return () => { void supabase.removeChannel(channel); };
}Keep the tracked payload under a few hundred bytes. Presence metadata is multiplied by member count on every sync, so a 2 KB payload in a 2,000-member room costs ~4 MB per client sync.
Performance Benchmarks & Trade-Offs
Indicative numbers from a Supabase Pro project (Postgres 15, 4 vCPU / 8 GB, eu-central-1), 10M-row events table at 12% tenancy skew, 500 concurrent Realtime subscribers, server-side timings excluding client TLS. Reproduce with your own cardinality before trusting any of it.
| Technique | p50 | p95 | Ceiling (single node) | Trade-off | |---|---|---|---|---| | RLS inline auth.uid(), no index | 41 ms | 182 ms | ~120 req/s | Trivial to write, sequential scan per request | | RLS (select auth.uid()) + composite index | 1.9 ms | 6.4 ms | ~4,800 req/s | Requires index discipline and stable helpers | | Extra AS RESTRICTIVE role-gate policy | +0.3 ms | +0.9 ms | Negligible | More policies to reason about, clearer admin paths | | Realtime Postgres Changes (per-row RLS) | - | 210 ms | ~500 subscribers on a hot table | Zero extra code, authorization cost scales with subscriber count | | Realtime Broadcast-from-Database | - | 38 ms | ~5,000 subscribers | Needs a trigger, private channels, and realtime.messages policy | | PostgREST RPC (security definer) | 4.1 ms | 9.0 ms | ~3,000 req/s | Logic lives in SQL, harder to unit test in TypeScript | | Edge Function (warm, same region) | 11 ms | 27 ms | ~1,200 req/s per isolate pool | Cold start 200-300 ms p95; requires pooled connections | | Database Webhook (pg_net dispatch) | 6 ms | 12 ms | Fire-and-forget | No retries, no DLQ, 5s timeout, silent failures |
| Dimension | Postgres Changes | Broadcast-from-Database | Edge Function | |---|---|---|---| | Authorization point | Per subscriber, per row | Once, at channel join | Explicit, per invocation | | Delivery guarantee | At-most-once on a live channel | At-most-once | At-least-once with idempotency key | | Serverless cold start | N/A (long-lived) | N/A (long-lived) | 200-300 ms p95 | | Best fit | Low-fan-out internal dashboards | High-fan-out tenant rooms, live cursors | Signed third-party integrations, orchestration |
Pro-Tips & Common Pitfalls
- Do not put authorization data in `user_metadata`. End users can rewrite it with
auth.updateUser(). Useapp_metadata, a Custom Access Token Hook claim, or - best - amembershipstable. - Always set `FORCE ROW LEVEL SECURITY` on tenant tables, or the table owner (which is what your dashboard and migration role often act as) reads everything.
- Always pair `USING` with `WITH CHECK` on `UPDATE`. Omitting
WITH CHECKlets a user updatetenant_idto a tenant they cannot read. - `security definer` helpers need `set search_path = ''` plus
revoke execute from public, anon. Without a pinnedsearch_path, a malicious schema can shadow objects inside your function. - Watch for policy recursion (
42P17). Any policy that reads its own table needs a definer helper. - Never ship `service_role` to a browser or mobile bundle. It bypasses RLS globally; treat it as a root credential and rotate it after any leak.
- Enable the Realtime publication and `replica identity full` explicitly for tables using Postgres Changes, otherwise old records arrive empty.
- Private channels are opt-in. Without
private: trueand arealtime.messagespolicy, any authenticated client can subscribe to any topic string. - Bound your presence metadata. Ghost users and N-squared sync cost trace back to oversized payloads and unstable presence keys.
- Never hold a 5432 connection per Edge Function invocation. Use Supavisor transaction mode on 6543 with
prepare: falseand a small per-isolatemax. - Monitor `net._http_response`. Webhook failures are invisible otherwise, and there is no dead-letter queue to fall back on.
- Beware webhook feedback loops where a webhook writes to a table that owns a webhook trigger. Add a source column or an
is_echoguard. - Set `statement_timeout` and PostgREST `db-max-rows`. One unbounded
select *on a tenant table can exhaust a 4 vCPU instance before p99 alerts fire.
Frequently Asked Questions (FAQ)
Does Supabase Realtime enforce Row Level Security on Postgres Changes?
Yes. For Postgres Changes, Realtime impersonates each subscriber's JWT claims and evaluates the table's SELECT policy against every changed row before delivering it, so a subscriber only receives rows the same user could read through PostgREST. This is also why Postgres Changes scales worse than Broadcast: authorization cost is O(changes x subscribers). If a table exceeds a few hundred concurrent subscribers, move to realtime.broadcast_changes() with a realtime.messages RLS policy, which authorizes once at channel join.
Why is my RLS policy slow, and how do I fix it?
The two dominant causes are per-row function evaluation and unindexed predicates. Rewrite using (user_id = auth.uid()) as using (user_id = (select auth.uid())) so the claim is read once as an InitPlan, mark helper functions stable and security definer, and create an index whose leading column matches the policy predicate - not merely the foreign key. Then verify with explain (analyze, buffers) on the exact query PostgREST generates, and keep pg_stat_statements enabled to catch planner regressions after migrations.
Can I use the `service_role` key inside Supabase Edge Functions?
Yes, and it is the standard pattern for privileged work, but the function then becomes your trust boundary. It must verify every caller explicitly - admin.auth.getUser(jwt) for human callers, or a shared secret / HMAC signature for machine callers such as pg_net webhooks - and it must re-apply tenant scoping itself, because service_role bypasses RLS entirely. Use --no-verify-jwt only when you implement that verification in code, never as a shortcut.
