# Channels and connections
Source: https://sovaria.in/docs/realtime-channels

How a realtime connection is opened, kept alive and re-opened; publishing and receiving; channel names; message size, rate and ordering; catching up with replay; closing codes; encrypted channels; and limits.

## The connection

1. **Ticket** — The client asks for a one-time **ticket** for a channel (`POST /api/v1/auth/ws-ticket`). The ticket says who is connecting and for which project — always the caller's own: an app user or API key gets one for its own project, a team member only for a project they are on. It works once and expires within a minute.
2. **Connect** — The client opens `wss://<project-ref>.sovarias.in/api/v1/rt/ws/<channel>?ticket=…`. Your channel rules decide here whether the caller may subscribe; if not, the socket is closed (code 4408, reason `CHANNEL_DENIED: …`).
3. **Stay alive** — The connection is kept alive with a heartbeat every 30 seconds; a connection silent for 90 seconds is treated as gone.
4. **Re-open** — If it drops, the SDK reconnects with backoff (at most 15 seconds between tries, configurable) and a fresh ticket each time.

JavaScript:
```js
const room = sovaria.realtime.channel('room-42', {
  onMessage: (payload) => addMessage(payload),
  onStatus: (status) => setStatus(status),   // 'connecting' | 'live' | 'reconnecting' | 'closed'
  onError: (err) => console.warn(err),       // it keeps retrying
  maxBackoffMs: 15000,
})

await room.send({ text: 'Hello!', at: Date.now() })
room.close()
```

## Publish and receive

- `room.send(payload)` or `sovaria.realtime.publish(channel, payload)` sends through the API (`POST /api/v1/rt/stream/publish/<channel>`); your rules must allow `PUBLISH` for the caller.
- Servers and functions can publish with the service role key — for example to notify users when a job finishes.
- Every subscriber of the channel, including the sender, receives the message as `{ payload, … }`.

## Channel names

| Pattern | Use |
|---|---|
| `room-42`, `orders` | Shared channels; allow them by name in rules. |
| `user:<user id>`, `user:<user id>:notifications` | A user's private channels; one rule covers them all with `ctx.realtime.in_own_channel == True`. |
| `db.table.<table>` | Database change events ([Database change events](https://sovaria.in/docs/realtime-database-changes)). |

## Ordering and delivery

- Messages on one channel arrive in the order they were published.
- A message reaches the clients connected at that moment. Each message carries `stream_seq`, its number in the channel. A client that was offline catches up with **replay**: `sovaria.realtime.replay(channel, after, limit)` returns the messages after the last `stream_seq` it saw (up to 1,000 per call; the most recent 1,000 per channel are kept).
- A client that can't keep up (its socket doesn't accept data within about a second) is disconnected so it doesn't slow the channel down; it reconnects and replays.

JavaScript:
```js
let lastSeen = 0
const ch = sovaria.realtime.channel('orders', {
  onMessage: (payload, raw) => { lastSeen = raw.stream_seq ?? lastSeen; show(payload) },
  onStatus: async (s) => {
    if (s === 'live' && lastSeen) {
      const missed = await sovaria.realtime.replay('orders', lastSeen, 200)
      missed.events?.forEach((e) => show(e.payload))
    }
  },
})
```

## Why a connection closes

| Code | Means | Do |
|---|---|---|
| `4401` | Not authorized: bad, expired or reused ticket, or the user signed out. | Get a new ticket (the SDK does); if it keeps failing, check the channel rules. |
| `4408` | Policy violation: a rule or limit refused the connection or a message. | Check rules and limits (message size, events per second). |
| `1013` | Slow consumer: the client didn't read fast enough. | Reconnect and replay; handle messages faster. |

## Encrypted channels

A channel can carry encrypted payloads. Sovaria creates the channel's key, keeps it and hands it to your signed-in clients (wrapped for a client's own public key when it sends one); clients encrypt messages before sending and decrypt after receiving, so payloads travel and are stored encrypted. Because Sovaria issues and holds the keys, this is not end-to-end encryption: Sovaria could read the messages. For data Sovaria must never be able to read, encrypt it in your app with a key only your users hold. Keys can be rotated and revoked ([HTTP API: realtime](https://sovaria.in/docs/rest-realtime)).

|  | Free | Pro | Ultra | Team | Enterprise |
|---|---|---|---|---|---|
| Encrypted realtime channels (Sovaria-managed keys) | ✓ | ✓ | ✓ | ✓ | ✓ |

## Limits

Per project you can lower these further and cap events per second per connection under Realtime › Settings ([Realtime settings and limits](https://sovaria.in/docs/realtime-settings)).

- **Visitors on the anon key.** Everyone using only your publishable (anon) key shares one identity, so the connections-per-user limit and the connect rate are counted per visitor address for them: one visitor holding many sockets can't lock the others out. Your project's concurrent-connection limit still bounds them all together.
- **Shared ceilings** (set by Sovaria, the same on every plan) keep one busy project from slowing others: about 500 messages a second on one channel from all senders together, 2,000 a second across a project's channels, and 10,000 connections on one channel. A message past a ceiling is refused with `rate_limited` (send fewer, or spread them over channels); a connection past the channel limit closes with `4429`.
- **Private user channels.** `ctx.realtime.in_own_channel` is true only for a signed-in user on `user:<their id>`; a caller with just the anon key has no own channel.

|  | Free | Pro | Ultra | Team | Enterprise |
|---|---|---|---|---|---|
| Concurrent realtime connections | 100 | 500 | 1,500 | 5,000 | 20,000 |
| Realtime channels | 20 | 500 | 5,000 | 20,000 | 100,000 |
| Realtime connections per signed-in user | 20 | 50 | 100 | 200 | 500 |
| Largest realtime message | 0 MB | 0 MB | 0 MB | 0 MB | 0 MB |
| Monthly realtime messages | 500,000 | 2,000,000 | 10,000,000 | 50,000,000 | 300,000,000 |
| Recent realtime messages kept per channel for replay | 1,000 | 1,000 | 1,000 | 1,000 | 1,000 |
