Getting Started

Postgres & Supabase Backend Setup

One schema, run once, works identically on Supabase's managed Postgres or your own Neon, RDS, CockroachDB, or self hosted instance. Every change is logged as a full row with an owner, so global rows reach everyone and per user rows reach only their owner. The changelog itself is closed to direct reads. What differs is how a change reaches the browser. Supabase does that part for you and everyone else needs one small bridge process, given in full below.

Which adapter am I actually using?

The schema on this page is shared, but the client side adapter is not. Pick based on where your database actually lives, not on "I am using Postgres." createSupabaseAdapter() talks directly to Supabase's own managed Realtime WebSocket service. It has nothing to connect to on Neon, RDS, CockroachDB, or a self hosted instance, because none of those run an equivalent service. If your database is Supabase, use createSupabaseAdapter() and Step 5 below. If it is anything else, use createWebSocketAdapter(), createSocketIOAdapter() or createSseAdapter() and Step 6 below. There is no scenario where createSupabaseAdapter() is the right choice for a non Supabase database.

Prerequisites
  • An existing Flux app already wired up on the client side, with the Supabase adapter chosen (Supabase path) or a WebSocket, Socket.IO or SSE adapter chosen (any other Postgres path).
  • A Postgres database: a Supabase project, or your own Neon, RDS, CockroachDB or self hosted instance.
  • Enough privileges on that database to create tables, functions, triggers and to revoke grants.
  • A primary key column named id on every table you will track.
  • A decision for every table you will track: is it GLOBAL (the same rows for everyone, safe to show to any visitor) or PER USER (rows belong to one owner)?
1

The changelog table

Run this once. On Supabase paste it into the SQL Editor. Everywhere else run it through your normal migration tooling. Nothing in it is Supabase specific. The changelog is what makes deletions catchable at all, and it keeps only the latest state per row so it does not grow per edit. The user_id column records who is allowed to read each entry. The block ends by enabling RLS and revoking every grant, so the table cannot be read through the REST API even with the anon key.
sql_editor_or_migration.sql
1-- Run once. On Supabase paste it into the SQL Editor, everywhere else use your
2-- normal migration tooling. Nothing in this block is Supabase specific.
3
4-- One row per entity. A new mutation on a row REPLACES its changelog entry
5-- instead of appending another, so the table stays small on a live app.
6-- Deletions are caught here because a plain SELECT can never tell "row was
7-- deleted" from "row never existed."
8--
9-- user_id decides who may read the entry:
10-- null a GLOBAL row, readable by every client (public tables)
11-- a real uuid a PER USER row, readable only by that user
12-- all zero uuid a PER USER row whose owner could not be resolved, readable by nobody
13create table if not exists public.flux_changelog (
14 id bigint generated always as identity primary key,
15 table_name text not null,
16 row_id text not null,
17 user_id uuid,
18 op text not null check (op in ('INSERT', 'UPDATE', 'DELETE')),
19 row_data jsonb,
20 changed_at timestamptz not null default now()
21);
22
23-- Already running the older table that had no user_id? This adds the column.
24alter table public.flux_changelog add column if not exists user_id uuid;
25
26-- Serves the catch up read: one table, newer than an anchor, in order.
27create index if not exists flux_changelog_table_changed_id_idx
28 on public.flux_changelog (table_name, changed_at, id);
29
30-- Serves the trigger's per write lookup and dedup delete. Without it every
31-- tracked write scans the changelog. An older two column index with this name
32-- is dropped first so the new definition takes its place.
33drop index if exists public.flux_changelog_table_row_idx;
34create index if not exists flux_changelog_table_row_idx
35 on public.flux_changelog (table_name, row_id, id desc);
36
37-- Close the front door. The table lives in the public schema, so the REST API
38-- exposes it. With RLS on, no policy, and every grant revoked, nobody can read
39-- or write it directly. The SECURITY DEFINER trigger and delta functions are
40-- owned by the table owner, so they bypass RLS and keep working.
41alter table public.flux_changelog enable row level security;
42revoke all on table public.flux_changelog from public, anon, authenticated;
Revoking access stops direct Realtime subscriptions to the changelog

Flux subscribes to your tracked tables, never to flux_changelog itself. If you added the changelog to the supabase_realtime publication and something of yours subscribes to it directly, the revokes above will stop those events. Run check g in Step 9 before deploying.

2

Global rows versus per user rows

