Realtime
Subscribe to inserts, updates and deletes on your tables over a WebSocket. Each change is checked against the subscriber’s read access before it is sent. Broadcast and presence channels can be made private, with rules in your schema.
Pre-1.0: APIs and config may change between releases.
What is sent
The realtime service reads changes from Postgres logical replication, so every committed INSERT, UPDATE and DELETE is seen, whether it came from the API, Studio, a function or plain SQL. There is nothing to switch on per table. A change is only sent to clients subscribed to that table.
| Event | new | old |
|---|---|---|
INSERT | the whole row | null |
UPDATE | the whole row | the whole row as it was |
DELETE | null | the whole row as it was |
Every table Supatype manages has REPLICA IDENTITY FULL, so the write-ahead log carries the whole previous row. A table set up outside Supatype keeps Postgres’s default identity, and its old can hold only the key.
Values arrive with the same types and formats as a REST read. A BigInt column becomes a native bigint, and Decimal and Money stay exact strings. Json columns arrive as the parsed value, not as JSON text. timestamptz arrives as ISO 8601 with a T and a full offset, such as 2024-01-01T12:00:00+00:00, which every browser parses; timestamp is 2024-01-01T12:00:00 and timetz has its full offset. Fractional seconds keep their microseconds. Arrays of any type arrive as arrays, as REST sends them: integer[] and double precision[] hold numbers, boolean[] holds booleans, bigint[] and numeric[] hold exact strings, and text[], uuid[] and date[] hold strings. Before 0.9.3 every array arrived as Postgres’s text form, such as "{1,2}". Before 0.9.3 Json was a string and timestamptz was 2024-01-01 12:00:00+00, which Safari and Firefox read as Invalid Date; code that called JSON.parse on a Json column now gets the value itself.
Read access
Realtime follows the same access rules as the REST API. For each change and each subscriber, the service checks with the subscriber’s token, inside Postgres:
- Insert and update: the row is selected again, by its primary key, as the subscriber. If the
readrule hides it, the change is not sent. The check sees the row as it is at that moment, so a row deleted straight after it was inserted is not sent either. With the Native provider or your own Postgres, thereadrule is applied to the row in the change instead. - Delete: the
readrule is applied to the deleted row, as the subscriber, so a subscriber only hears of deletes of rows they could read. A delete on a table withoutREPLICA IDENTITY FULL, or without a Supatypereadrule, is not sent. - Field rules: a column the subscriber may not read under a field rule arrives as
null, in bothnewandold. A filter on such a column is matched against the masked value, so it cannot be used to test a hidden value. - Service role: sees every change unmasked.
- No token: receives no changes.
The row check uses the table’s primary key. Inserts and updates on a table without one are not sent.
Subscribe
from(table).subscribe() is the shortest path, shown on the client page. The callback’s rows are typed from your schema.
const sub = supatype.from("comment").subscribe( (change) => { if (change.eventType === "INSERT") addComment(change.new) if (change.eventType === "UPDATE") replaceComment(change.new) if (change.eventType === "DELETE") removeComment(change.old?.id) }, { event: "*", filter: `post_id=eq.${postId}` },)
// latersub.unsubscribe()Each call opens its own channel, so two components watching the same table do not interfere. All channels share one WebSocket per client. The payload has eventType, new, old, schema, table and commitTimestamp.
Options
| Option | Values | Default |
|---|---|---|
event | "INSERT", "UPDATE", "DELETE", "*" | "*" |
filter | "column=op.value", several joined with commas | none |
schema | the Postgres schema of the table | "public" |
Filters
A filter is checked on the server, so changes that do not match never reach the client. Several conditions joined with commas must all match. The operators are eq, neq, gt, gte, lt and lte.
- Values are compared by the column’s type, as Postgres would compare them, so
salary=gt.100000compares numbers. A column of a type the service does not recognise is compared as text. - A null value, or one that cannot be read as the column’s type, matches nothing.
- An operator not in that list is ignored, and the filter then matches every change.
- A delete is matched on
old, the row as it was.
Channels
supatype.realtime.channel(name) is the lower-level form, for when you want the channel’s status or want to mix changes with broadcast and presence:
const channel = supatype.realtime .channel(`post:${postId}`) .on("postgres_changes", { event: "INSERT", table: "comment", filter: `post_id=eq.${postId}` }, (change) => { showComment(change.new) }) .subscribe((status, err) => console.log(status, err?.message))Status is SUBSCRIBING, SUBSCRIBED, CHANNEL_ERROR, TIMED_OUT or CLOSED. CHANNEL_ERROR means the server refused a request on the socket, such as a postgres_changes listener for a table that does not exist, for a view, which has no changes of its own, or for a table the subscriber’s role cannot read, such as auth.users with an anon or signed-in key: every change would be withheld from it. A channel used only for broadcast and presence is never checked against a table, whatever its name. With CHANNEL_ERROR the callback’s second argument, err, is an Error whose message is the server’s reason and names the table; it is undefined with every other status. A join hears only changes committed after it was taken. TIMED_OUT means the client gave up reconnecting. Render the status rather than assuming a channel is live: a subscription that stopped receiving looks the same as a quiet table. Pass table explicitly. Without it the channel name is read as schema:table.
A channel carries one table subscription. If you call .on("postgres_changes", ...) more than once on a channel, the first call’s table, event and filter are what the server registers. Use one channel per table.
Broadcast and presence
Broadcast sends a message to everyone else on a channel. Presence tells a channel who has joined and left. Neither touches the database.
const room = supatype.realtime .channel(`cursor:${docId}`) .onBroadcast("move", (payload) => drawCursor(payload)) .onPresence(({ joins, leaves }) => updateUsers(joins, leaves)) .subscribe((status) => { if (status === "SUBSCRIBED") room.track({ name: displayName }) })
room.broadcast("move", { x: 120, y: 48 })- Only clients that have subscribed to the channel receive its messages. The two differ on the sender: a broadcast is not sent back to the client that sent it, but presence is. Your own
trackarrives in youronPresenceas a join, and your own leave as a leave, so skip your own entry if you only want the others. - A presence entry is the payload you pass to
track, plususer_idfrom the token. The server writesuser_idlast, so a payload cannot claim to be someone else. Every client without a signed-in user shares theuser_idanonymous, souser_idcannot tell two anonymous clients apart, or tell you which entry is your own. Put a value you generate yourself in thetrackpayload, such astrack({ clientId: crypto.randomUUID(), name }), and key your member map on that. - Calling
trackagain announces the new payload as a fresh join, so keep your own map of members keyed byuser_id. - A client that joins late is sent the members already tracked on the channel as joins, then hears about joins and leaves from then on.
- A client leaves on
untrack(), on unsubscribe and when its socket closes. - Messages sent while the socket is not open are dropped, so send after
SUBSCRIBED.
Framework hooks
@supatype/react exports useSubscription. It subscribes when the component mounts, unsubscribes when it unmounts, and re-subscribes when the channel name, event, table, schema or filter changes. The callback can change between renders without re-subscribing. It returns status, and error, the server’s reason while the status is CHANNEL_ERROR and null otherwise.
import { useState } from "react"import { useSubscription } from "@supatype/react"import type { TableRow } from "@supatype/client"
function Comments({ postId }: { postId: string }) { const [comments, setComments] = useState<TableRow<"comment">[]>([]) const { status } = useSubscription<TableRow<"comment">>(`comments:${postId}`, { table: "comment", event: "INSERT", filter: `post_id=eq.${postId}`, callback: ({ new: row }) => { if (row) setComments((list) => [...list, row]) }, }) return <p>{status}: {comments.length} new</p>}It needs SupatypeProvider above it, which takes your client as client. Give each use its own channel name: two hooks with the same name share a channel.
useChannel(name, setup, deps) is for a channel that needs more than one listener, such as rows, presence and a broadcast together. setup receives the channel and adds its listeners; the hook subscribes, unsubscribes when the component unmounts or name or deps change, and runs setup again only when deps change, as useEffect does. It returns status and error as useSubscription does, and isConnected and connectionState for the socket itself.
import { useChannel } from "@supatype/react"import { addBid, notify } from "./app"
function Auction({ id }: { id: string }) { const { status, isConnected } = useChannel(`auction:${id}`, (channel) => { channel.on("postgres_changes", { event: "INSERT", table: "bid", filter: `auction_id=eq.${id}` }, ({ new: bid }) => addBid(bid)) channel.onBroadcast("outbid", (payload) => notify(payload)) }, [id]) return <p>{isConnected ? status : "reconnecting"}</p>}useRealtimeConnection() returns only isConnected and connectionState. @supatype/vue has useChannel(name, setup) and useRealtimeConnection(), and @supatype/svelte and @supatype/solid have createChannel(name, setup) and createRealtimeConnection(). They return status and error as that binding’s createSubscription does ("connecting", "connected", "disconnected" or "error"), plus isConnected and connectionState, each as a ref, signal accessor or store to match the binding. name can be a string, or one that changes: a ref or getter in Vue, an accessor in Solid, a store in Svelte (with runes, toStore(() => name) from svelte/store makes one). When it changes the old channel is left, its listeners go with it, and setup runs on the new channel, so status reads "connecting" until it joins. Otherwise setup runs once, when the component mounts (straight away in Svelte), and the channel is left when it unmounts. There is no deps argument.
@supatype/vue has useSubscription(table, { event, filter }), and @supatype/svelte and @supatype/solid have createSubscription(table, { event, filter }). These watch the public schema and return data, error and status, which is "connecting", "connected", "disconnected" or "error". data is the table’s rows. It is read once the subscription has joined, and read again after each re-join (a dropped socket that came back, or a sign-in), so changes made while the socket was down are not lost. From then on each change is an upsert by key: an insert or update replaces the row with the same key or adds it, and a delete removes it, with no effect for a key that is not held. The key is id; pass key: "slug", or an array for a composite key, when the primary key is another column. A filter narrows the read as well as the changes. If the read fails, error holds the reason until a later read succeeds, and status is unchanged. Before 0.9.3 data started empty and an update or delete of a row that existed before subscribing did nothing.
Private channels
A private channel is a broadcast and presence channel with access rules, written in your schema. You declare it with a Channel type, push, and the realtime service checks every join, broadcast and presence update against that rule, as the user who made it. Nobody can read or fake traffic on it just by knowing its name.
This is the same idea as Supabase Realtime Authorization. The difference is who decides. In Supabase the client flags a channel private and policies on realtime.messages do the rest. Here the schema declaration decides, whether or not the client says private, so a client cannot skip the rules by leaving a flag out.
How it works
- A channel has three operations.
joincovers subscribing, receiving broadcasts and receiving presence.sendcovers broadcasting.trackcovers appearing in presence. - An operation you leave out is denied to everyone except the service role. A declaration with no rules at all is refused when the schema is read.
- Each rule is written in the same access rule language as a model, and runs inside Postgres as the caller. A
Rowsrule sees only the rows that caller may read. - Each operation is judged on its own. A rule that reads a table the caller has no privilege on denies that operation and no other, so a channel with
join: Publicand atrackrule over a private table still admits anon to join, and refuses it presence. - The server asks once at join, keeps the answer, and then judges each broadcast and presence update from that answer with no database call.
- The service role may do anything on any channel.
Example: an auction lot
Each lot has a channel. Only a signed-in user who is watching the lot may join it and appear in its presence. Any signed-in user who has joined may send a bid event, and only with an amount between 1 and 1,000,000. Only the seller, or an auctioneer, may announce that the reserve is met, which is a second channel on the same lot.
import type { Model, Channel, UUID, Int, LoggedIn, Role, In, Exists, Rows, Eq, All, Any, AuthUid, Param, Event, Payload,} from "@supatype/types"
export type Lot = Model< { id: UUID; seller_id: UUID; title: string }, { access: { read: LoggedIn } }>
export type LotWatcher = Model< { id: UUID; lot_id: UUID; user_id: UUID }, { access: { read: LoggedIn } }>
export type Bid = Model< { id: UUID; lot_id: UUID; bidder_id: UUID; amount: Int }, { access: { read: LoggedIn; create: LoggedIn } }>
// Lots the signed-in user is watching.type MyLots = Rows<"lot_watcher", "lot_id", Eq<"user_id", AuthUid>>
// True when the signed-in user is the seller of the lot named in the topic.type SellerOfThisLot = Exists< Rows<"lot", "id", All<[Eq<"id", Param<"id">>, Eq<"seller_id", AuthUid>]>>>
// Bids and watchers. A signed-in watcher may send a "bid" event with a sensible amount.export type LotChannel = Channel<"lot:{id}", { params: { id: UUID } access: { join: Any<[In<"id", MyLots>, Role<"auctioneer">]> send: All<[ LoggedIn, Event<"bid">, Payload<"amount", { kind: "number"; min: 1; max: 1000000 }>, ]> track: All<[LoggedIn, In<"id", MyLots>]> }}>
// Announcements only the seller (or an auctioneer) may make about the same lot.export type LotStatusChannel = Channel<"lot:{id}:status", { params: { id: UUID } access: { join: Any<[In<"id", MyLots>, Role<"auctioneer">]> send: All<[Any<[SellerOfThisLot, Role<"auctioneer">]>, Event<"reserve_met">]> }}>Things to notice:
In<"id", MyLots>at the top of a rule: a bare string names a channel parameter, here the{id}in the pattern. InsideRowsa bare string is a column of that table, so a parameter there is writtenParam<"id">.EventandPayloadare checked by the realtime server on every broadcast, with no database call. They are valid only insendand only directly insideAll<[...]>. OneAllnames one event, which is why the seller’s event has its own channel.Payloadchecks the shape of a field:string(withmaxLength),number(withminandmax),booleanorrequired. A missing field fails its check. It cannot say whether a bid is a good one. Put that in a database function (see sending from the database).- The channel types need no
export, but exporting them does no harm.
Declaring a channel
- A pattern is segments separated by
:. A segment is a literal, a{name}that matches exactly one segment, or a final*that matches one or more remaining segments. - A literal may hold only letters, digits,
_,.and-. A pattern may not be a bare*, and may not start withrealtime:or_supatype. - Every
{name}needs an entry inparams, and everyparamskey must be in the pattern. A parameter is aUUID, astringor anInt. A topic whose parameter has the wrong shape, such aslot:abcfor{id: UUID}, is refused as not fitting. It never reaches Postgres as a bad cast. - Two declarations that could match the same topic are refused, and both are named.
lot:{id}andlot:featuredcannot both exist. Owneris refused on a channel, because a channel has no row to own.- A
sendrule made only ofEventandPayloadchecks who is sending nothing, so anon may send.supatype diffandsupatype pushwarn about it every time, as long as the rule stands. Add a caller test such asLoggedIn. WritingPublicin the rule says anyone may send, and silences the warning. supatype diffandsupatype pushlist channels added, removed and changed, and which operation’s rule changed.- The engine must be new enough to emit the access functions. The CLI refuses a push that declares a channel, or sets
realtime.channels, to an engine that does not listprivate_channelsin its capabilities. See moving from 0.9.2. - After
supatype generate, the declared patterns type the channel names in the client, so editors suggestlot:${string}. Any other string is still accepted.
A declaration is enforced as soon as it is pushed, for every client, including ones built before channels existed.
The realtime.channels switch
The switch decides what happens to a topic that no declaration matches. It lives in supatype.config.ts and push carries it into the database, so self-host and Cloud need nothing else.
import { defineConfig } from "@supatype/cli"export default defineConfig({ project: { name: "gavel" }, database: { provider: "docker" }, server: { mode: "dev" }, app: { mode: "none" }, realtime: { channels: "declared" },})| Value | An undeclared topic |
|---|---|
"open" | Broadcast and presence work as they always did. This is the default when the key is absent. |
"declared" | The join is allowed, so from(table).subscribe() still works, but broadcast and presence on it are refused. A broadcast from the database to it is dropped. supatype init writes this for new projects. |
The REALTIME_CHANNELS environment variable on the realtime service can only tighten this. Set to declared, it makes the service behave as declared even when the database says open. It can never loosen a database that says declared. Any other value stops the service from starting.
Using a private channel from the client
Pass private: true when you open the channel. The server enforces declarations without it. What the flag adds is an assertion: a name that no declaration matches is refused at once, so a typo fails loudly, and a server too old to enforce channels is never asked.
import { isRealtimeChannelError } from "@supatype/client"import { supatype } from "./supatype"import { displayName, lotId, retryLater, showBid, showRefusal, tellUser, updateWatchers } from "./app"
const lot = supatype.realtime .channel(`lot:${lotId}`, { private: true }) .onBroadcast("bid", (bid) => showBid(bid)) .onPresence(({ joins, leaves }) => updateWatchers(joins, leaves)) .onRefused((refusal) => { // The channel is still joined. This one send went nowhere. if (refusal.code === "payload_refused") tellUser("That bid was not accepted.") }) .subscribe((status, err) => { if (status === "SUBSCRIBED") lot.track({ name: displayName }) if (status === "CHANNEL_ERROR" && isRealtimeChannelError(err)) { if (err.retryable) retryLater() else showRefusal(err.reason) } })
lot.broadcast("bid", { amount: 120 })In React, useChannel takes the options as its fourth argument, and returns error for a refused or withdrawn join and refusal for a refused send. The Vue, Solid and Svelte channel bindings take the same options and return refusal too.
import { useChannel } from "@supatype/react"import { isRealtimeChannelError } from "@supatype/client"import { showBid } from "./app"
function Lot({ id }: { id: string }) { const { status, error, refusal } = useChannel( `lot:${id}`, (channel) => { channel.onBroadcast("bid", (bid) => showBid(bid)) }, [id], { private: true }, )
if (status === "CHANNEL_ERROR") { return <p>{isRealtimeChannelError(error) ? error.reason : "error"}: {error?.message}</p> } return <p>{status}{refusal ? ` (${refusal.code})` : ""}</p>}Refusals and withdrawal
Every refusal carries a fixed code. Your app acts on the code, and may show the message. Codes are listed in refusal codes.
- A refused join arrives as
CHANNEL_ERROR, with aRealtimeChannelErroras the second argument. Itsreasonis the code,channelnames the topic, andretryableis true only when the server could not reach the database.isRealtimeChannelError(value)tells one from any other error. - A refused broadcast, presence track or payload does not change the channel’s status. The channel is still joined. It goes to
onRefusedas{ channel, code, message }, withcodeone ofsend_denied,track_deniedorpayload_refused. - Withdrawal is access taken back from a channel you held. It reaches every handle on that channel as
CHANNEL_ERRORwith reasonwithdrawn, and you also leave the channel’s presence. The client does not rejoin by itself. Subscribe again once the user’s access is restored. - A message never contains the rule or the data it read. It names the declaration.
Sending from the database
A broadcast is not a transaction, so data that matters, such as a bid, should be written by a database function. That function can then tell the watchers itself with _supatype.realtime_send(topic, event, payload). It works from any SQL: an RPC function, a trigger, a hook or a migration.
create or replace function place_bid(p_lot uuid, p_amount integer)returns voidlanguage plpgsqlsecurity invokeras $$begin insert into bid (id, lot_id, bidder_id, amount) values (gen_random_uuid(), p_lot, auth.uid(), p_amount);
-- Tell everyone watching the lot. The send rule of lot:{id} is checked as the caller. perform _supatype.realtime_send( 'lot:' || p_lot, 'bid', jsonb_build_object('amount', p_amount) );end;$$;The client calls it like any function, and listeners get the broadcast through onBroadcast as usual.
const { error } = await supatype.rpc("place_bid", { p_lot: id, p_amount: 120 })if (error) console.error(error.code, error.message)- Receivers are every member the channel’s
joinrule admitted. There is no new access path. realtime_sendchecks the caller’ssendrule, including the event and payload checks, and raises error42501with the same sentence a refused broadcast gets. Only signed-in users sending as themselves pass. Anon is refused. The service role may send anything.- It writes one row to
_supatype.realtime_outbox, which the realtime service reads from the replication slot. A trigger deletes each row as it is written, so the table never fills. Inserting into the outbox directly is judged by the same rule, and the row’ssendermust be the caller’s own id (leave it out and the insert is refused). - Under
declared, a database send to a topic no declaration matches is dropped, and the service logs it once per topic.
Token changes, re-checks and outages
- New token. When a socket gets a new token, for example after sign-in, sign-out or a role change, every channel it holds is judged again as the new identity. A channel whose
joinrule no longer admits the user is withdrawn, with a presence leave. Changedsendandtrackanswers replace the old ones. - Revocation. If a user is removed from a table a rule reads, such as
lot_watcher, the held channels of that declaration are judged again, in one batch a second. They are also judged again after a schema push, and every 300 seconds as a backstop. SetREALTIME_CHANNEL_RECHECK_Sto change that interval. - Expiry. A token that expires closes the socket with 4401, as before.
- Database down at join. The service fails closed. It refuses every join, open channels included, with code
unavailableandretryableset, because without the database it cannot tell whether a topic is declared. Retry with a delay. - Database down at a re-check. Nobody loses a channel because a check could not run. Held channels keep their access and the check is tried again at the next interval. A new token that cannot be checked still withdraws the channels, since the old answer no longer applies.
- Shared instance. A shared realtime service, which serves many projects from one database, does not enforce channel rules. It refuses a join that says
private, with codeshared_instance. Supatype Cloud (closed beta) runs one realtime service per project.
Refusal codes
The set is closed. A client that meets a code it does not know should treat it as refused.
| Code | Arrives as | Meaning | What the app should do |
|---|---|---|---|
join_denied | CHANNEL_ERROR | The channel’s join rule said no, or the channel declares none. | Tell the user they may not open this. Do not retry. Ask them to sign in if they are not. |
not_declared | CHANNEL_ERROR | You opened it with private: true and no declaration matches the name. | A bug: fix the name, or push the declaration. |
does_not_fit | CHANNEL_ERROR | A declaration matches the start of the name, but a parameter has the wrong shape, such as a non-UUID. | A bug: build the topic from a valid value. |
unavailable | CHANNEL_ERROR, retryable | The server could not reach the database to check. | Retry after a delay. This is the only retryable code. |
shared_instance | CHANNEL_ERROR | The realtime service is shared, and private channels are not available there. | Use a project with its own realtime service. |
withdrawn | CHANNEL_ERROR | A re-check took back access to a channel you held. | Stop showing the channel’s data. Join again only when the user’s access changes. |
send_denied | onRefused | A broadcast was refused: the send rule said no, there is none, or the topic is undeclared under declared. | Show that the send failed. The channel is still joined. |
track_denied | onRefused | A presence track was refused. | Show that the user is not shown as present. The channel is still joined. |
payload_refused | onRefused | The event name or payload failed the send rule’s checks. | Fix the message, or tell the user their input was not accepted. |
refused | CHANNEL_ERROR | Any other refusal, such as a bad filter, a missing table or no token. | Read the message. Do not retry blindly. |
unsupported_server | CHANNEL_ERROR | The client’s own: the server did not announce private channel support, so a private: true join was never sent. The message says to upgrade the server. | Upgrade the realtime service. Do not fall back to an open channel. |
Moving from 0.9.2
Nothing changes until you declare a channel or set realtime.channels. A project with no realtime key stays "open", so broadcast and presence behave as they did. supatype init writes "declared" for new projects only.
Before 0.9.3, anyone with your anon key could join any channel, read its broadcasts, send on it and appear in its presence. To close that:
- Step 1: Upgrade the realtime service and the engine. The engine must list
private_channelsin its capabilities. The CLI checks this and refuses the push if it does not, because an older engine would drop the channels and report success while enforcing nothing. On self-host, raise the engine pin inversions.engine. On Cloud, a push that declares channels is refused until the platform’s engine lists the capability. - Step 2: Declare a
Channelfor each topic your app uses, with the rules you want. Declaring one enforces its pattern at once, for every client, in either mode. - Step 3: Set
realtime: { channels: "declared" }and runsupatype dev. Fix the refusals you see.supatype diffwarns when the mode goes fromopentodeclared, and when you remove a declaration underdeclared. - Step 4: Push.
- Step 5: Add
private: trueto the channels the client opens, so a mistyped name is refused instead of left open.
A channel named after a table, which from(table).subscribe() opens, keeps working under declared with no declaration, because it only carries row changes. Row changes are still guarded by the table’s access rules.
A client that sends private: true to a 0.9.2 realtime service fails with unsupported_server and the message “this realtime server does not enforce private channels; upgrade it”.
Connection and auth
The client opens the socket at /realtime/v1 on your project URL when the first channel subscribes, and closes it when the last one unsubscribes. It sends the current session’s token, or the anon key when nobody is signed in.
supatype.realtime.removeChannel(name) leaves a channel by name. supatype.realtime.disconnect() closes the socket whatever is still subscribed, and reports CLOSED to every channel still registered.
When someone signs in, signs out or a different user signs in, the client reconnects with the new token and joins every channel again. Access is checked as the new identity from then on. A token refresh for the same user does not reconnect, so no changes are missed.
A channel’s status cannot tell a drop from a first connect, since both read SUBSCRIBING. For the socket itself, supatype.realtime.isConnected is true while it is open, and supatype.realtime.onConnectionChange((state) => ...) calls you each time supatype.realtime.connectionState changes between "connected", "connecting" (first connect, reconnecting after a drop or a sign-in, or waiting to retry) and "disconnected" (nothing subscribed, disconnect() was called, or every retry failed). It returns a function that stops the listener, and does not call you with the state it already has. Refetch when the state returns to "connected" after a drop. In React, useChannel and useRealtimeConnection expose the same two values.
If the socket drops, the client retries after 1, 2, 4, 8 and 16 seconds, then every 30 seconds, for up to 10 attempts. Channels report SUBSCRIBING while it retries and TIMED_OUT once it gives up. Changes made while the socket was down are not replayed, so refetch after a reconnect if you need the gaps filled.
Config and requirements
Realtime needs Postgres with wal_level = logical, the wal2json plugin, and a database role allowed to create replication slots. The Postgres that supatype dev and the self-host stack run has all three. For a database you bring yourself, supatype db check tests for them.
If the database cannot do logical decoding, realtime does not stop the stack. The service stays up and serves broadcast and presence, change subscriptions deliver nothing, and /health/ready on the service answers 503 with the reason. When you run against your own database, set database.external.realtime to false in supatype.config.ts to leave the service out of the stack.
The service reads these environment variables. The self-host compose file sets the first three.
| Variable | Default | What it controls |
|---|---|---|
DATABASE_URL | required | The database to read changes from |
JWT_SECRET | required | Verifies subscribers’ tokens |
SLOT_NAME | supatype_realtime | The replication slot the service creates and reads |
PORT | 4000 | The port the service listens on |
REPLICATION_POLL_INTERVAL | 100 | How often, in milliseconds, the slot is read |
SECURE_CHANNELS | true | When true, a client must present a valid token before it can join a channel |
REALTIME_CHANNELS | unset | Set to declared to refuse broadcast and presence on undeclared channels whatever the database says. It can only tighten realtime.channels |
REALTIME_CHANNEL_RECHECK_S | 300 | Seconds between re-checks of every channel a socket holds, as a backstop to the checks made on a new token, a push and a change to a table a rule reads |
To set these from supatype.config.ts rather than the environment, use realtime: { channels: "declared", recheckSeconds: 120 }. Self-host renders them as the realtime service’s defaults, which a value in .env overrides. A push to Supatype Cloud sets them on the project’s realtime service (production only), and a setting you take out of the config stops applying on the next push that still sets another one.
Limits
- Changes are picked up by reading the replication slot every 100 ms, so expect that much delay on top of the network.
- While
supatype pushis changing the schema, the slot is not read. Changes made during the push are held in the slot and sent once it finishes. - Each change costs one database query per subscriber, to check that subscriber’s access. Many subscribers to a busy table means many queries.
- The replication slot keeps WAL until the service reads it. If the service is stopped for a long time while the database keeps writing, WAL builds up on disk.
- Each private channel a socket holds costs one query at join, one more every re-check interval, and a batch a second while a table its rules read is changing.
- Subscriptions live in the service’s memory. A restart drops every socket, and clients reconnect and join again.