Realtime application patterns

Practical Sockudo patterns for public channels, private auth, presence, history, mutable messages, annotations, and scaling.

4 min read
View .mdEdit on GitHub

This page collects the patterns most Sockudo applications are built from: public feeds, private and presence channels, recovery and rewind, mutable messages, annotations, and the shape of a scaled deployment. Use it as a blueprint when you design a new realtime feature, and as a checklist when you review one.

Sockudo starts Pusher-compatible and becomes Sockudo-native when you opt into Protocol V2 features. The safest production pattern is to keep untrusted clients simple and put authority in your backend.

The trust model

Browser or mobile SDKSockudoYour backendHistory / versionstorePush queue WebSocket subscribeprivate/presence auth requestsigned auth responsesigned HTTP publishfanout
flowchart LR
  B[Browser or mobile SDK] -->|WebSocket subscribe| S[Sockudo]
  B -->|private/presence auth request| A[Your backend]
  A -->|signed auth response| B
  A -->|signed HTTP publish| S
  S -->|fanout| B
  S --> H[(History / version store)]
  S --> P[(Push queue)]

Three actors, three roles:

  • Clients hold only the app key. They connect, subscribe, and render. They can be inspected and modified by their users, so nothing they send is trusted on its own.
  • Your backend holds the app secret. It decides who may join which private or presence channel, signs those decisions, and publishes business events over the signed HTTP API.
  • Sockudo verifies signatures, fans messages out, and keeps history, versions, and the push queue.

Every pattern below follows from that split: authorization decisions are made in your backend, and Sockudo enforces the signed result.

Public feed

Public channels require no channel auth. Use them for data that is safe for anyone with the app key to receive.

import Sockudo from "@sockudo/client";
const client = new Sockudo("app-key", {
wsHost: "realtime.example.com",
forceTLS: true,
});
const channel = client.subscribe("market:btc");
channel.bind("price.updated", (event) => {
renderPrice(event.data);
});

Publish from a trusted backend:

await sockudo.trigger("market:btc", "price.updated", {
symbol: "BTC",
price: "104200.00",
});

Private channel

Private channels prove the user may subscribe before Sockudo admits the subscription. Channels whose name starts with private- trigger the flow automatically.

  1. The client opens a WebSocket and receives a socket_id.
  2. On subscribe("private-..."), the client SDK posts socket_id and channel_name to your channelAuthorization.endpoint.
  3. Your backend authenticates the user, checks the channel against its own policy, and signs the pair with the app secret.
  4. The client sends the signature to Sockudo, which verifies it and completes the subscription.
const client = new Sockudo("app-key", {
wsHost: "realtime.example.com",
forceTLS: true,
channelAuthorization: {
endpoint: "/api/sockudo/channel-auth",
headers: { "x-csrf": csrfToken },
},
});
const account = client.subscribe("private-account:user-42");
account.bind("invoice.paid", updateInvoice);

Backend auth should derive the channel from verified user state, not from a trusted-looking request body.

app.post("/api/sockudo/channel-auth", async (req, res) => {
const user = requireUser(req);
const { socket_id, channel_name } = req.body;
if (channel_name !== `private-account:${user.id}`) {
return res.status(403).json({ error: "forbidden" });
}
res.json(sockudo.authorizeChannel(socket_id, channel_name));
});

Presence room

Presence channels add a current member list and join/leave events.

const room = client.subscribe("presence-room:incident-123");
room.bind("pusher:subscription_succeeded", (members) => {
renderMembers(members);
});
room.bind("pusher:member_added", (member) => {
addMember(member.id, member.info);
});
room.bind("pusher:member_removed", (member) => {
removeMember(member.id);
});

Presence auth includes user data:

res.json(sockudo.authorizeChannel(socketId, channelName, {
user_id: user.id,
user_info: {
name: user.name,
role: user.role,
},
}));

Members are keyed by user_id, so one user with several tabs appears once: member_added fires on the first connection and member_removed after the last one leaves. Keep user_info small; it is capped by presence.max_member_size_in_kb (default 2 KB) and sent to every member.

Protocol V2 recovery and rewind

Protocol V2 clients can recover missed messages and ask for recent history during subscribe.

  • Recovery fills the gap after a short disconnect, so a client that was already subscribed sees every message exactly as if it had stayed connected.
  • Rewind gives a client that is joining now the last few messages, so a new chat window or dashboard starts populated.