Every entry in the changelog has one of three owners, decided by flux_resolve_owner() at the moment the row changes. A global row has a null user_id. It is the same for every client, so pricing tables, blog posts and currency rates belong here, and a logged out visitor may catch up on them. A per user row stores its owner's uuid. Only that user's catch up and live push ever receive it, so projects, profiles and anything private belong here. If a per user row's owner cannot be resolved, it gets the all zero nobody uuid, which matches no real user, so the row is never shared by mistake.
Which tables are global is decided in exactly one place, flux_is_global_table(). The owner function and the upgrade step both read from it, so the list can never disagree with itself.
sql_editor_or_migration.sql
1-- The ONE place that decides which tables are global. Rows of these tables
2-- have no owner (user_id null) and every caller receives them, including
3-- logged out callers if you grant them the delta functions. To make another
4-- table global, add it here and nowhere else.
5create or replace function public.flux_is_global_table(p_table text)
6returns boolean
7language sql
8immutable
9set search_path to 'public'
10as $function$
11 select p_table in ('blog_posts', 'plan_pricing', 'currency_rates');
12$function$;
13
14revoke all on function public.flux_is_global_table(text) from public, anon, authenticated;
The delta function in Step 5 reads auth.uid() and returns rows where user_id is null or equals the caller. A logged out caller therefore sees global rows only. On a bridge backend the listener does the same job at broadcast time, using the owner carried in the NOTIFY.
sql_editor_or_migration.sql
1-- Decides, per table, who may read a row. The trigger calls this for every
2-- change. Adapt the cases to your schema.
3--
4-- Return null the row is global (see flux_is_global_table)
5-- Return a user uuid the row belongs to that user and nobody else may read it
6-- Return all zeros the owner could not be resolved, so no user receives it
7--
8-- A table with no rule raises an error on purpose. A table you forgot can
9-- never become public by accident, the first write to it fails loudly.
10create or replace function public.flux_resolve_owner(p_table text, p_row jsonb)
11returns uuid
12language plpgsql
13security definer
14set search_path to 'public'
15as $function$
16declare
17 v_user_id uuid;
18 c_nobody constant uuid := '00000000-0000-0000-0000-000000000000';
19begin
20 -- Global tables never have an owner. Nothing user related is looked up.
21 if public.flux_is_global_table(p_table) then
22 return null;
23 end if;
24
25 case p_table
26 -- Per user tables: the owner is stored on the row.
27 when 'projects' then
28 v_user_id := (p_row ->> 'user_id')::uuid;
29
30 -- The row is the user's own record.
31 when 'profiles' then
32 v_user_id := (p_row ->> 'id')::uuid;
33
34 -- Child tables: the owner is the owner of the parent row. If a cascade
35 -- already removed the parent, the lookup finds nothing and the owner
36 -- falls back to "nobody". The trigger then reuses the owner from the
37 -- row's previous changelog entry, so the real owner still receives the
38 -- delete.
39 when 'project_domains' then
40 select pr.user_id into v_user_id
41 from public.projects pr
42 where pr.id = (p_row ->> 'project_id')::uuid;
43
44 else
45 raise exception
46 'flux_resolve_owner: table % is not registered. Add it to flux_is_global_table() or give it an owner rule.',
47 p_table;
48 end case;
49
50 return coalesce(v_user_id, c_nobody);
51end;
52$function$;
53
54-- SECURITY DEFINER functions in the public schema are callable as RPCs by
55-- default. This one reveals who owns a row, so only the trigger may run it.
56revoke all on function public.flux_resolve_owner(text, jsonb) from public, anon, authenticated;
A global table is a public table

Rows of a global table go to every client that can call the delta function, and each entry carries the full row. If a table holds anything not meant for every visitor, such as unpublished drafts or internal settings, do not list it in flux_is_global_table(). Give it an owner rule instead, or do not track it. The owner function raises an error for any table without a rule, so a table you forgot fails on its first write instead of leaking. Keep that behavior. For child tables, resolve the owner through the parent, as project_domains does above.

3

The trigger: full rows, one entry per row

