Skip to content

Push from a use case and listen in the browser

This guide takes one push from the line of code that writes it to the browser handler that receives it. For what a push is and why it is a signal rather than state, read Push to clients first. For topic syntax, rules and tickets in detail, see Topics, rules and tickets.

There are two hosts for the stream. The wire is the same, so the browser code below does not change between them, only its base URL.

App-hosted Platform gateway
Stream served by your application, using the framework push module (Java or Go) fc-server with FC_PUSH_ENABLED=true (fcdev turns it on by default)
Your code writes a push in the use case plan (andPush / usecase.Push) a PUSH row in your outbox, via the SDK, or the framework with push.driver=platform
Base URL for clients your application, for example https://app.example.com/api the platform, https://<platform>/api
Rules and ticket keys declared on your push module synced to the platform from your code
Push cursor (snapshot) yes no (see section 5)
Suits a framework service with its own long-running server PHP-FPM, serverless, scripts, any SDK, devices listening to several applications

If you are not on a framework service, use the gateway. It is the only option for the TypeScript, PHP and Rust SDKs, and for the Go and Java SDKs outside the framework. The Python SDK does not write pushes.

Every push is written in a transaction, so it exists only if the change it announces commits. A push is a topic ({application}:{segment}…), a type (order.updated) and a small JSON object that says what changed.

In a framework use case, add a push to the plan. It is written in the attempt’s transaction, in plan order:

return usecase.NewPlan(e.created(cx, t1),
usecase.Push("shop:order:"+t1.id, "order.created", map[string]any{"id": t1.id}),
usecase.Insert(usecase.NewFresh(cx, t1), thingRepo{}),
), nil

Pass pushes.RunnerOption() to usecase.NewRunner so the runner enforces push.max-data-bytes. Outside a use case, build the push and publish it in a transaction you own:

p, err := push.New("shop:order:ord_1", "order.updated", map[string]any{"version": 7})
if err != nil {
return err // *push.InvalidPushError, with a reason code
}
err = pgx.BeginTxFunc(ctx, pool, pgx.TxOptions{}, func(tx pgx.Tx) error {
// ... the change ...
return pushes.Publish(ctx, tx, fw.ContextFor(clientID), p)
})

With the plain Go SDK (no framework), write the PUSH outbox row with the pgx sink. This is the gateway path:

sink := outboxpgx.NewSink(outboxpgx.Config{ClientID: clientID, ClientCode: "acme"})
err := sink.WritePush(ctx, tx, outbox.NewPush("shop:order:ord_2", "order.updated",
map[string]any{"status": "shipped"}))

A push the platform would refuse is refused when it is built, and nothing is written. The SDKs report the refusal with a code: TOPIC_INVALID, TYPE_INVALID, TYPE_RESERVED (reset, auth-expired, subscribed, anything starting fw.), DATA_INVALID, DATA_NOT_OBJECT, DATA_TOO_LARGE, and, for gateway rows, PUSH_ID_INVALID and CLIENT_INVALID. The data limit is 16 KiB by default and at most 64 KiB.

Gateway rows: ordering, client and wake-up

Section titled “Gateway rows: ordering, client and wake-up”

A gateway push is a PUSH row in your outbox_messages, relayed like an event (see the outbox).

  • Ordering. The row’s message group is the topic, so one topic’s pushes reach the gateway in order. For a signal-only topic that does not need order, write the row ungrouped (WithUngrouped, withUngrouped, .ungrouped()): it is batched and concurrent.
  • Client. A push belongs to a client. The SDK’s configured client code is the default; override it per push. _platform leaves it out, which makes the push platform-wide (every stream on the topic hears it).
  • Push id. The row id is the push id (a TSID unless you set one, at most 26 characters). The gateway writes a push id once, so a retried row is not delivered twice.
  • Wake-up. On PostgreSQL the insert also notifies the platform’s outbox processor, so the push leaves when your transaction commits instead of waiting for the next poll. MySQL and MongoDB cannot notify; the processor’s poll (1 s by default) delivers.
  • Prerequisite. The platform’s outbox processor must know the PUSH type. fcdev and the current images do; an older processor fails the row.
  • Permission. The credential that drains the outbox needs platform:messaging:batch:push-write. The built-in platform:application-service role carries it. An application-scoped credential can push only for topics that begin with its own application code.

If the application is paused, or over its publish rate, the gateway answers the whole batch 429 with Retry-After. The rows wait in your outbox, in order, and no retry attempts are spent.

A client may listen to a topic if a rule allows it or it holds a ticket. Declare rules for the common cases:

Rule Meaning
shop:orders:{id} requires shop:orders:order:view anyone with the permission, on any order of their own client
shop:user:{principal} only the caller’s own topic
shop:announcements, public open to everyone, on purpose

A rule with neither {principal} nor a required permission is refused when it is declared, so no topic is open by accident.

App-hosted, on the push module:

pd := push.Declare(app)
pd.Topic("shop:order:{id}", push.Requires("shop:order:view"))
pd.Topic("shop:user:{principal}")
pd.PublicTopic("shop:announcements")

With push.driver=platform, the flowcatalyst module sends the rules and the public ticket keys to the gateway, as the PUSH category of sync: flowcatalyst.Build(ctx, b, fcd, flowcatalyst.WithPushes(p)). The plain Go SDK does not sync rules or mint tickets; use the framework module for that.

Rules and keys are a full replace at the gateway: send both every time. The gateway refuses (400, with a code) rules for another application’s topics, open rules that are not marked public, duplicate patterns, more than 200 rules, more than 4 keys, and keys that are not public Ed25519 JWKs. Calling the sync needs platform:application-service:push:sync and access to the application. Every gateway task reloads within about a second.

