Realtime
Realtime is one capability, realtime, with two channels that the consent screen keeps apart, since they are
trusted differently: updates, how a page that shows a module route's answer hears that it changed and asks again at
once (for both kinds of module), and sockets, two-way connections with visitors (trusted modules only). It was
called live until 15 November 2026 (decision 0002 point 9.1). This page says where it lives, how it is checked and
how it is tested. Visitors' pages first; then team members' screens, whose first
account is the entry editor's "who else has this open".
How it works
- A module's public or account
GETroute that says what it answers (answer) names its answer's topic:realtime: request => `order:${id}`(1 to 200 letters, digits and:._-; nothing for no topic). - A client island keeps that answer with a repeating call that is realtime:
repeat: { every: 30, while: <condition>, realtime: true }. After the call went well, the islands' runtime opens the route's own address withAccept: text/event-stream(the browser'sEventSource, with the visitor's cookies). - The API runs the route as for any call (its rate limit, auth and handler) and only then opens the stream on
realtime:<plugin>:<topic>. A route that refuses the call opens nothing. - In its change's transaction (
inTransaction; it goes once that commits,afterCommit) or after it, the module callssendRealtimeUpdate(ctx, topic). Every container with a stream on that topic hears it through Redis and sends achangedevent; the page asks the route again, and the scheduled call is skipped.
An update says only "ask again", never what changed: what the page sees is always the route's own answer to that
visitor. The browser reconnects by itself (after 5 seconds) and then asks again too, in case it missed one. every
stays the safety net for a page whose stream could not open (Redis away, an old browser, a proxy that cuts it).
Limits
- A stream ends after 5 minutes (
REALTIME_STREAM_MS); the browser opens it again, through the route's checks. - A comment every 25 seconds (
REALTIME_PING_MS) keeps proxies from closing it;X-Accel-Buffering: nokeeps nginx from holding it back. - One address keeps at most 10 streams open per container (
REALTIME_STREAMS_PER_IP); the next answers 429. - Each stream counts against the route's own rate limit, like any call.
- A repeating call stops after two minutes (
MAX_REPEAT_MS), and so does its listening.
Team members' screens
The entry editor shows the other team members who have the same entry open, and says at once when one of them saves it (Collections). Core's own, not a module's:
- The editor sends a heartbeat (
POST /api/collections/<slug>/<id>/presence) every 10 seconds while its tab is visible, says goodbye (DELETE) when it closes, and listens to the same address withtext/event-stream:presenceevents ({ others: [{ id, name }] }) andsavedevents ({ by }). - A member is kept in Redis for 20 seconds after their last heartbeat. A member joining or leaving, and every save of
the entry, goes between containers on the entry's team topic (
team:entries:<slug>:<id>); each stream then reads again what its member may see. - The admin's session only, never a token, read without extending it. Every call checks the collection's
readaction; the stream checks the session and the action again on every message and every 10 seconds, and ends when either fails. Heartbeats: 30 a minute per account. The stream's other limits are the visitors' (five minutes, pinged every 25 seconds), with at most ten per member per container. Switched off with the realtime feature. - Tested in
shade/test/features/presence/server/presence.test.ts,apps/api/test/http/controllers/presence.test.ts(two containers on one Redis) ande2e/tests/presence.spec.ts(two members in two browsers).
Two-way connections: sockets
Server-sent events only say "ask again". For a chat, editing together or a live game, a page needs many small
messages in both directions. A trusted module may declare WebSocket routes in the manifest part realtime, as its sockets, under
/api/v1/account/<plugin>/…, served by the public container (and all). The realtime capability covers them, and its
consent says in a line of its own, apart from the updates, that the module keeps two-way connections with visitors. An untrusted module cannot have sockets: its manifest
is refused at load and when it is installed, because socket messages carry data (an untrusted module keeps the "ask
again" updates above).
import { defineModule, sendRealtimeMessage } from '@shadestack/module-sdk/server'
import * as z from 'zod'
export default defineModule({
name: 'chat',
// …accounts: { roles: { member: { can: ['chat.talk'] } } }, capabilities: { realtime: { need: 'required' } }
realtime: { sockets: [{
path: '/rooms/:room',
auth: { account: 'chat.talk' },
// Each message type with the schema of its `data`; anything else closes the connection.
messages: { say: z.object({ text: z.string().max(500) }) },
// The topics this connection listens to, decided before it opens. Throw to refuse it.
topics: async (ctx, request) => [`room:${request.params.room}`],
// Runs per message, as the module's own actor; `message.account` is the visitor.
message: async (ctx, message, connection) => {
await sendRealtimeMessage(ctx, `room:${message.params.room}`, 'said', { text: message.data.text, from: message.account?.id })
connection.send('sent')
}
}] }
})
A page sends and gets JSON messages of the form { "type": "say", "data": { "text": "Hello" } }. A ShadeError the
handler throws comes back as an error message ({ code, message }); any other error closes the connection and goes
to the error log.
Checks before a connection opens
The upgrade is checked like a call to an account route, and a refused one gets an ordinary HTTP answer the page can read:
- the socket exists, its module is on, and the realtime feature and the module's
realtimecapability are on (404 otherwise); - the page's
Originis the site's or one of the other frontends' (Settings, Other frontends), else 403: another site cannot open a connection with a visitor's cookie; - the socket's rate limit (a public socket must declare one, per IP; an account socket gets 60 a minute per account) and, for account sockets, 300 a minute per IP before the session is read;
- for
'account'and{ account: '<ability>' }, the signed-in account (401) and their ability (403); - the module's own
topics(throwforbidden()for a room the account may not enter); - at most 10 open connections per address in one container (
SOCKET_LIMITS.perAddress; a module may setmaxConnectionsPerAddresslower for its socket), else 429. Redis must take the subscriptions (503 otherwise).
Limits
- A message is JSON of at most 64 KB, in both directions. At most 20 messages a second per connection
(
maxMessagesPerSecondsets it lower); more closes the connection. - Messages of one connection run one after the other; at most 50 wait for the handler, and a connection that cannot keep up with what is sent to it (over 1 MB unsent) is closed.
sendRealtimeMessage(ctx, topic, type, data)goes through Redis to every container's connections on that topic. In a transaction (inTransaction) it goes once that commits, like a realtime update, so a rollback never reaches visitors. Topics are the module's own (room:<id>,account:<id>): 1 to 200 letters, digits and:._-, at most 20 per connection. Redis being away fails the send (503), since a lost message is not asked for again.
How a connection ends
The close code says why, so a page knows whether to open a new connection:
| Code | Why | The page |
|---|---|---|
| 1001 | 30 minutes passed (SOCKET_LIMITS.lifetimeMs), or the container is stopping | opens a new one at once, through the checks |
| 4403 | the visitor signed out or lost the ability (checked every 15 seconds) | does not reconnect |
| 4404 | the module, its realtime capability or the realtime feature was switched off | does not reconnect |
| 1003, 1007, 1008, 1009 | not text, not valid JSON of the declared type, an undeclared type or too many messages, over 64 KB | fixes its code |
| 1011 | the module's handler failed (see the error log) | may retry later |
| 1013 | it cannot keep up with what is sent to it | may retry later |
| 1000 | the module closed it (connection.close()) |
A module's own client code uses the browser's WebSocket (new WebSocket('wss://www.example.com/api/v1/account/chat/rooms/lobby');
the visitor's cookie goes with it). In the website editor an interactive part listens and sends with two actions (experimental until a
second module uses them):
- A socket state holds what the socket says:
{ status, count, type }, the status beingconnecting,open,closedorfailed,counthow many messages came andtypethe last one's type. Without JavaScript it staysclosedand the part shows what the server rendered. - Listen to socket (
listenSocket, runs when the part loads) names the module, the socket's path (/rooms/:room, its parameters given by formulas) and the state. It can run other read-only actions after each message and when the connection comes back (then), typically reading the module's route again: the message data itself is not shown, so the route stays the one source of what the page displays. The connection comes back after a drop, waiting 1 second and then longer each time up to 30 seconds, and ends when the visitor leaves the page. - Send on socket (
sendSocket) sends a message of a type the module's socket declares; any other is refused when the page is saved.
The appointments module's Free times, live component is the first account: it shows the free times and reads them again when
someone else books or cancels.
Metrics: shade_socket_connections_open, shade_socket_closes_total{reason} and shade_socket_messages_total{direction}.
The reverse proxy must pass WebSocket upgrades
Caddy and Traefik do by default. Nginx needs the upgrade headers and a read timeout above the 25 seconds between the API's pings:
location /api/v1/account/ {
proxy_pass http://127.0.0.1:4001;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 120s;
}
Where it is in the code, and its tests: shade/features/realtime/README.md in the shade repository.