Subscriptions
Since 0.18.0. Everything on this page shipped in 0.18.0: the backplane (cratestack#1266), refusal, filters and REST (cratestack#1267), subscription procedures, topics, the WebSocket binding and the Rust client (cratestack#1268), and the TypeScript and Dart clients. The design is
docs/design/subscriptions-websocket.mdin the framework repository.
A subscription is an op like any other. It has an op id, a policy, and an input. What it returns is a stream: once the server says Ready, nothing committed after that point is missed. The other outcome is that the stream ends with unavailable, and the client resubscribes and refetches. That single contract holds on every binding.
What you can subscribe to
Model feeds
model Note {
id Int @id
ownerId Int
body String
archived Boolean
@@allow("read", ownerId == auth().id)
@@deny("read", archived)
@@emit(created, updated, deleted)
@@subscribe
}@@subscribe requires @@emit(...). It works under transport rpc, where the op id is model.Note.subscribe, and under REST, where the feed is GET /notes/$subscribe.
Every event passes the subscriber's read policy: the same @@allow/@@deny rules get applies, decided against the event's record. Two cases are refused at open:
- A caller no row could pass. An anonymous caller on
ownerId == auth().idis refused withunauthenticated(401); an authenticated one withpermission_denied(403). - A policy that reads a
@server_onlycolumn. The event does not carry that column, so the policy cannot be decided.
A feed takes list's own filter syntax, plus operations and fields:
GET /rpc/subscribe/model.Note.subscribe?body__contains=keep&operations=created&fields=id,bodyThe filter is evaluated in memory against the event's row, and it only narrows what the policy already allows. Some inputs are refused with invalid_argument:
- paging and shaping keys (
limit,sort,include, …); - relation and full-text filters;
- a filter over a
@server_onlycolumn.
Rows that leave your feed. When an update moves a row out of your filter, or out of what your read policy lets you see, you receive an Updated event with matches: false. Its data is the row as you last saw it, not the new values, so remove that row (by its key) from your local copy. Ordinary events leave matches out, which means true. You are not told why the row left, and nothing is sent about rows you never matched. There is no exit event for update_many or for a feed whose operations exclude updated, so still refetch after a bulk update and when you reconnect. In the clients: ModelEvent.matches (Rust), matches?: boolean (TypeScript; test === false), CratestackModelEvent.matches (Dart).
Subscription procedures and topics
Live data that is not a row change has its own construct. A topic carries typed messages under a key, to every replica. A subscription procedure is the policy boundary that exposes one:
type RoomArgs {
roomId String
}
type ChatMessage {
roomId String
body String
}
topic RoomMessage(roomId: String): ChatMessage
subscription procedure roomMessages(args: RoomArgs): ChatMessage
@allow(auth() != null)The handler runs once, at open. Its Err refuses the subscription before Ready. The stream it returns is the subscription:
impl cratestack_schema::procedures::ProcedureRegistry for Rooms {
async fn room_messages(
&self,
db: &cratestack_schema::Cratestack,
_ctx: &CratestackContext,
args: room_messages::Args,
_authorized: room_messages::Authorized,
) -> Result<SubscriptionStream<room_messages::Output>, CratestackError> {
if args.args.roomId == "secret" {
return Err(CratestackError::Forbidden("not a member of this room".to_owned()));
}
db.topics().room_message(&args.args.roomId).subscribe().await
}
}db.topics().room_message(&id) has three methods:
publish(&msg)delivers to every current subscriber, on every replica.publish_in_tx(tx, &msg)sends the notification from inside your transaction, so the message is delivered only if the transaction commits:rustdb.transaction(async |tx| topics.room_message("r1").publish_in_tx(tx, &msg).await).await?;subscribe()is what a handler usually returns.
Inside an @isolation procedure, take topics from the handle you are given: tx_db.topics(). Their publish rides the procedure's transaction. The message is delivered when the attempt commits, and never for an attempt that errors or is retried after a serialization failure, so there is no need to publish "after the commit" yourself. With the default PgNotifyBackplane it notifies inside the transaction; with InProcessBackplane it is queued and sent once the attempt commits. Inside tx_db.transaction(async |tx| ..), call publish_in_tx(tx, &msg). If that transaction(..) rolls back, its messages are dropped even though the attempt around it commits.
A subscription procedure returns one item type (not T[]). It cannot declare @stream, @isolation, @no_idempotency, @status, @no_rate_limit or @mcp. It may declare @frames(unsigned) (below). It works under db = None too, with your own stream as the source.
Topics work under db = None as well, on cratestack-api: the same db.topics().room_tick(&id) with publish and subscribe, but no publish_in_tx, since there is no transaction; publish once the work is done. The default backplane is an InProcessBackplane shared by every Cratestack::builder().build() of the schema in the process, so it reaches one replica only. To reach others, pass your own SubscriptionBackplane with Cratestack::builder().with_backplane(Arc::new(..)). A db = None schema that declares a topic has a Cratestack that is Clone but not Copy.
Signed services: @frames(unsigned)
Since 0.20.4, cratestack#1378: the server and the generated Rust, TypeScript and Dart clients.
A service that requires signed requests cannot stream to a signed client, because a stream cannot be sealed. Mark a subscription procedure @frames(unsigned) to let it open signed:
subscription procedure roomMessages(args: RoomArgs): RoomEvent
@frames(unsigned)The open is verified like a unary call and @allow sees the principal its signature names, but the frames that follow are not signed. Treat each as a hint (an id) and re-read through a sealed call. The stream ends after max_signed_stream_life (default one hour) with unavailable / stream lifetime, and the client resubscribes. The only argument is unsigned; sealed and chain are reserved and refused, and @frames is refused on unary and @stream procedures and when repeated. It is part of the op contract, so adding or removing it is wire-incompatible, and it does not apply to @@subscribe model feeds. Details, the wire and the limits: Signed subscriptions.
The generated clients open it signed; a client that holds an envelope never opens a subscription in plain:
- Rust.
subscribe()seals the open (aPOSTof the input's CBOR on RPC, aGETwith a body on REST) and reads the plain stream, over cbor-seq (Autopicks it) or SSE. An unmarked subscription, a WebSocket or WebTransport pin, and REST onwasm32areEnvelopeError::StreamsUnsupported, with nothing sent. A stream that lostCratestack-Frames: unsigned, a forged plain200or the wrongContent-TypeisEnvelopeError::UnsignedFramesRefused. - TypeScript. Give the runtime
subscriptions: { seal: createSealedSubscriptions({ cose, contracts }) }. RPC only: a REST route is aCoseFailuremisuse. An unmarked subscription or a socket pin is aCratestackSubscriptionErrorwith codestreams_unsupported. The sealedfetchnever follows a redirect, and an unsigned refusal isunsigned_refusal, never a server code. A cross-origin browser page needs the server to sendAccess-Control-Expose-Headers: Cratestack-Frames. - Dart. Opt in with
CratestackSubscriptionOptions(sealsSubscriptions: true). The generated client then hands your signingCratestackHttpTransportthe route and contract inrequest.extraand refuses an answer without the marker (unsigned_frames_refused); an unmarked subscription and a socket pin arestreams_unsupported, and an unsigned refusal isunsigned_refusal. Without the opt-in a subscription opens as it always did. It never seals itself.
Each reconnect is a new signed open. A relay can forge the terminal unavailable frame, so resubscribe with a jittered backoff. See Signed subscriptions.
Every replica sees every event
Events reach subscribers through the subscription backplane. The default, PgNotifyBackplane, uses Postgres LISTEN/NOTIFY, and the writing transaction itself notifies. A subscriber on replica B therefore sees a write committed on replica A, in commit order, and only if it committed.
When the listener reconnects, events may have been lost, so every subscription on that replica ends with unavailable / "subscription interrupted". Behind PgBouncer in transaction mode, LISTEN does not work. In that case, run a single replica with Cratestack::builder(pool).with_backplane(Arc::new(cratestack::InProcessBackplane::new())).
The bindings
| Binding | Where | Frames | When |
|---|---|---|---|
| SSE | /rpc/subscribe/<op> (GET with the input as the query, or POST with a JSON body); REST GET /<plural>/$subscribe, GET /$procs/<name> | event: ready, event: message, one event: error; : keepalive every 15 s; JSON | everywhere |
application/cbor-seq (since 0.20.3, cratestack#1001) | the same SSE routes with Accept: application/cbor-seq: RPC GET and POST /rpc/subscribe/<op>, REST GET /<plural>/$subscribe, GET /$procs/<name> | one CBOR ServerFrame per item of a CBOR sequence; a CBOR null every 15 s; a Uuid is a byte string | a CBOR-only client, or a proxy that mangles text/event-stream; plain HTTP |
| WebSocket | GET /rpc/ws (/$ws on REST), with extension websocket { } + the websocket feature | Init, multiplexed Requests, Ready / next / end / err, cancel; CBOR (binary) or JSON (text) | one connection for many subscriptions; where UDP is blocked |
| WebTransport | CONNECT /rpc/wt on a separate UDP listener, with extension webtransport { } + the webtransport feature | the same frames, one QUIC stream per subscription | no head-of-line blocking; survives a network change |
(Since 0.19.6, cratestack#1360.) On the CBOR WebSocket and WebTransport bindings, an item is encoded the way a unary CBOR response is: a Uuid (every model event's eventId too) is a 16-byte string, and Bytes inside a Json field is a byte string. JSON frames (text messages, NDJSON) and SSE are byte-for-byte what they were: a Uuid is text and bytes are an integer array (base64 inside a Json field). A schema Bytes field is an integer array on every wire. A request's input may carry byte strings on CBOR too, though a Uuid subscription argument must still be text, because the input becomes a query string. Before this, the CBOR bindings sent Uuids as text and bytes inside a Json field as base64, and a request input holding a byte string closed the socket with 4400.
Serving the session bindings:
// WebSocket: a router to merge into yours.
let app = cratestack_schema::axum::rpc_router(db.clone(), registry.clone(), (), CborCodec, auth.clone(), limit)
.merge(db.subscriptions(registry.clone()).websocket(
// `.rate_limit(..)` is optional (since 0.19.3); without it, opens are unlimited.
WebSocketConfig::new().rate_limit(rate_limit_layer.for_subscriptions()),
auth.clone(),
));
// WebTransport: a second listener, on UDP.
let server = db.subscriptions(registry).webtransport(config, auth)?;
tokio::spawn(server.serve());Without a subscription procedure, db.subscriptions() takes no registry.
Both session bindings authenticate with the router's AuthProvider. A native client sends its credentials on the handshake; a browser, which cannot set headers there, sends them in the Init frame. The rules are the same on both:
A refusal sends
{id: 0, err}first, then closes:Close Meaning 4401 unauthenticated 4403 forbidden 4400 a malformed frame 4500 the provider could not decide; retry, do not sign out A later
Initrefreshes the credentials, and must name the same principal.The session closes with 4401 when the credential's
exppasses.Origins are same-origin by default (
OriginPolicy).Limits per socket and per principal are configuration (
WebSocketLimits,WebTransportLimits), never schema syntax.Opens can be rate limited (since 0.19.3):
.rate_limit(layer.for_subscriptions())onWebSocketConfigorWebTransportConfigcharges one token per subscriptionRequest. A throttled open is anerrframe withresource_exhaustedanddetails.retry_after_secs, and the socket stays open. SSE opens are charged byRateLimitLayeralready. See Rate limiting.
Clients
The call is the same in every language. It resolves, or starts emitting, after Ready. A refusal is an error of the call, never an item.
Rust (include_server_schema! or include_client_schema!):
let config = ClientConfig::new(base).with_subscription_transport(SubscriptionTransport::Auto);
let client = cratestack_schema::client::Client::new(CratestackClient::cbor(config));
let mut notes = client.notes().subscribe(&Default::default()).await?;
while let Some(event) = notes.recv().await { let event = event?; /* ModelEvent<Note> */ }Auto tries each binding the build has, in order, and moves on only when one cannot be opened:
- WebTransport, with the
client-webtransportfeature and the listener named in the config. - A WebSocket, with the
client-wsfeature. - SSE.
SubscriptionTransport::WebTransport, WebSocket, Sse and CborSeq (since 0.20.3) each pin one binding. Auto never picks CborSeq.
Both features are native-only. On cratestack-client they are named webtransport and ws.
let config = ClientConfig::new(base).with_webtransport(
"https://api.example.com:4433/rpc/wt".parse()?,
ServerTrust::NativeRoots, // or CertificateHashes(vec![dev_cert.sha256]) in development
);A WebTransport session that is not open within 3 s counts as unreachable, and that is remembered for 10 minutes, so a UDP-blocked network pays the wait once.
The client reads a WebSocket or WebTransport item the way a unary CBOR call is read, so a Uuid field decodes from its byte string (since 0.19.6). It still reads an older server's text Uuids, but a client from before this change cannot read a newer server's model events over those two bindings: upgrade them together, or pin SubscriptionTransport::Sse meanwhile. A partial model event (fields) read as ModelEvent<serde_json::Value> fails on a Uuid field over a socket; read it into a struct of Option<_> fields instead, or use SSE.
If you implement SubscriptionDispatcher by hand, open(request, codec) now takes the binding's codec and yields SubscriptionStream<RpcFrameValue>, and ServerFrame::next / ClientFrame::request take impl Into<RpcFrameValue>. Encode each item with RpcFrameValue::encode_with(&codec, &item), or yield serde_json::json!(..).into().
TypeScript (both REST and RPC packages):
const client = new CratestackClient("https://api.example.com", {
headers: { authorization: `Bearer ${token}` },
subscriptions: { webTransport: { url: "https://api.example.com:4433/rpc/wt" } },
});
for await (const event of client.notes.subscribe({ operations: ["created"] }, { signal })) {
render(event.data);
}"auto" (the default) tries three bindings in order:
- WebTransport, when you name its URL and the browser supports it.
- A shared WebSocket.
- SSE over
fetch.
subscriptions: { transport: "webtransport" | "websocket" | "sse" | "cbor-seq" } pins one binding; "cbor-seq" (since 0.20.3) is never chosen by "auto". A WebTransport attempt that is not ready within 3 s is remembered for 10 minutes, so a UDP-blocked network pays that wait once. Breaking out of the loop, or aborting signal, cancels the subscription. Each hook layer wraps any subscription:
--swr:useSubscription(key, (signal) => client.notes.subscribe({}, { signal })), overswr/subscription.--tanstack:useSubscriptionQuery(key, open, { onItem }). The query'sdatais the latest item, and the subscription ends when the query's last observer unmounts. To keep a list fresh, invalidate its key inonItem.
Dart: a Stream, over SSE through the same CratestackHttpTransport every call uses:
client.notes.subscribe(onReady: () => setState(() => live = true)).listen(render);With --preset riverpod (or fespalier), each op also gets a stream provider: ref.watch(noteEventsProvider(input: ...)) for a model feed, and ref.watch(linesProvider(args)) for a subscription procedure. Watching an equal input reuses the same subscription.
The Dart client also speaks a WebSocket, on native and web, and WebTransport, on Flutter web only. Pass CratestackSubscriptionOptions to the client as subscriptions:. In the riverpod preset, override <prefix>SubscriptionOptionsProvider instead.
final client = MyCratestackClient(
adapter,
subscriptions: CratestackSubscriptionOptions(
credentials: () => {'authorization': 'Bearer $token'},
webTransportUrl: Uri.parse('https://api.example.com:4433/rpc/wt'), // web only
),
);auto tries WebTransport, then the WebSocket, then SSE, and never CratestackSubscriptionTransport.cborSeq(since 0.20.3), which you pin with transport:. A socket does not go through your HTTP transport, so it cannot carry the token a Dio interceptor adds. credentials supplies the headers the socket sends instead. Until you set it, auto stays on SSE.
examples/realtime-chat in the framework repository puts all of this together. It has a model feed, a topic behind a subscription procedure, and all three bindings. Its test proves in Chromium that "auto" uses WebTransport with UDP open and falls back to the WebSocket with UDP blocked.
Bounding one SSE event
(since 0.20.2, cratestack#1379)
An SSE reader buffers bytes until it sees the blank line that ends an event. A server (or an intermediary) that never sends it would grow the client's memory until the process dies, so every client caps one event at 1 MiB. Rust counts the raw bytes received, line endings and the blank line included; TypeScript and Dart count UTF-8 bytes after \r\n is normalized to \n, so they may accept up to one more byte per line (the bound is still linear in the cap). A longer event ends the subscription with a typed error, and the connection is dropped. Nothing after it is delivered. The cap counts the partial data: lines and the unfinished line too, so one endless line with no newline is refused, not only many lines.
| Client | Set it | The error |
|---|---|---|
| Rust | ClientConfig::new(base).with_max_sse_event_bytes(n) | ClientError::EventTooLarge { limit } |
| TypeScript | subscriptions: { maxEventBytes: n } | CratestackEventTooLargeError, code event_too_large, .limit |
| Dart | CratestackSubscriptionOptions(maxEventBytes: n) | CratestackEventTooLargeException, code event_too_large, .limit |
Raise the cap only if one frame can legitimately be larger than 1 MiB. The WebSocket and WebTransport bindings are not governed by this setting. The application/cbor-seq binding is: see Subscribing over application/cbor-seq. A refused event is not retried by the client, and Auto does not fall back to another binding on it. A ready event over the cap refuses the open with the same typed error. On the Rust RPC client it is RpcClientError::EventTooLarge { limit } (not InvalidResponse). In the Dart --preset riverpod stream providers, Riverpod 3 retries a failed provider (up to 10 times, with backoff) unless the error is an Error or ProviderException; the generated providers pass retry: cratestackSubscriptionRetry, which defers to Riverpod's ProviderContainer.defaultRetry and opts CratestackEventTooLargeException out of that retry (it reaches the provider as an AsyncError at once; ref.invalidate retries by hand) and keeps the default for every other error.
Subscribing over application/cbor-seq
(since 0.20.3, cratestack#1001)
The SSE routes also answer Accept: application/cbor-seq. The body is a CBOR sequence of the frames SSE carries, CBOR-encoded, so items arrive in their CBOR shapes, as on a unary CBOR call: a Uuid is a byte string. Use it when the client speaks only CBOR, or sits behind a proxy that mangles text/event-stream.
The server picks the binding from Accept. application/cbor-seq selects cbor-seq; text/event-stream and */* select SSE. Entries are matched literally and the first entry the server speaks wins: application/cbor-seq, text/event-stream is cbor-seq, text/event-stream, application/cbor-seq is SSE. A missing or unacceptable Accept is 406 not_acceptable before authentication. The message changed to subscription endpoint requires Accept: text/event-stream or application/cbor-seq, so match on the status or the code, not the text. A refusal before the stream (bad auth, policy, a bad body) is the same JSON error body as for SSE, with its own status. Every response the generated subscribe handler makes carries Vary: Accept, set once by the handler, so a cache keeps the two bindings of one URL apart. A compact answer (application/vnd.cratestack.compact+…) adds its own second Vary line naming Cratestack-Contract, which caches combine. That covers success on both bindings and every refusal the handler itself makes: the 406, auth refusals, the RPC POST body 400 and an unknown op. A refusal from a layer in front of the handler does not carry it: the 413 body limit, a 405, a path rejection, the rate-limit 429 or an envelope-layer error. Accept matching is literal: q-values are not parsed.
Framing. Each item is one CBOR ServerFrame:
| Item | Meaning |
|---|---|
{id: 1, ready: {}} | first; the subscription is live |
{id: n, next: <item>} | one per event; n counts up from 2, as on SSE. The ids count up per frame; WebTransport instead carries one subscription id on every frame |
{id, err} or {id, end: {}} | exactly one terminal frame. A model feed's overflow is err with unavailable. end is sent when the source simply ends (SSE sends nothing then) |
null (0xf6) | the keep-alive, every 15 s while nothing is due. Not a frame |
The response is Content-Type: application/cbor-seq (the existing cratestack::CBOR_SEQUENCE_CONTENT_TYPE, exported at the crate root on both the cratestack-pg and cratestack-api facades, not under cratestack::rpc; no new constant). The binding items are under cratestack::rpc: SubscribeBinding, SubscribeCodec, decode_subscribe_open_body and encode_subscription_cbor_seq_response.
Routes. All four generated subscribe routes get it: GET and POST /rpc/subscribe/<op>, GET /$procs/<name> and GET /<plural>/$subscribe. REST has no POST subscribe form, for SSE or for cbor-seq. POST /rpc/subscribe/<op> now reads its open body by Content-Type: application/cbor is CBOR, anything else (or none) is JSON. The bounds are SSE's: the credential-expiry cut-off and the open rate limit apply. The per-principal session cap (SessionRegistry::admit) is used only by the WebSocket and WebTransport bindings, so cbor-seq does not use it, as SSE does not.
Clients opt in; Auto never picks it. A body that ends inside a frame, or between frames without end or err, is an error in every client, never a quiet end, because the server always sends a terminal frame. One frame is capped by the same per-event cap as SSE (1 MiB by default).
| Client | Pin it | Cap | Needs |
|---|---|---|---|
| Rust | ClientConfig::new(base).with_subscription_transport(SubscriptionTransport::CborSeq) | with_max_subscription_frame_bytes(n) (the same setting as with_max_sse_event_bytes) | nothing extra |
| TypeScript | subscriptions: { transport: "cbor-seq" } | maxEventBytes | @cratestack/cbor, loaded on first use (a dependency of an RPC package, an optional peer of a REST one; without it on a REST package the subscription fails with CratestackSubscriptionError code codec_unavailable before any request is sent) |
| Dart | CratestackSubscriptionOptions(transport: CratestackSubscriptionTransport.cborSeq) | maxEventBytes | nothing extra (the generated cratestack_cbor codec) |
What a client refuses. Before the first frame a client checks the response Content-Type is application/cbor-seq (parameters ignored, case-insensitive), and that the stream opens with ready. If err comes first, that is the server's refusal and the error carries the server's code. If end or next comes first, or an item is not a map, the response is invalid. A stream that ends without end or err is an error. All of these are ClientError::InvalidResponse (Rust), a CratestackSubscriptionError with code invalid_response (TypeScript) or a CratestackSubscriptionException with code invalid_response (Dart).
Model event ids. A model event's event_id travels as a 16-byte CBOR byte string on cbor-seq. The TypeScript and Dart clients revive it to the canonical hyphenated UUID string (ModelEvent.event_id, CratestackModelEvent.eventId); in Rust ModelEvent.event_id is a Uuid.
Over the cap the error is ClientError::EventTooLarge, CratestackEventTooLargeError or CratestackEventTooLargeException, as for SSE. A truncated or unterminated stream is ClientError::InvalidResponse (Rust), a CratestackSubscriptionError with code invalid_response (TypeScript) or a CratestackSubscriptionException with code invalid_response (Dart).
Breaking for exhaustive matches
SubscriptionTransport (Rust) and CratestackSubscriptionTransport (Dart) each gained a variant. An exhaustive match or switch needs a new arm. A generated TypeScript package also emits src/cbor-item.ts and src/cbor-argument.ts when a REST schema has a subscription, as an RPC package already did.
Deploying WebTransport
WebTransport is HTTP/3, so it is UDP, normally on the same port number as HTTPS, in the same process as your axum server. Your load balancer must forward UDP (L4) to it. To keep sessions across a client's network change, it must route by QUIC connection ID. Keep the WebSocket or SSE fallback reachable for networks that block UDP. The full checklist is §6a.6 of the design.
Read next
- RPC transport: the op ids and the
/rpc/subscribeendpoint in context. - AuthProvider: what authenticates a subscription, on every binding.
- TypeScript client generation and Dart client generation.