The trigger writes the owner and the full row on every change and replaces the previous entry for that row. Inserts and updates store the whole record, deletes store just an id. There are no field level diffs, so a catch up row is always a complete record the client can apply directly. A row that was inserted but not yet seen by a client stays an INSERT even if it is edited again, so the client never receives an UPDATE for a row it has never had. When a cascade removes a child row after its parent, the trigger reuses the owner from that row's previous entry, so the real owner still receives the delete.
sql_editor_or_migration.sql
1-- The trigger function. Every entry stores the FULL row, never a diff, so a
2-- client that applies it always receives a complete record.
3--
4-- INSERT full row
5-- UPDATE full row (the newest state)
6-- DELETE just {"id": ...}, which is all a client needs to remove a record
7--
8-- Assumes each tracked table has a primary key column named "id".
9create or replace function public.flux_log_change()
10returns trigger
11language plpgsql
12security definer
13set search_path to 'public'
14as $function$
15declare
16 v_row jsonb;
17 pk_value text;
18 v_op text;
19 v_data jsonb;
20 v_owner uuid;
21 v_id bigint;
22 v_existing_op text;
23 v_existing_owner uuid;
24 v_had_existing boolean;
25 c_nobody constant uuid := '00000000-0000-0000-0000-000000000000';
26begin
27 if TG_OP = 'DELETE' then
28 v_row := to_jsonb(OLD);
29 else
30 v_row := to_jsonb(NEW);
31 end if;
32
33 pk_value := v_row ->> 'id';
34
35 -- Flux tracks rows by a primary key column named id. Without it the dedup
36 -- below matches nothing, so refuse the write with a readable message.
37 if pk_value is null then
38 raise exception
39 'flux_log_change: table % has no "id" value. Flux tracks rows by a primary key column named id.',
40 TG_TABLE_NAME;
41 end if;
42
43 v_owner := public.flux_resolve_owner(TG_TABLE_NAME, v_row);
44
45 -- Latest surviving entry for this row (single state keeps only one).
46 select c.op, c.user_id
47 into v_existing_op, v_existing_owner
48 from public.flux_changelog c
49 where c.table_name = TG_TABLE_NAME
50 and c.row_id = pk_value
51 order by c.id desc
52 limit 1;
53 v_had_existing := found;
54
55 if TG_OP = 'DELETE' then
56 v_op := 'DELETE';
57 v_data := jsonb_build_object('id', pk_value);
58
59 -- Cascade deletes on per user tables: the parent row is already gone, so
60 -- the owner cannot be looked up. Reuse the owner from the previous entry
61 -- so the owner still receives the delete. Global tables return null and
62 -- never enter this branch.
63 if v_owner = c_nobody and v_had_existing and v_existing_owner is not null then
64 v_owner := v_existing_owner;
65 end if;
66
67 elsif TG_OP = 'UPDATE' then
68 v_op := 'UPDATE';
69 v_data := v_row;
70
71 -- A row the client has not seen yet (a pending INSERT) stays an INSERT.
72 if v_had_existing and v_existing_op = 'INSERT' then
73 v_op := 'INSERT';
74 end if;
75
76 else
77 v_op := 'INSERT';
78 v_data := v_row;
79 end if;
80
81 -- Single state: only the newest entry per row survives.
82 delete from public.flux_changelog
83 where table_name = TG_TABLE_NAME
84 and row_id = pk_value;
85
86 -- clock_timestamp() is when the trigger ran. The column default now() is
87 -- when the transaction began. Using the trigger time narrows the window the
88 -- five second overlap has to cover. Only the commit time would close it.
89 insert into public.flux_changelog (table_name, row_id, user_id, op, row_data, changed_at)
90 values (TG_TABLE_NAME, pk_value, v_owner, v_op, v_data, clock_timestamp())
91 returning id into v_id;
92
93 -- Only the bridge path in Step 6 listens to this. NOTIFY payloads are capped
94 -- at 8000 bytes, so only the changelog id, the table and the owner travel.
95 -- On a Supabase only setup nothing listens, and you can delete this statement.
96 perform pg_notify('flux_changes', json_build_object(
97 'id', v_id, 'table', TG_TABLE_NAME, 'user_id', v_owner
98 )::text);
99
100 if TG_OP = 'DELETE' then
101 return OLD;
102 end if;
103 return NEW;
104end;
105$function$;
106
107-- Only the trigger itself should ever run this.
108revoke all on function public.flux_log_change() from public, anon, authenticated;
109
110-- Attach to every table you want realtime and catch up on. Copy this block
111-- per table and swap the table name in both lines. The trigger name matters,
112-- flux_reconcile only answers for tables that carry flux_changelog_trigger.
113drop trigger if exists flux_changelog_trigger on public.your_table;
114create trigger flux_changelog_trigger
115 after insert or update or delete on public.your_table
116 for each row execute function public.flux_log_change();
Single state, full rows, not full history

Each mutation replaces that row's entry, so flux_changelog holds at most one entry per entity. If you need an audit trail of every intermediate change, this schema is not it. Keep a separate append only log alongside it. One consequence to know: if a row's owner changes, the entry carries only the new owner, so the previous owner is never told the row left. Design owner rules so a row's owner does not change.

Security notes before enabling this on every table

Do not add a public SELECT policy to flux_changelog, and do not grant it back. Entries hold full row snapshots and would expose every logged change. RLS on with no policy and no grants is correct. The SECURITY DEFINER functions are the only sanctioned read path, and they filter by caller themselves.

The trigger raises an error when a row has no id, which aborts that write. Write once to every tracked table in a staging project before enabling this in production.

Per user filtering is only as correct as your owner rules. A wrong case in flux_resolve_owner() shows one user's rows to another, so test each table with two different accounts before shipping.

4

What actually differs: reaching the browser, not the schema

Postgres has no concept of pushing a change to a connected browser. LISTEN and NOTIFY only reach other database connections. Supabase closes that gap for you: enable Replication on a table and its managed Realtime service broadcasts every change over a WebSocket it already runs, filtered per subscriber by RLS. Every other provider gives you the database half only. The bridge from NOTIFY to a client connection is something you build once, as a small always on process. Step 5 covers Supabase and Step 6 covers everyone else.
5

On Supabase: enable Replication, then install the delta functions

