# Realtime
Source: https://sovaria.in/docs/realtime-overview

Broadcast messages on channels, track who is online, and stream database changes to clients.

Realtime connects clients over WebSockets. Use **channels** to broadcast messages (chat, cursors, game state), **presence** to see who is connected, and **database change data capture** to push inserts, updates and deletes from your tables.

(Diagram: Realtime channels)

## Subscribe to a channel

The SDK first gets a one-time **ticket** for the channel (checked against your rules), then opens the WebSocket with it. Tickets work once and expire after a few seconds, so a leaked URL is useless.

JavaScript:
```js
const url = await sovaria.realtime.wsUrlWithTicket('room-42')
const ws = new WebSocket(url)
ws.onmessage = (e) => {
  const msg = JSON.parse(e.data)
  console.log(msg.payload)
}
```

## Publish

JavaScript:
```js
await sovaria.realtime.publish('room-42', { text: 'Hello!', at: Date.now() })
```

cURL:
```bash
curl -s -X POST https://<project-ref>.sovarias.in/api/v1/rt/stream/publish/room-42 \
  -H "Authorization: Bearer $ACCESS_TOKEN" -H 'X-Sovaria-Project-ID: <project-id>' \
  -H 'Content-Type: application/json' -d '{"payload":{"text":"Hello!"}}'
```

## Presence and history

- `sovaria.realtime.presence(channel)` — who is connected right now.
- `sovaria.realtime.replay(channel, after, limit)` — messages a client missed while it was offline.

## Who can join and publish

Channel rules are project policies with two actions: **SUBSCRIBE** and **PUBLISH**. App users and anon-key visitors get **no channel** until a rule allows it — unlike some platforms, channels are not open by default. Console members and the service role key are not limited.

- `ctx.resource.name` is the channel name and `ctx.action` is `SUBSCRIBE` or `PUBLISH`.
- `ctx.realtime.in_own_channel` is true for a signed-in caller's private channels: `user:<user id>` and anything under it, such as `user:<user id>:notifications`. A caller with only the anon key has none (all such visitors share one id).
- App roles you assign under **Authentication → Users** are in `ctx.actor.roles`.
- `ctx.realtime.prefix` is the text before the first `:` and `ctx.realtime.id` the text after it, so `clinic:42` has prefix `clinic` and id `42`.
- One channel per tenant (organization, clinic, workspace): compare the id with the caller's tenant, `ctx.realtime.id == ctx.org.id` (the active app organization) or `ctx.realtime.id == ctx.app_metadata.clinic_id` (metadata an admin set). A rule on the prefix or a role alone lets every tenant's members into every tenant's channel. A caller without that organization or metadata is refused.
- Database change events follow row security: each subscriber receives only the rows their own policies let them read.

Policy:
```bash
# Staff join only their own clinic's channel (clinic:<clinic id>)
ALLOW IF ctx.realtime.prefix == "clinic" AND ctx.realtime.id == ctx.app_metadata.clinic_id AND "staff" IN ctx.actor.roles

# Each signed-in user may listen on their own channels
ALLOW IF ctx.realtime.in_own_channel == True AND ctx.action == "SUBSCRIBE"

# Everyone signed in may join and talk in the lobby
ALLOW IF ctx.resource.name == "lobby" AND ctx.actor.is_anonymous == False

# Only staff may announce
ALLOW IF ctx.resource.name == "announcements" AND (ctx.action == "SUBSCRIBE" OR "staff" IN ctx.actor.roles)
```

Add rules under **Policies**, which has ready-made realtime templates. A refused ticket or publish returns `403` with `CHANNEL_DENIED` and the reason.

## Database changes

Turn on **Realtime → Database change data capture** and choose the tables. Every insert, update and delete is published on that table's channel. Subscribers only receive rows they are allowed to read under your [row-level security](https://sovaria.in/docs/row-level-security).

## Limits and slow connections

| Limit | Free | Pro | Ultra | Team | Enterprise |
|---|---|---|---|---|---|
| Concurrent connections per organization (`rt.concurrent`) | 100 | 500 | 1,500 | 5,000 | 20,000 |
| Connections per signed-in user (`rt.connections_per_user`) | 20 | 50 | 100 | 200 | 500 |
| Largest message | 128 KB | 128 KB | 128 KB | 128 KB | 128 KB |

- The connection after the limit is closed with code `4408` and `PLAN_LIMIT_REACHED`; one that closes frees its slot at once, and a connection that disappears without closing (a crashed device) stops counting within 90 seconds.
- Every subscriber gets messages in order through its own buffer. A client that stops reading (a frozen tab, a dead mobile network) is closed with code `1013` (*slow consumer*) once it falls about 1,000 messages or 8 MB behind, or a single send stalls for most of a second, so it never slows anyone else down. The SDKs reconnect on their own and first deliver what was published while they were away (from the channel's replay history, in order, each message once), then live messages; `onGap` tells you when messages are older than the retained history and couldn't be recovered. Without an SDK, reconnect and call `replay(channel, after)` with the last `stream_seq` you saw.
- Messages are sent uncompressed: compressing each message once per subscriber costs far more server time than it saves on JSON this size.

## Performance

We measure realtime with an open load test (`scripts/load/ws_ramp.py`): thousands of subscribers connect the way an app does (ticket, then WebSocket), a publisher sends messages with a timestamp, and every subscriber records when each one arrives. Engine-only results on one CPU core (2026-10-23):

| Subscribers | Message | Delivery p50 | p95 | Server time per delivery | Memory per connection |
|---|---|---|---|---|---|
| 1,000 | 1 KB | 9 ms | 18 ms | 16 µs | ~22 KB |
| 4,000 | 1 KB | 25 ms | 50 ms | 15 µs | ~22 KB |
| 4,000 | 10 KB | 28 ms | 58 ms | 14 µs | — |
| 4,000 | 50 KB | 47 ms | 88 ms | 23 µs | — |

These are engine-only numbers from a single process with the test clients on the same machine, so the tails include the clients' own load. Results through the full production path will be published here when measured.

> **Tip:** Use realtime for things that change while the user watches; for everything else, query the database when the page loads.
