# Subscribe

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

The Subscribe frame, start positions, gaps, snapshots, event type filters, unsubscribing, flow control and reading presence.

Subscribing is a WebSocket feature. Over HTTP, use [`POST /v1/poll`](/docs/realtime-api/poll), which takes the same
`Subscribe` entries.

## The Subscribe frame [#the-subscribe-frame]

| Field | Default | Meaning |
| --- | --- | --- |
| `topic` or `topic_id` | required | One concrete topic. Subscribe by name after every reconnect; IDs can change when a topic is recreated |
| `start` | `Latest` | Where stream events start: `Latest`, `Oldest`, `After` (with `cursor`) or `LastN` (with `last_n`) |
| `cursor` | | With `After`: the last event you processed, `{ epoch, seq }` |
| `last_n` | | With `LastN`: how many retained events to replay |
| `on_gap` | `FromOldest` | If the cursor can't be honoured: `FromOldest`, `FromLatest` or `Fail` |
| `snapshot` | `true` | Send current KV values and signals first |
| `types` | all | Event types to receive: `Durable`, `LastValue`, `Ephemeral`. An inbox following many rooms usually wants `[Durable]` |

| `start` | Stream events delivered |
| --- | --- |
| `Latest` | Only new events |
| `Oldest` | Everything still retained, then live |
| `After` + `cursor` | Everything after the cursor, then live |
| `LastN` + `last_n` | The last N retained events, then live |

## Replies, in order [#replies-in-order]

1. An optional **`Gap`**, if the position can't be honoured.
2. **`SubAck { topic_id, deliveries, oldest, latest, catching_up, snapshot_follows, state_latest }`**, with your
   `corr`. `deliveries` lists the types the topic allows; `oldest` and `latest` are the retained range.
3. The **replay** of stream events, as `Deliver { replayed: true }`.
4. One or more **`Snapshot`** chunks of current KV values and signals, when you receive those types and `snapshot`
   is on. Each has `snapshot_id`, `chunk`, `last_chunk` and `fence`, the position the snapshot reflects.
5. Live **`Deliver { replayed: false }`** frames, with `corr` 0.

Nothing is missed or repeated between the replay and live events. Each `Deliver` carries one topic's
[events](/docs/realtime-api/frames#event).

Subscribing again to a topic you already follow moves your position. Subscriptions are to concrete topics only;
there are no pattern subscriptions.

## Gaps [#gaps]

`Gap { reason, requested, oldest, latest, resumed }`:

| `reason` | Meaning |
| --- | --- |
| `Expired` | The events after your cursor were purged |
| `EpochLost` | Your cursor is from an earlier epoch |

Then `on_gap` decides: `FromOldest` replays from the oldest retained event, `FromLatest` goes live, `Fail` stops
(`resumed: false`, no subscription). Fetch the missing range from your own backend. A cursor ahead of the topic gets
`OpError { InvalidCursor }`.

## Unsubscribe [#unsubscribe]

`Unsubscribe { topic | topic_id }` always answers `OpOk`, even if you weren't subscribed.

## The server ending a subscription [#the-server-ending-a-subscription]

`SubEnded { topic_id, code, message }` means the server ended a subscription: for example your token refresh dropped
the right (`Forbidden`), or your backend removed you from a private topic.

## Flow control [#flow-control]

`CursorAck { acks: [{ topic_id, cursor }] }` tells the server how far you have processed. It is a hint only and gets
no reply.

If your connection can't keep up and its send queue fills, it is closed with `Close { Backpressure, retry_after_ms }`.
Events stay retained, so reconnect and resume from your cursor.

When a segment's outbound traffic goes over its limit, the server keeps delivering every event and slows publishers
instead, with `Flow { action, retry_after_ms }` (`corr` 0):

| `action` | Meaning | What to do |
| --- | --- | --- |
| `Throttle` | Deliveries are behind | Publish more slowly; publishes are still accepted |
| `Pause` | Behind by more than a second | Stop publishing; until `Resume`, publishes get `RateLimited` |
| `Resume` | Caught up | Publish as before |

## Presence [#presence]

Presence is read by subscribing to system topics, which are KV topics:

| Subscribe to | Needs | Receives |
| --- | --- | --- |
| `$online/{identity}` | `presence` on it, or nothing for your own | One entry per open connection of the identity, keyed by session ID |
| `$presence/{topic}` | `presence` on `{topic}` or a pattern covering it | One entry per connection present in the topic or below it, keyed `identity#session_id` |

Entries are JSON `{ identity, session, device, since, data }`; a leave is a tombstone with the same key. To set your
own status data, publish up to 1,024 bytes of JSON to your own `$online/{identity}` with `delivery: LastValue` and no
`key`. See [Presence](/docs/primitives/presence).

## Personal topic [#personal-topic]

When `Welcome.features` includes `user-topics`, subscribe to your own `$user/{identity}`; it needs no capability. It
is a stream, so subscribe after a saved cursor (or from `Oldest`) to find invites sent while you were away.

## Errors [#errors]

| Code | When |
| --- | --- |
| `Forbidden` | No rule matches, or the token, rule or member entry doesn't allow `subscribe` |
| `InvalidTopic` | Not a valid topic name |
| `ClassMismatch` | `types` asks only for types the topic doesn't carry |
| `InvalidCursor` | The cursor is ahead of the topic |
| `QuotaExceeded` | Over 1,000 subscriptions on this connection, or the topic or personal-topic limit is reached |
| `RateLimited` | Too many subscribes per minute in the segment |