One statement per tracked table turns on managed Realtime broadcasting:
supabase_sql_editor.sql
1-- Turns on Supabase's managed Realtime broadcast for a TRACKED table (the
2-- ones that carry the trigger). The dashboard toggle under Database,
3-- Replication does the same thing.
4alter publication supabase_realtime add table public.your_table;
5
6-- Do NOT add flux_changelog itself. It is closed to direct access on purpose.
That is the whole live push path. createSupabaseAdapter() subscribes to the Realtime channel and needs nothing more from you for live events. Catch up on reconnect uses three functions: the single table delta, a batch version that serves every table in one HTTP request, and the reconcile function that confirms deletions the delta window cannot see. The delta functions return their answer as the RPC result, so it reaches only the user who asked.
supabase_sql_editor.sql
1-- Delta catch up, batch catch up and reconcile. Run after Steps 1 to 3.
2
3-- The reply is the RPC RESULT, so it reaches only the caller. Rows are filtered
4-- by the CALLER: their own per user rows plus global rows (user_id is null),
5-- never another user's. SECURITY DEFINER is required because flux_changelog
6-- has RLS enabled and every grant revoked.
7--
8-- These replace the older versions that returned void and broadcast the reply
9-- with realtime.send on a shared topic. Dropping the old signatures removes
10-- that path.
11drop function if exists public.flux_request_delta(text, text, bigint, integer);
12drop function if exists public.flux_request_delta_batch(jsonb);
13
14create or replace function public.flux_request_delta(
15 p_table text,
16 p_since_ms bigint,
17 p_limit integer default 2000
18)
19returns jsonb
20language plpgsql
21security definer
22set search_path to 'public'
23as $function$
24declare
25 -- Must stay below the cleanup retention (14 days) so a gap can never
26 -- straddle a purge.
27 c_retention_ms constant bigint := 13::bigint * 24 * 60 * 60 * 1000;
28
29 -- server_now is reported BEHIND the real clock, so a transaction that began
30 -- before this read but commits after it is delivered again next time.
31 -- Applying a row twice is harmless.
32 c_overlap_ms constant bigint := 5000;
33 c_max_limit constant integer := 5000;
34
35 v_caller uuid := auth.uid(); -- null for logged out callers: global rows only
36 v_now_ms bigint := (extract(epoch from clock_timestamp()) * 1000)::bigint;
37 v_limit integer := least(greatest(coalesce(p_limit, 2000), 1), c_max_limit);
38 v_rows jsonb := '[]'::jsonb;
39 v_count integer := 0;
40 v_too_old boolean := false;
41begin
42 -- A missing anchor must never be read as "nothing changed".
43 if p_table is null or p_since_ms is null then
44 raise exception 'flux_request_delta: p_table and p_since_ms are required';
45 end if;
46
47 if p_since_ms < v_now_ms - c_retention_ms then
48 v_too_old := true;
49 else
50 with page as (
51 select c.id, c.row_id, c.op, c.row_data, c.changed_at
52 from public.flux_changelog c
53 where c.table_name = p_table
54 and c.changed_at > to_timestamp(p_since_ms / 1000.0)
55 -- global rows (user_id null) or this caller's own rows, never another user's
56 and (c.user_id is null or c.user_id = v_caller)
57 order by c.changed_at asc, c.id asc
58 limit v_limit + 1
59 )
60 select
61 count(*),
62 coalesce(
63 jsonb_agg(
64 jsonb_build_object(
65 'op', p.op,
66 'row_id', p.row_id,
67 'data', jsonb_build_object('id', p.row_id) || coalesce(p.row_data, '{}'::jsonb),
68 'timestamp', (extract(epoch from p.changed_at) * 1000)::bigint
69 )
70 order by p.changed_at asc, p.id asc
71 ),
72 '[]'::jsonb
73 )
74 into v_count, v_rows
75 from page p;
76
77 -- More rows than we are willing to send: refuse a partial delta so the
78 -- client refetches instead of claiming coverage over missing rows.
79 if v_count > v_limit then
80 v_too_old := true;
81 v_rows := '[]'::jsonb;
82 end if;
83 end if;
84
85 return jsonb_build_object(
86 'rows', v_rows,
87 'server_now', v_now_ms - c_overlap_ms,
88 'too_old', v_too_old,
89 'uid', v_caller
90 );
91end;
92$function$;
93
94-- One HTTP request for every table. Takes [{ "table": ..., "since_ms": ... }]
95-- and returns { "<table>": { rows, server_now, too_old, uid }, ... }.
96-- since_ms is parsed as numeric and floored, so a fractional epoch value can
97-- never break the bigint cast. A total row budget keeps one call bounded: once
98-- it is spent, remaining tables answer too_old and are refetched.
99create or replace function public.flux_request_delta_batch(p_requests jsonb)
100returns jsonb
101language plpgsql
102security definer
103set search_path to 'public'
104as $function$
105declare
106 c_total_budget constant integer := 10000;
107 c_per_table constant integer := 2000;
108
109 v_caller uuid := auth.uid();
110 v_now_ms bigint := (extract(epoch from clock_timestamp()) * 1000)::bigint;
111 v_budget integer := c_total_budget;
112 r jsonb;
113 v_reply jsonb;
114 v_out jsonb := '{}'::jsonb;
115begin
116 if jsonb_typeof(p_requests) <> 'array' then
117 raise exception 'flux_request_delta_batch: p_requests must be a json array';
118 end if;
119 if jsonb_array_length(p_requests) > 50 then
120 raise exception 'flux_request_delta_batch: too many requests (max 50)';
121 end if;
122
123 for r in select * from jsonb_array_elements(p_requests) loop
124 if (r ->> 'table') is null or (r ->> 'since_ms') is null then
125 raise exception 'flux_request_delta_batch: every request needs a table and since_ms';
126 end if;
127
128 if v_budget <= 0 then
129 v_reply := jsonb_build_object(
130 'rows', '[]'::jsonb, 'server_now', v_now_ms - 5000, 'too_old', true, 'uid', v_caller
131 );
132 else
133 v_reply := public.flux_request_delta(
134 r ->> 'table',
135 floor((r ->> 'since_ms')::numeric)::bigint,
136 least(c_per_table, v_budget)
137 );
138 v_budget := v_budget - jsonb_array_length(v_reply -> 'rows');
139 end if;
140
141 v_out := v_out || jsonb_build_object(r ->> 'table', v_reply);
142 end loop;
143
144 return v_out;
145end;
146$function$;
147
148-- Which of these local ids no longer exist on the server? SECURITY INVOKER on
149-- purpose: RLS applies, so an id the caller can no longer see is reported as
150-- deleted for THEM. Only tables that carry the flux trigger are allowed.
151create or replace function public.flux_reconcile(p_table text, p_local_ids text[])
152returns text[]
153language plpgsql
154security invoker
155set search_path to 'public'
156as $function$
157declare
158 v_missing text[];
159begin
160 if not exists (
161 select 1
162 from pg_trigger t
163 join pg_class c on c.oid = t.tgrelid
164 join pg_namespace n on n.oid = c.relnamespace
165 where not t.tgisinternal
166 and t.tgname = 'flux_changelog_trigger'
167 and n.nspname = 'public'
168 and c.relname = p_table
169 ) then
170 raise exception 'flux_reconcile: "%" is not a flux tracked table', p_table;
171 end if;
172
173 execute format(
174 'select coalesce(
175 array(
176 select unnest($1)
177 except
178 select t.id::text from public.%I t where t.id::text = any($1)
179 ),
180 ''{}''::text[]
181 )',
182 p_table
183 )
184 into v_missing
185 using p_local_ids;
186
187 return v_missing;
188end;
189$function$;
190
191-- PostgREST callers need explicit EXECUTE. Logged in users only by default.
192revoke all on function public.flux_request_delta(text, bigint, integer) from public, anon, authenticated;
193revoke all on function public.flux_request_delta_batch(jsonb) from public, anon, authenticated;
194revoke all on function public.flux_reconcile(text, text[]) from public, anon;
195
196grant execute on function public.flux_request_delta(text, bigint, integer) to authenticated;
197grant execute on function public.flux_request_delta_batch(jsonb) to authenticated;
198grant execute on function public.flux_reconcile(text, text[]) to authenticated;
199
200-- Logged out visitors catching up on GLOBAL tables (blog_posts, plan_pricing,
201-- currency_rates): uncomment to allow. They only ever receive global rows.
202-- grant execute on function public.flux_request_delta(text, bigint, integer) to anon;
203-- grant execute on function public.flux_request_delta_batch(jsonb) to anon;
204-- grant execute on function public.flux_reconcile(text, text[]) to anon;
This is the exact shape of the reply. The adapter turns it into one outcome per channel:
flux_request_delta result
1// What flux_request_delta returns as the RPC RESULT. Nothing is broadcast, so
2// only the caller who made the request ever receives it.
3{
4 rows: [
5 {
6 op: 'INSERT' | 'UPDATE' | 'DELETE',
7 row_id: '662f...',
8 data: { id: '662f...', ...fullRow }, // DELETE: { id } only
9 timestamp: 1718000001234 // epoch ms, server clock
10 }
11 ],
12 server_now: 1718000099000, // becomes the new sync anchor (already 5 seconds behind)
13 too_old: false, // true: the server will not send a partial delta
14 uid: '3f1c...' | null // who this reply was built for (null: logged out)
15}
16
17// flux_request_delta_batch takes [{ table, since_ms }, ...] and returns one of
18// the objects above per table:
19// { "projects": { rows, server_now, too_old, uid }, "licenses": { ... } }
20
21// Outcome the adapter reports:
22// rows applied applied
23// no rows confirmed current (a quiet table is a valid answer)
24// too_old = true too old, the client refetches the channel
25// RPC error or no reply failed, the gap stays open and the client refetches
The delta function must be SECURITY DEFINER, not INVOKER