const client = new Sockudo("app-key", {
wsHost: "realtime.example.com",
forceTLS: true,
protocolVersion: 2,
connectionRecovery: true,
});
const orders = client.subscribe("private-orders:user-42", {
rewind: { count: 50 },
});
orders.bind("sockudo:rewind_complete", ({ historical_count, live_count }) => {
console.log({ historical_count, live_count });
});
client.bind("sockudo:resume_success", ({ recovered, failed }) => {
console.log("resume", { recovered, failed });
});
V2 client
Sockudo
Durable history
1subscribe with rewind
2read history until attach serial
3historical page
4historical messages
5buffered live messages
6sockudo:rewind_complete
7network interruption
8resume positions
9cold replay if hot buffer expired
10sockudo:resume_success or resume_failed
sequenceDiagram
  participant C as V2 client
  participant S as Sockudo
  participant H as Durable history

  C->>S: subscribe with rewind
  S->>H: read history until attach serial
  H-->>S: historical page
  S-->>C: historical messages
  S-->>C: buffered live messages
  S-->>C: sockudo:rewind_complete
  C--xS: network interruption
  C->>S: resume positions
  S->>H: cold replay if hot buffer expired
  S-->>C: sockudo:resume_success or resume_failed

Use until_attach for late joins: it prevents a history page from racing with live messages above the attach serial.

Mutable messages

Mutable messages let a logical message be updated, deleted, appended, and summarized while keeping a version history. Every subscriber converges on the same latest version, and late joiners receive that version rather than the original create payload.

const latest = await channel.getMessage("msg_01J");
const versions = await channel.getMessageVersions("msg_01J", {
limit: 20,
direction: "oldest_first",
});

Trusted backends mutate through signed HTTP:

POST /apps/{app_id}/channels/private-doc:123/messages/msg_01J/update
Content-Type: application/json
{
"data": { "title": "Final incident report" },
"description": "user edit",
"metadata": { "editor": "user-42" },
"op_id": "edit-msg_01J-title-v2"
}

Append is the right primitive for streams:

{
"data": "next generated token ",
"extras": {
"ai": {
"transport": {
"run-id": "run_123",
"stream-id": "text",
"status": "streaming"
}
}
},
"op_id": "run_123:text:00042"
}

A stable op_id per operation makes retries safe: a repeated op_id returns status: "duplicate" instead of appending twice. See Mutable messages.

Annotations

Annotations attach secondary state to a message without rewriting the message itself. Use them for reactions, read receipts, moderation notes, delivery receipts, and summaries.

POST /apps/{app_id}/channels/chat/messages/msg_01J/annotations
Content-Type: application/json
{
"type": "reactions:distinct.v1",
"name": "thumbs-up",
"clientId": "user-42",
"count": 1
}

Annotation permissions are separate from message mutation permissions, so a user can react to a message they are not allowed to edit.

Backend publishing checklist

ConcernRecommendation
SecretsKeep app secrets and provider credentials server-side.
IdempotencySend idempotency_key for business events and op_id for mutations.
EchoUse socket_id when the originating client already applied an optimistic update.
Payload sizeSend stable identifiers and fetch large state from your app API.
AuthSign private, presence, encrypted, and user auth from your backend.
HistoryStore opaque cursors unchanged. Do not parse cursor internals.

Scaling shape

Sockudo cluster Load balancerAdapter busShared cacheHistory + versionstoreWebhook / push queueNode ANode BNode C adapter fanout
flowchart TB
  LB[Load balancer] --> Cluster
  subgraph Cluster [Sockudo cluster]
    N1[Node A]
    N2[Node B]
    N3[Node C]
  end
  Cluster <-->|adapter fanout| Bus[(Adapter bus)]
  Cluster --> Cache[(Shared cache)]
  Cluster --> Store[(History + version store)]
  Cluster --> Queue[(Webhook / push queue)]

The adapter bus is any horizontal adapter: Redis, Redis Cluster, NATS, Kafka, RabbitMQ, Pulsar, Google Pub/Sub, Apache Iggy, or OMQ.

For horizontal deployments, avoid memory-only cache, queue, history, and version stores. Memory is fine for local development and single-node demos; production clusters need shared stores for idempotency, recovery, push dispatch, and durable history continuity.

Normal Sockudo vs AI Transport

NeedNormal SockudoAI Transport
Broadcast app eventstrigger, channels, private authNot needed
Presence/collaborationPresence channelsUsed for agent/user state too
Recover after reconnectProtocol V2 recoveryRequired for durable runs
Persist channel historyDurable historyRequired for sessions
Edit or append messagesMutable messagesUsed for streamed output
Wake offline usersPush notificationsUsed for background agents
Model/provider integrationYour app codeProvider adapters and run lifecycle

Start with normal Sockudo when you are building realtime product events. Add AI Transport when model runs need to outlive one HTTP request, one browser tab, or one device.

Next steps