# Realtime

Your application can hear about rows being added, changed and deleted as it happens, over a WebSocket. Each listener is told only about rows that row-level security lets them read.

## Switch it on for a table

In the console: **Data → Tables page →** the table **→ Structure → Realtime**. It is off for every table until you switch it on. The table needs a primary key.

## Connect

```
wss://api.rezincore.com/v1/realtime
```

The key and token go in the **first message**, never in the address.

```
send      {"type":"auth","apikey":"<publishable key>","token":"<the signed-in user's token>"}
receive   {"type":"ready"}

send      {"type":"subscribe","table":"notes"}
receive   {"type":"subscribed","table":"notes"}

receive   {"type":"change","table":"notes","op":"INSERT","row":{…}}
receive   {"type":"change","table":"notes","op":"UPDATE","row":{…}}
receive   {"type":"change","table":"notes","op":"DELETE","key":{"id":"…"}}
```

From your own server, sign in with a secret key and an organization instead:

```json
{ "type": "auth", "apikey": "<secret key>", "organization": "<organization ID>" }
```

A minimal listener in a browser:

```js
const ws = new WebSocket('wss://api.rezincore.com/v1/realtime');
ws.onopen = () => ws.send(JSON.stringify({ type: 'auth', apikey: KEY, token: TOKEN }));
ws.onmessage = (event) => {
  const msg = JSON.parse(event.data);
  if (msg.type === 'ready') ws.send(JSON.stringify({ type: 'subscribe', table: 'notes' }));
  if (msg.type === 'change') console.log(msg.op, msg.row ?? msg.key);
  if (msg.type === 'signed_out') { /* sign in again, then reconnect */ }
};
```

## What a listener hears

It is decided by the table's row-level security. For each change the row is read again *as that listener*; only a row that comes back is sent, as it is now. So:

- a row the listener may not read is never mentioned to them;
- an update that moves a row out of a listener's sight sends them nothing;
- a deleted row cannot be read again, so a delete goes only to listeners in the row's own organization and carries only the key. **The table needs an `organization_id` column for deletes to be sent at all.**

## Rules to build around

- **Changes are delivered once, to whoever is connected.** A listener that was away does not get what it missed. Re-read the table when you reconnect.
- **Listening does not keep a sign-in alive.** When the user's sign-in ends or goes idle, the socket closes with `{"type":"signed_out"}`.
- A connection listens to **20 tables at most**.
- Send `{"type":"ping"}` to check the connection is alive; the answer is `{"type":"pong"}`.
- A page in a browser may connect only from an address the project lists. See [Authentication settings](https://rezincore.com/docs/auth/settings.md#url-configuration).
- Each change costs one extra read per listener, so a table with very many listeners and very frequent changes is the wrong fit today.