flux_changelog has RLS enabled and every grant revoked by design. An INVOKER version runs as the calling role and is refused by RLS. The call either errors or returns an empty rows array, which a client would read as "nothing changed." Use SECURITY DEFINER as shown, keep the explicit GRANT EXECUTE to authenticated, and let the function filter by auth.uid() itself.

Catch up replies are private to the caller

Older versions of these functions returned nothing and broadcast the reply with realtime.send on a topic shared by every client subscribed to that table. Anyone could listen in on other users' replies. The current functions return the rows as the RPC result instead, so no shared topic exists. The reply also carries the uid it was built for, so an adapter can discard a reply that was prepared for a different session. Installing this step drops the old signatures, and with them the broadcast path. Between running the SQL and deploying the matching client, an older client cannot catch up and falls back to refetching.

Live Realtime respects RLS, the DIY path does not

Supabase's postgres_changes broadcasts are filtered per subscriber by the RLS policies that already govern that table, so a client only receives changes to rows it could SELECT. That is a real advantage over the bridge in Step 6, where you filter by owner yourself. Keep real RLS policies on your tracked tables, because the changelog filtering only covers catch up.

6

On any other Postgres: the bridge process, in full

This is the piece that does not exist on Supabase and cannot be skipped elsewhere: a small, always on process holding one dedicated LISTEN connection and translating each NOTIFY into a call against the registry your WebSocket, Socket.IO or SSE page already built. It reads the owner from the entry and passes it along, so a per user row reaches only its owner's connections and a global row reaches everyone. The trigger from Step 3 already sends the NOTIFY this process listens for.
server/postgres_listener.js
1// server/postgres_listener.js
2//
3// The bridge a non Supabase Postgres needs and Supabase does not. LISTEN and
4// NOTIFY only reach OTHER DATABASE CONNECTIONS, never a browser, so one
5// dedicated connection is held open, hears the NOTIFY fired by the trigger,
6// and forwards it into the registry your transport page already built.
7//
8// Every row forwarded here is a FULL row (INSERT and UPDATE) or { id } (DELETE).
9// There are no partial updates, so a client can replace or merge safely.
10//
11// The NOTIFY carries user_id. A null owner means a GLOBAL row, sent to every
12// subscriber. A uuid owner means a PER USER row, sent only to that user's
13// sockets. The all zero "nobody" uuid matches no real user, so such a row is
14// delivered to no one. The registry on the transport page does the filtering.
15
16const { Client } = require('pg')
17const { broadcastToWs } = require('./broadcast') // swap for io.to(room).emit or broadcastToSse
18
19function tableToChannel(table) {
20 // However you map table to Flux channel name. Simplest case: identical.
21 return table
22}
23
24async function startPostgresListener() {
25 // A dedicated client, NOT a pooled one. See the callout below this block.
26 const listenerClient = new Client({ connectionString: process.env.DATABASE_URL })
27 await listenerClient.connect()
28 await listenerClient.query('LISTEN flux_changes')
29
30 console.log('[pg] Listening for flux_changes notifications')
31
32 listenerClient.on('notification', async (msg) => {
33 let payload
34 try {
35 payload = JSON.parse(msg.payload)
36 } catch {
37 return
38 }
39
40 // Single state: this always fetches the row's CURRENT logged entry, even
41 // if several edits landed before the listener got to this one.
42 const { rows } = await listenerClient.query(
43 'SELECT row_id, op, row_data, user_id, changed_at FROM flux_changelog WHERE id = $1',
44 [payload.id]
45 )
46 const row = rows[0]
47 if (!row) return
48
49 const op = row.op === 'INSERT' ? 'CREATE' : row.op
50
51 broadcastToWs(
52 tableToChannel(payload.table),
53 {
54 entity: payload.table,
55 id: row.row_id,
56 op,
57 data: row.op === 'DELETE' ? { id: row.row_id } : row.row_data,
58 timestamp: new Date(row.changed_at).getTime(),
59 source: 'my_postgres_listener',
60 },
61 row.user_id // null: everyone, uuid: only that user
62 )
63 })
64
65 listenerClient.on('error', (err) => {
66 console.error('[pg] Listener connection error:', err)
67 // A dropped LISTEN connection means live updates silently stop until this
68 // reconnects. Add real reconnect with backoff before shipping.
69 })
70}
71
72module.exports = { startPostgresListener }
server/postgres_listener.py
1# server/postgres_listener.py
2#
3# Same bridge using asyncpg's native LISTEN and NOTIFY support. Forwards into
4# the registry your chosen transport already built.
5#
6# Rows are FULL rows (INSERT and UPDATE) or {"id": ...} (DELETE). The NOTIFY
7# carries user_id: None means a GLOBAL row sent to everyone, a uuid means a
8# PER USER row sent only to that user's connections. The all zero "nobody"
9# uuid matches no real user, so such a row is delivered to no one.
10
11import asyncio
12import json
13import asyncpg
14from broadcast import broadcast_to_ws # or sse_registry or socketio's sio
15
16def table_to_channel(table: str) -> str:
17 return table
18
19async def start_postgres_listener(dsn: str):
20 # A dedicated, unpooled connection. LISTEN needs one connection held open
21 # for the whole process lifetime.
22 conn = await asyncpg.connect(dsn)
23
24 async def on_notify(connection, pid, channel, payload):
25 data = json.loads(payload)
26
27 row = await conn.fetchrow(
28 "SELECT row_id, op, row_data, user_id, changed_at FROM flux_changelog WHERE id = $1",
29 data["id"],
30 )
31 if not row:
32 return
33
34 op = "CREATE" if row["op"] == "INSERT" else row["op"]
35 row_data = json.loads(row["row_data"]) if row["row_data"] else {}
36 owner = str(row["user_id"]) if row["user_id"] else None
37
38 await broadcast_to_ws(
39 table_to_channel(data["table"]),
40 {
41 "entity": data["table"],
42 "id": row["row_id"],
43 "op": op,
44 "data": {"id": row["row_id"]} if row["op"] == "DELETE" else row_data,
45 "timestamp": int(row["changed_at"].timestamp() * 1000),
46 "source": "my_postgres_listener",
47 },
48 owner,
49 )
50
51 await conn.add_listener("flux_changes", on_notify)
52 print("[pg] Listening for flux_changes notifications")
53
54 # This connection only listens. Keep the coroutine alive.
55 while True:
56 await asyncio.sleep(3600)
Connection pooling breaks LISTEN, use a direct connection