3. Mint a ticket (when a rule cannot say it)

Section titled “3. Mint a ticket (when a rule cannot say it)”

“This user may see order 7 but not order 8” is not a rule. Your own endpoint checks access and mints a short-lived ticket; the browser then presents it when it subscribes.

ticket, err := pushes.Ticket(fw.ContextFor(clientID).WithPrincipal(principalID), "shop:order:{id}")

A ticket is an EdDSA-signed JWS. Its exp is at most five minutes after iat: that is only the time to subscribe with it, not the life of the stream. The minters refuse a topic outside your application and more than 100 topics. Tickets are signed with your private key; the host verifies with the public key, which is why the gateway never holds your secret.

A Vue application built on the shared UI package does not need to drive the stream itself: providePushHub, usePushTopics, useLiveList and useLiveRecord from @flowcatalyst/ui/push wrap the same reader (see Reading pushes in a Vue app). Anywhere else:

PushStream from @flowcatalyst/field-js (and its React Native copy in @flowcatalyst/field-react-native) does both steps for you: it subscribes, reads the stream, keeps the last id, and reconnects and resumes. It works on a plain web page as well as on a field device. It is installed from its git tag; see Choosing a field library.

import { PushStream } from "@flowcatalyst/field-js";
const stream = new PushStream({
baseUrl: "https://<platform>/api", // or your application's /api when app-hosted
topics: ["shop:user:prn_0ABC", "shop:orders:ord_7"],
fetch: globalThis.fetch.bind(globalThis), // cookie session; a field device passes auth.fetch
getTickets: (topics) => fetchTicketsFromMyEndpoint(topics), // only for topics that need one
});
stream.on("shop:orders:*", (push) => {
// push = { id, topic, type, data }
refreshOrder(push.data.orderId);
});
stream.addEventListener("reset", () => reloadEverything()); // away too long: reload state
stream.addEventListener("denied", (e) => console.warn((e as CustomEvent).detail));
stream.start();
  • on(pattern, handler) takes a topic, or a pattern where * is one segment and a final ** is the rest. onAny(handler) takes every push.
  • Pushes arrive once, in order. Ids are 64-bit, so they are strings.
  • On auth-expired (the stream token reached its expiry) or a 401, the reader subscribes again and resumes from its last id, so nothing is lost.
  • 403 NO_TOPICS (nothing was granted) stops the stream and raises error.
  • Where fetch bodies are not streamable (React Native’s default), the reader falls back to EventSource; give it eventTypes (your push types) then, because EventSource only hears types it is told about.

Under the hood this is two requests: POST {base}/push/subscriptions with { "topics": [...], "tickets": [...] }, answered with a stream token and the granted and denied topics; then GET {base}/push/stream?st=<token>, which is the event stream. A denied topic is reported, not an error for the others. See the push wire format.

The gateway accepts a bearer access token, the platform session cookie (with the console’s CSRF rule), a field token with its DPoP proof, or a ticket alone. A browser on another origin needs that origin in the tenant’s allowed CORS origins. A field worker is confined to the application their token was issued for. A user who can act for several clients names one in the subscribe body ("client": "acme"). Listening to every client at once needs platform:push:stream:all-clients.

5. Do not miss the change between “load” and “listen”

Section titled “5. Do not miss the change between “load” and “listen””

A screen loads its state and then listens. A change committed in between would be lost. For an app-hosted stream, close the gap with a push cursor:

  1. In the endpoint that returns the state, read the cursor first, then read the state.
  2. Return the cursor with the state (pushCursor by convention).
  3. Open the first listen with lastEventId: cursor. After a reset, reload and take a new cursor.
cursor := a.pushes.Cursor() // before the state read
order, err := a.orders.Find(ctx, id)
return OrderView{Order: order, PushCursor: cursor}, err

Java has pushes.cursor(). A cursor that lags the log only replays a few extra signals, which is harmless.

The platform gateway owns the log, so an application that publishes through it has no cursor (Cursor() returns ""). Its client opens the first listen live and reads its state once more when the stream reports subscribed; that closes the same gap from the client side.

Setting Meaning
FC_PUSH_ENABLED=true run the gateway in fc-server; routes under /api/push/* and /health/push
FC_PUSH_STREAM_SECRET required, at least 32 characters, the same on every gateway task
FC_PUSH_DRIVER postgres (default) or redis (uses FC_REDIS_URL)
FC_PUSH_RETENTION how long the log keeps pushes for resuming clients, 10 minutes to 24 h

Under fcdev the gateway is on by default (--push) with a random stream secret per start. The other FC_PUSH_* limits are in the environment variable reference. The console has a Platform > Push group (applications, live streams, recent pushes, test send); viewing needs platform:admin:push:view, and changing limits or pausing needs platform:admin:push:manage. Both are anchor-only.

Symptom Likely cause
The row fails in the outbox the processor is older than the PUSH type; upgrade it
TOPIC_NOT_OWNED on ingest the topic’s first segment is not the credential’s application
Subscribe answers 403 NO_TOPICS no rule matched and no valid ticket; check the rule’s permission and the ticket’s iss, client and exp
A topic is denied with TOPIC_FORBIDDEN no rule for it on that host
A topic is denied with TICKET_INVALID wrong aud, kid or iss, expired, topic outside iss, other client, or cnf mismatch
429 PUSH_LIMIT stream limit per instance, per principal or per application
The client keeps getting reset it was away longer than the retention, or the log driver was switched