# WebSocket

URL: https://docs.folkways.io/docs/realtime-api/websocket

GET /v1/ws: opening a connection, Hello and Welcome, heartbeats, token refresh, closing, reconnecting and the client checklist.

```http
GET wss://realtime.folkways.net/v1/ws
```

A standard WebSocket upgrade. No headers, query string or cookies are read, so there is no token in the URL and no
CORS. Each message is **binary** and holds exactly one [packet](/docs/realtime-api/payloads) of up to 64 KiB; a text
message closes the connection with `BadFrame`.

<Diagram name="connection-lifecycle" alt="The client sends Hello with its token within 5 seconds and gets Welcome with its identity, limits and features. It subscribes and gets an optional Gap, a SubAck and any replay or snapshot, then live Deliver frames. It publishes and gets a PubAck. It pings every 30 seconds and gets Pong; 90 seconds of silence closes it with Timeout. Sixty seconds before expiry it gets TokenExpiring, sends Reauth with a new token and gets OpOk. When the service ends a connection it sends Close with a code and a retry delay first." />

## Hello [#hello]

The first frame must be `Hello`, within **5 seconds** of connecting. Any other frame first closes the connection
with `HelloRequired`; no `Hello` in time closes it with `AuthRequired`.

| Field | Required | Meaning |
| --- | --- | --- |
| `token` | yes | The [token](/docs/realtime-api/authentication) |
| `client` | no | Your client's name and version, for troubleshooting |
| `device` | no | A label for this device or app instance, e.g. `ios`, `web-chrome`; at most 64 bytes. Shown in presence |
| `features` | no | `["invisible"]` keeps this connection out of presence |
| `max_frame_bytes` | no | The largest packet you want to receive |

## Welcome [#welcome]

The answer to a valid `Hello`:

| Field | Meaning |
| --- | --- |
| `identity` | The token's `sub`, or `anon:<session id>` for an anonymous connection |
| `anonymous` | `true` when the token named no one |
| `session_id` | This connection's ID, unique per connection |
| `expires_at_ms` | When the token expires |
| `server_time_ms` | The server's clock, for estimating your clock offset |
| `limits` | The [limits](/docs/realtime-api/limits) in force: sizes, heartbeat, rate limits |
| `segment_id`, `environment` | The segment, from the token, and its environment |
| `capabilities` | The rights granted, as `{ topic, ops }`, so an app can hide what it may not do |
| `features` | What this server offers: `presence`, `user-topics` (your [personal topic](/docs/concepts/topics#personal-topics)), `invisible` |
| `resumed` | Always `false`: there is no session resume. Subscribe again after every reconnect |

If the token is refused, the answer is a `Close` instead: `AuthInvalid`, `AuthExpired`, `AuthRevoked`, `Suspended`,
`QuotaExceeded` (a connection limit) or `Draining`.

## Heartbeat [#heartbeat]

Send `Ping { nonce, ts_ms }` every `limits.heartbeat_ms` (30 seconds); the server answers `Pong` with the same
`nonce`. A connection that sends nothing for `limits.idle_timeout_ms` (90 seconds) is closed with `Timeout`.

## Token refresh [#token-refresh]

Sixty seconds before the token expires, the server sends `TokenExpiring { expires_at_ms }`. Get a new token and send
`Reauth { token }`; the server answers `OpOk`, and subscriptions carry on.

- The new token must be for the same segment and identity, or the connection closes with `AuthInvalid`.
- An anonymous connection may `Reauth` with a signed-in user's token and keep its subscriptions. If that identity is
  at its connection limit and the segment refuses new connections, the answer is `OpError { QuotaExceeded }` and the
  connection stays anonymous.
- If the new token drops a right, each affected subscription ends with `SubEnded { Forbidden }` before the `OpOk`.
- Without a refresh, the connection closes with `AuthExpired` at expiry.

## Closing [#closing]

When the server ends a connection, it first sends `Close { code, reason, retry_after_ms }`. Use the `code`; the
WebSocket close code is only a coarse mirror:

| WebSocket code | Meaning |
| --- | --- |
| `1000` | Normal |
| `1001` | The server is draining (restarting) |
| `1008` | Any other refusal: authentication, permissions, limits |
| `1009` | A packet was too large |
| `1011` | Internal error |
| `1013` | Try again later: backpressure, overload, unavailable |

A connection can also drop with no `Close` at all: the network goes away, a proxy times out, or a server stops
unexpectedly. Treat that as a temporary disconnect: reconnect with backoff and resume from your cursors.

To close politely, send `Close`.

**Draining.** A server shutting down closes every connection with `Close { Draining }`, each with its own
`retry_after_ms` (between about 1 and 5 seconds). Wait that long, reconnect (you reach another server) and resume
each topic from its cursor.

## Reconnecting [#reconnecting]

1. Wait at least `retry_after_ms`, with exponential backoff and full jitter on repeated failures.
2. Open a new connection and send `Hello`.
3. For each topic, send `Subscribe { start: After, cursor: <last processed> }`.
4. Handle any `Gap`.
5. Drop any event whose cursor isn't after your saved one.

**Don't reconnect automatically** after `Replaced` (a newer connection of the same identity took this one's place)
or `AuthRevoked` (your backend cut this user off). Never retry `AuthInvalid` with the same token.

## Connection limits [#connection-limits]

| Limit | Over it |
| --- | --- |
| The segment's or workspace's connection limit | `Close { QuotaExceeded }` in answer to `Hello` |
| Connections per identity | The identity's oldest connection is closed with `Replaced`, or the new one refused with `QuotaExceeded`, as the segment is set |
| New connections per minute in the segment | `Close { RateLimited, retry_after_ms }` |
| Too many failed authentications from one address in a minute | `Close { RateLimited, retry_after_ms }`, even for a valid token |
| Too many sockets from one address that haven't sent `Hello` | The upgrade is refused with HTTP `429` |

## Client checklist [#client-checklist]

- Send `Hello` with the token as the first frame; never put a token in a URL.
- Use non-zero `corr` values for requests, and match replies by `corr`. Unsolicited frames have `corr` 0.
- Ping every `heartbeat_ms`.
- Refresh on `TokenExpiring` with `Reauth`.
- Save the last processed cursor per topic; on reconnect, subscribe after it and handle `Gap`.
- Drop duplicates by `(epoch, seq)`.
- Point receipts, edits and reactions at `uid`, never at a cursor.
- Give each stream publish a fresh 128-bit `idempotency_key`, and reuse it when retrying that publish.
- Reconnect with backoff and full jitter, honouring `retry_after_ms`.
- Treat `Backpressure` and `Draining` as "reconnect and resume".
- Don't reconnect automatically after `Replaced` or `AuthRevoked`.
- Send a `device` label if your users connect from several devices.
- Order events by cursor, not by arrival.