If your DATABASE_URL points at a transaction mode pooler (PgBouncer, Supabase's pooler on port 6543, RDS Proxy in transaction mode), LISTEN silently does not work through it. The pooler can hand your session's connection to another client between transactions, so notifications never reach the one that issued LISTEN. The listener needs its own connection string pointed at the database directly (session mode, port 5432).

Catch up on the bridge path is served by your transport

The Supabase delta functions above are not used on this path. Your WebSocket, Socket.IO or SSE server answers catch up itself, by running the same query as flux_request_delta against flux_changelog with the connected user's id: rows where user_id is null or user_id = that user, ordered by changed_at, answering too old past the retention window. The server connects as a trusted role, so it must apply that filter itself. Reconcile is the flux_reconcile query run under that user's identity.

Start the listener alongside your transport server, before accepting connections, so no client can connect before the bridge is listening.
7

Retention

Single state dedup keeps the changelog far smaller than an append only log, but it is not free. Every distinct row you ever touched keeps one entry, and a deleted row leaves a tombstone that is never replaced. Retention is a pair of numbers that must stay consistent: cleanup removes entries older than 14 days, and the delta function answers too old for any anchor older than 13 days. A client offline longer than that refetches the channel, and flux_changelog_cleanup refuses to keep less than 14 days, so a scheduler passing a smaller number cannot break catch up. The function is also locked to the database owner. Without that lock, anyone with the anon key could empty the changelog.
sql_editor_or_migration.sql (optional)
1-- Optional. With single state dedup flux_changelog grows only with the number
2-- of distinct rows ever touched, plus one tombstone per deletion that is never
3-- replaced. Cleanup mostly matters for those tombstones.
4--
5-- Retention is a pair: this cleanup purges entries older than 14 days, and
6-- flux_request_delta refuses (too_old) any anchor older than 13 days. The one
7-- day gap means a catch up can never be answered from a half purged window.
8-- The function below refuses to keep less than 14 days, so a scheduler that
9-- passes a smaller number cannot delete data the delta still needs. If you
10-- raise one number, raise the other, and set the client deltaRetentionMs to
11-- match the smaller one.
12--
13-- On Supabase pg_cron is available under Database, Extensions. Elsewhere you
14-- may need to install it, or call the same DELETE from an external scheduler.
15create or replace function public.flux_changelog_cleanup(retain_days integer default 14)
16returns void
17language plpgsql
18security definer
19set search_path to 'public'
20as $function$
21begin
22 delete from public.flux_changelog
23 where changed_at < now() - make_interval(days => greatest(coalesce(retain_days, 14), 14));
24end;
25$function$;
26
27-- Without this, anyone holding the anon key could call
28-- flux_changelog_cleanup(0) and empty the changelog, and every client would be
29-- told "nothing changed". pg_cron runs as postgres and is not affected.
30revoke all on function public.flux_changelog_cleanup(integer) from public, anon, authenticated;
31
32select cron.schedule('flux_changelog_cleanup', '0 3 * * *',
33 $$select public.flux_changelog_cleanup(14)$$);
8

Upgrading from an older schema

If you already ran an earlier version of this schema, run the statements below once after Steps 1 to 3. They remove the old diff function, which is callable by anyone with the anon key until dropped, remove the old delta signatures, replace pending partial rows with full rows, and give every per user entry an owner. Entries whose owner cannot be recovered go to nobody, so they are never shown to everyone.
sql_editor_or_migration.sql (one time)
1-- Only if you ran an OLDER version of this schema. Run once, after Steps 1 to 3.
2
3-- 1. Functions from older versions that are no longer used. The diff function
4-- is callable by anyone with the anon key until it is dropped.
5drop function if exists public.flux_jsonb_diff(jsonb, jsonb);
6drop function if exists public.flux_request_delta(text, text, bigint, integer);
7drop function if exists public.flux_request_delta_batch(jsonb);
8
9-- 2. Replace every pending UPDATE entry with the current full row, so no
10-- client ever receives a partial record. Repeat per tracked table.
11update public.flux_changelog c
12set row_data = to_jsonb(t)
13from public.your_table t
14where c.table_name = 'your_table'
15 and c.op = 'UPDATE'
16 and c.row_id = t.id::text;
17
18-- 3. Fill the owner on existing per user entries.
19update public.flux_changelog
20set user_id = public.flux_resolve_owner(table_name, row_data)
21where op <> 'DELETE'
22 and not public.flux_is_global_table(table_name);
23
24-- 4. Any per user entry still without an owner (old deletes carry no row to
25-- resolve one from) would be visible to everyone. Give it to "nobody".
26-- Affected clients refetch through reconcile or too_old instead.
27update public.flux_changelog
28set user_id = '00000000-0000-0000-0000-000000000000'
29where user_id is null
30 and not public.flux_is_global_table(table_name);
9

Testing your setup

Run these checks after deploying. They confirm every entry is a full record, that global and per user rows are separated, that the delta function does not error for a caller with no auth.uid(), that reconcile reports missing ids, and that the privileges and RLS are what this page promises.
sql_editor_or_psql
1-- a) Every INSERT or UPDATE entry carries a full record with its id.
2-- Expected: no rows.
3select table_name, row_id, op
4from public.flux_changelog
5where op in ('INSERT', 'UPDATE') and not (row_data ? 'id');
6
7-- b) Global tables have no owner, per user tables always have one.
8-- Expected: no rows.
9select table_name, user_id
10from public.flux_changelog
11where (public.flux_is_global_table(table_name) and user_id is not null)
12 or (not public.flux_is_global_table(table_name) and user_id is null)
13limit 20;
14
15-- c) The delta function does not error for a caller with no auth.uid(). The
16-- SQL Editor has none, so this only returns global rows.
17select public.flux_request_delta(
18 'currency_rates',
19 (extract(epoch from now() - interval '2 days') * 1000)::bigint
20);
21
22-- d) Reconcile reports ids the server does not have.
23select public.flux_reconcile('projects', array['definitely not an id']);
24
25-- e) Who can run what. Expected: flux_request_delta, flux_request_delta_batch
26-- and flux_reconcile are open to authenticated only. Every other flux
27-- function is open to nobody. Any anon_can_run = true deserves a look.
28select p.proname,
29 has_function_privilege('anon', p.oid, 'execute') as anon_can_run,
30 has_function_privilege('authenticated', p.oid, 'execute') as authed_can_run
31from pg_proc p join pg_namespace n on n.oid = p.pronamespace
32where n.nspname = 'public' and p.proname like 'flux%'
33order by p.proname;
34
35-- f) The changelog is closed. Expected: rls_on = true, both can_read = false.
36select c.relrowsecurity as rls_on,
37 has_table_privilege('anon', c.oid, 'select') as anon_can_read,
38 has_table_privilege('authenticated', c.oid, 'select') as authed_can_read
39from pg_class c where c.oid = 'public.flux_changelog'::regclass;
40
41-- g) The changelog is not published to Realtime. Expected: no rows.
42select * from pg_publication_tables
43where pubname = 'supabase_realtime' and tablename = 'flux_changelog';
On Supabase, change a row in a table with Replication on and confirm your Flux app receives it. The Realtime Inspector in your dashboard shows raw broadcast traffic if you want to rule out the client first. Then sign in as two different users, change a per user row for one of them, and confirm the other receives nothing, live or on catch up. Delete a parent row that has children, such as a project with domains, and confirm the owner receives the child deletes too. If live updates work but catch up comes back empty after you changed something offline, check that the delta functions are SECURITY DEFINER and granted to authenticated, not a client bug.
On any other provider, test the bridge in isolation first. Fire a manual notification and confirm your listener logs it:
psql or SQL editor
1-- In a second psql session or the SQL Editor: fire a manual NOTIFY to confirm
2-- your listener process receives them, independent of any real trigger.
3select pg_notify('flux_changes', '{"id": 0, "table": "test", "user_id": null}');
Once that round trips, change a row in a table with the trigger attached and confirm the event reaches your WebSocket, Socket.IO or SSE test client, and only the right user's client for a per user table.
Production considerations before you ship this

