Skip to content
cabby v0.6.0Cabby 0.6.0 release notes

History, recovery and presence

Without a broker, Cabby keeps nothing: a broadcast reaches the clients connected at that moment, and a client that reconnects starts from scratch. With a broker, Cabby keeps the recent history of each stream and the state of each session, so a client that comes back gets its session and the messages it missed.

Pick a broker

--broker Where history and sessions live After Cabby restarts Nodes Presence
none (the default) nowhere nothing to keep any none
memory the node's memory lost one per node
sqlite memory and a file kept after a graceful stop one per node, not saved
redis Redis kept many, shared shared by every node
postgres PostgreSQL kept many, shared none
nats NATS JetStream kept many, shared none

On several nodes, the in-memory and SQLite brokers keep only what each node accepted itself. A client that reconnects to another node starts a new session, and can miss messages even when its history request succeeds. Several nodes need a shared broker (Several nodes).

--presets=broker picks memory. The startup log names the broker and its limits:

INF Using in-memory broker (epoch: n1PL, history limit: 100, history ttl: 300s, sessions ttl: 300s, presence ttl: 15s)

Without one, it says Using no-op (legacy) broker.

Flag Default What it limits
--history_limit 100 Messages kept per stream
--history_ttl 300 Seconds a message stays in a stream's history
--sessions_ttl 300 Seconds a disconnected session can still be restored
--presence_ttl 15 Seconds a member stays listed after its connection is gone

How a client catches up

Every broadcast the broker stores gets a place in its stream: an epoch and an offset.

{"identifier":"{\"channel\":\"$pubsub\",\"stream_name\":\"lobby\"}","message":{"n":3},"stream_id":"lobby","epoch":"n1PL","offset":3}

Live messages arrive in offset order too, so what a client catches up on and what follows live line up. On one node this holds for every client (Action Cable, Turbo Streams, SSE, Pusher) and every broker. Across nodes, the Redis broker with Redis pub/sub on the same Redis orders the whole stream; other brokers and pub/sub pairs order the broadcasts that went through each node.

Missed messages come back in two ways. When a client's connection drops, the client asks for them, as below. When a node's link to pub/sub drops while its clients stay connected, the node reads what its streams missed from a shared broker (Redis, PostgreSQL or NATS) once the link is back, and delivers it as ordinary live messages, once and in order; the in-memory and SQLite brokers can't (Several nodes). A client that reconnects meanwhile can get a message both ways, with the same offset; @cabby/web shows it once.

Recovery needs the actioncable-v1-ext-json subprotocol. A client that reconnects does two things:

  1. It restores its session. It names its previous session id in ?sid=, or in the X-Cabby-Restore-Sid header (X-AnyCable-Restore-Sid works too). Cabby answers with a new session id, "restored":true and the subscriptions it got back. It doesn't call connect or subscribe again through your app. A session is restored once, and only after it has gone: an id that has already restored a session, or the id of a session still connected, gets a new session, as does a session that expired. The next reconnect names the new id.

    {"type":"welcome","sid":"DRibOW12lGpm3qrvIKh_Q","restored":true,"restored_ids":["{\"channel\":\"$pubsub\",\"stream_name\":\"lobby\"}"]}
    
  2. It asks for what it missed, from the last epoch and offset it saw in each stream. Cabby sends the newer messages, then confirm_history.

    {"command":"history","identifier":"{\"channel\":\"$pubsub\",\"stream_name\":\"lobby\"}","history":{"streams":{"lobby":{"epoch":"n1PL","offset":2}}}}
    

    A new subscription can ask for the messages since a time instead, in Unix seconds: "history":{"since":1795977414} next to "command":"subscribe".

If the epoch no longer matches, because the in-memory broker restarted or SQLite came back after a crash, Cabby answers reject_history. The client can't tell which messages it missed, so it should load the current state from your app again. Without a broker, every history request gets reject_history, and Cabby logs couldn't retrieve history with error="history not supported".

@cabby/web does all of this for you: it restores the session and asks for the missed messages after a short disconnect. Turbo Streams do too once bin/rails g cabby:client runs them on it (Hotwire); @rails/actioncable, and Turbo's own connection, don't recover.

When catching up fails

Each @cabby/web subscription reports how catching up went with a history event: { ok: true }, or { ok: false } when Cabby answers reject_history or doesn't answer within historyTimeout (5 seconds). Cabby rejects when the page's last message has left the stream's history (by default the last 100 messages, for up to 300 seconds), when the epoch changed, or when there is no broker. initial: true marks the answer to a subscription's first request, which exists only when the subscription was created with since (a page rendered on the server, see Hotwire); after a reconnect, initial is absent.

Live messages keep coming and only the gap is lost, so load the current state from your app and skip the messages the page already shows. A fetch can't loop:

const room = cabby.stream("room-1")
const shown = new Set()

function show(message) {
  if (shown.has(message.id)) return // already on the page
  shown.add(message.id)
  // add the message to the page
}

room.on("message", show)
room.on("history", async ({ ok }) => {
  if (ok) return
  const response = await fetch("/rooms/1/messages.json")
  for (const message of await response.json()) show(message)
})

On a Turbo page, each turbo_stream_from element reports the answer as a cabby:history event that bubbles to document, with { ok, initial } as detail. Fetch the list again whenever it fails, or reload the page only after a reconnect: a failed first request (initial: true) would fail again after the reload, on a server without a broker for example, and the page would loop.