One listener process, not one per server instance. If you run several copies of your backend behind a load balancer, run the Step 6 bridge in only one of them, or each replica will LISTEN and broadcast every change again.

Listener reconnect. The minimal error handler only logs a dropped connection. Production code should reconnect with backoff and issue LISTEN flux_changes again. Single state dedup softens the blow, because catch up on reconnect fetches each row's current entry, but live push stops silently in the meantime.

Owner rules are your access control. Whether a client sees a row is decided by flux_resolve_owner() and flux_is_global_table(), on both the Supabase path and the bridge path. Review both whenever you attach the trigger to a new table.

Lock down every flux function. SECURITY DEFINER functions in the public schema are callable as RPCs by default. Run check e in Step 9 after every change. Only the delta functions and reconcile should be open to signed in users.

Server clock only. Timestamps and the sync anchor come from the database clock. The five second overlap in server_now exists so a transaction that commits late is delivered again on the next catch up. Applying a row twice is harmless. A transaction that stays open longer than the overlap before committing can still be missed, so keep transactions on tracked tables short.

Rate of catch up. The batch function caps at 50 tables per call, 2000 entries per table and 10000 entries per call. Past that the answer is too old and the client refetches, which is the correct outcome.

This page covers the database and delivery layer only. For the server code the Step 6 bridge forwards into, see getting_started/websocket, getting_started/socketio or getting_started/sse. For the deeper explanation of sync anchors and delta catch up across every transport, see core_concepts/sync_anchors.

Powered by Flux