// Load the list again whenever a catch-up fails (a fetch cannot loop)
document.addEventListener("cabby:history", async ({ detail }) => {
  if (detail.ok) return
  const html = await (await fetch(location.href)).text()
  const fresh = new DOMParser().parseFromString(html, "text/html")
  document.querySelector("#messages").replaceWith(fresh.querySelector("#messages"))
})

// Or reload the page, only after a reconnect: a failed first request would fail again
document.addEventListener("cabby:history", ({ detail }) => {
  if (!detail.ok && !detail.initial) location.reload()
})

On a server without a broker, a page with both loads once and fetches itself once.

Deploys and restarts

  • Deploying your app doesn't touch Cabby's connections: Cabby runs apart from your web processes, so clients stay connected.
  • Restarting Cabby (an upgrade, docker stop, kamal accessory reboot cabby) closes every connection. On SIGTERM or SIGINT, Cabby tells each client {"type":"disconnect","reason":"server_restart","reconnect":true}, closes the socket and waits up to --shutdown_timeout seconds (30) to finish. Clients reconnect. With SQLite, Redis, PostgreSQL or NATS they get their sessions and missed messages back; with the in-memory broker they start again.
  • Several nodes need a shared broker (Redis, PostgreSQL or NATS). A client that reconnects to another node restores its session there (Several nodes).

Presence

Presence tells the subscribers of a stream who else is there. A client joins with an id and any JSON it wants the others to see:

{"command":"join","identifier":"{\"channel\":\"$pubsub\",\"stream_name\":\"lobby\"}","presence":{"id":"u1","info":{"name":"Ada"}}}

Every subscriber, the one that joined included, gets the event:

{"type":"presence","identifier":"{\"channel\":\"$pubsub\",\"stream_name\":\"lobby\"}","message":{"id":"u1","info":{"name":"Ada"},"type":"join"}}

"command":"presence" asks for the current list, and "command":"leave" leaves:

{"type":"presence","identifier":"{\"channel\":\"$pubsub\",\"stream_name\":\"lobby\"}","message":{"type":"info","total":1,"records":[{"info":{"name":"Ada"},"id":"u1"}]}}

What the list holds depends on the broker:

--broker One node Several nodes
redis every member one list for every node, each user once
memory, sqlite every member (SQLite doesn't save it) per node: each node lists and announces its own members
postgres, nats, none no presence no presence

Without presence, Cabby answers "message":{"type":"error","total":0} and logs presence not supported.

  • Presence works on public streams, on signed streams (unless --streams_presence=false), on Pusher presence- channels (Laravel) and on your app's channels, where a Rails channel joins with join_presence (Rails).
  • With the Redis broker, a join is announced once, when a user's first session on any node joins, and a leave once, when the last one goes. The members of a node that dies leave after --presence_ttl, announced once by another node. A restored session keeps its presence on the node that restores it.
  • A member whose connection drops without leave stays listed for --presence_ttl seconds (15), then the others get a leave event.
  • Once your app has joined a subscription to presence, from a channel's callback or action, the app sets that subscription's presence until the client unsubscribes. The client's own join and leave commands for it, and presence sent with its subscribe, change nothing and announce nothing: the client gets no reply, and Cabby logs a warning (Troubleshooting). The app's later answers still join and leave, and "command":"presence" still lists the members. On $pubsub streams, and on channels where the app only enables presence without joining, the client's join and leave work as above. With the Redis broker, this holds on every node, also after a restore on another one. If the client had joined on its own before the app's first join, that join replaces the client's presence: the members get its leave, then the app's join.
  • Your app can read the list over HTTP: GET /api/presence/<stream>/users, with Authorization: Bearer <key>. Without --api_secret, the key is the HMAC-SHA256 of api-cable with --secret, in hex.

With the Redis broker on several nodes:

  • Give every node the same --presence_ttl.
  • While Redis is unreachable, presence requests fail: "type":"error", a Pusher presence- subscription fails, and the users endpoints answer 400. The members of a node cut off for longer than --presence_ttl leave for the others, and join again once it's back. When every node loses Redis at once, connected members aren't announced as leaving (with the default TTL).
  • Presence events and stored broadcasts of one stream aren't ordered with each other: a message broadcast right after a join can arrive before it.

Whispers

A whisper is a short message from one client to the other subscribers of a stream, such as "typing…". Cabby passes it on without calling your app, doesn't send it back to the client that whispered, and doesn't keep it in history. It works with or without a broker.

{"command":"whisper","identifier":"{\"channel\":\"$pubsub\",\"stream_name\":\"lobby\"}","data":{"typing":true}}

The others receive "message":{"typing":true} for that identifier. Whispers are on for public streams, for signed streams with --streams_whisper, for a channel's stream your app opens with whisper: true (Rails), and for Pusher private- and presence- channels. Elsewhere Cabby drops them (with --debug, it logs whisper stream not found).

A whisper is a message between subscribers that chose to exchange them, so it reaches only the subscriptions that take whispers on its stream, on every node. A Turbo Streams or CableReady subscription of the same name, or a channel that streams from it without whisper: true, doesn't get it. A whisper needs the subscription, as the channel's other commands do: on a channel the client hasn't subscribed to, Cabby refuses it with unknown subscription. While nodes of 0.5 and 0.6 share pub/sub, set --whisper_compat_0_5 on the 0.6 nodes until the last 0.5 node is gone (Upgrading to 0.6).