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.
Choose where the streams live
Section titled “Choose where the streams live”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.
1. Publish
Section titled “1. Publish”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{}),), nilPass 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"}))In a framework use case:
Plan<Tick> plan = Plan.emit(new Tick(events.metadata(c, TICKED, new TickId(cmd.id()))));return plan.andPush(Push.of("shop:order:" + cmd.id(), "order.updated", Map.of("orderId", cmd.id(), "version", cmd.version())));Outside a use case, Pushes.publish(tx, context, push) writes it in a transaction you own and
Pushes.publishAlone(context, push) in its own.
With the Java SDK, write the PUSH outbox row for the gateway:
driver.withTransaction(tx -> { // business writes ... outbox.createPush(CreatePushDto.create("shop:orders:ord_2", "order.updated", Map.of("status", "shipped")), tx); return null;});Through the gateway. Inside a use case plan:
import { usecase, CreatePushDto } from "@flowcatalyst/sdk";
return usecase.Plan.andPush( usecase.Plan.save(order, orderRepo, event), CreatePushDto.create(`shop:orders:${order.id}`, "order.updated", { status: "placed" }),);Or directly, in the transaction of the change:
import { OutboxManager, PgOutboxDriver, CreatePushDto } from "@flowcatalyst/sdk";
const outbox = new OutboxManager(new PgOutboxDriver(pool), "clt_0HZXEQ5Y8JY5Z", { clientCode: "acme", // the default client of a push; "_platform" leaves it out});
await outbox.createPush( CreatePushDto.create("shop:orders:ord_2", "order.updated", { status: "shipped" }), tx,);Through the gateway:
use FlowCatalyst\Facades\Outbox;use FlowCatalyst\Outbox\DTOs\CreatePushDto;
DB::transaction(function () use ($order) { $order->save();
Outbox::createPush( CreatePushDto::create("shop:orders:{$order->id}", 'order.updated', ['status' => 'shipped']), );});In a use case plan, Plan::save(...)->andPush(CreatePushDto::create(...)) writes the push after the
event, in the plan’s transaction.
Through the gateway:
use flowcatalyst_sdk::outbox::CreatePush;
let data = serde_json::json!({ "status": "shipped" });manager .create_push(&CreatePush::new("shop:orders:o1", "order.updated", &data)) .await?;CreatePush also has .client_code(..), .id(..), .message_group(..), .ungrouped() and
.max_data_bytes(..). The Rust SDK is not released yet.
What is checked when you publish
Section titled “What is checked when you publish”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.
_platformleaves 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
PUSHtype. 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-inplatform:application-servicerole 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.
2. Say who may listen
Section titled “2. Say who may listen”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.
App-hosted, on the module builder:
PushModule.Builder b = PushModule.builder().application(new ApplicationCode("shop")) .authenticate(PushAuth.authModule());b.topic("shop:order:{id}", "shop:order:view");b.topic("shop:user:{principal}");b.publicTopic("shop:announcements");With the Java SDK and the gateway, declare them with the other definitions:
var minter = TicketMinter.fromConfig("shop", System.getenv("PUSH_TICKET_KEY"), List.of()); // kid:base64url-seedvar set = DefinitionSet.define("shop").withPush(PushDefinition.of(List.of( PushRule.of("shop:orders:{principal}"), PushRule.of("shop:admin:{id}", "shop:admin:read"), PushRule.open("shop:board")), minter));client.definitions().sync(set); // POST /api/applications/shop/push/syncimport { sync, TicketMinter } from "@flowcatalyst/sdk";
const tickets = TicketMinter.fromConfig("shop", process.env.PUSH_TICKET_KEY!, []);
const definitions = sync .defineApplication("shop") .withPush({ rules: [ { pattern: "shop:orders:{id}", requires: ["shop:orders:order:view"] }, { pattern: "shop:user:{principal}" }, { pattern: "shop:announcements", public: true }, ], keys: tickets, // sends the public JWKS (up to 4 keys) }) .build();
await client.definitions().sync(definitions);In config/flowcatalyst.php, then php artisan flowcatalyst:sync (--push syncs only these):
'push' => [ 'rules' => [ ['pattern' => 'shop:orders:{id}', 'requires' => ['shop:orders:order:view']], ['pattern' => 'shop:user:{principal}'], ['pattern' => 'shop:announcements', 'public' => true], ], 'ticket_key' => env('FLOWCATALYST_PUSH_TICKET_KEY'), // "kid:base64url-seed", Ed25519 'previous_ticket_keys' => env('FLOWCATALYST_PUSH_PREVIOUS_TICKET_KEYS'),],use flowcatalyst_sdk::push::{PushDefinition, PushRule};
let rules = vec![ PushRule::new("shop:orders:{id}").requires(["shop:orders:order:view"]), PushRule::new("shop:user:{principal}"), PushRule::new("shop:announcements").public(),];let def = PushDefinition::new(rules, minter.jwks()?);// add it to a DefinitionSet with with_push(def), or call client.push().sync(..)Ticket minting needs the push-tickets feature.
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}")// app-hostedString ticket = pushes.ticket(Context.of(client).withPrincipal(new PrincipalId("prn_9")), "shop:order:{id}");// gateway, with the Java SDKString t = minter.mint(TicketMinter.Request.of("acme", List.of("shop:orders:{id}")).withSub("prn_1"));const ticket = tickets.mint({ client: "acme", // the stream's client ("_platform" for platform-wide) topics: ["shop:orders:ord_7"], sub: "prn_1", // optional // jkt: "<dpop key thumbprint>", // optional: bind to a device key // ttlSeconds: 60, // 1 to 300, default 60});$minter = TicketMinter::fromConfig(config('flowcatalyst.application_code'), config('flowcatalyst.push.ticket_key'));$ticket = $minter->mint(client: 'acme', topics: ['shop:orders:ord_7'], sub: 'prn_1');let minter = TicketMinter::from_config("shop", &std::env::var("PUSH_TICKET_KEY")?, &[])?;let ticket = minter.mint(&MintTicket::new("acme", ["shop:orders:ord_7"]).principal("prn_1"))?;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.
4. Listen in the browser or on a device
Section titled “4. Listen in the browser or on a device”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 statestream.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 a401, the reader subscribes again and resumes from its last id, so nothing is lost. 403 NO_TOPICS(nothing was granted) stops the stream and raiseserror.- Where
fetchbodies are not streamable (React Native’s default), the reader falls back toEventSource; give iteventTypes(your push types) then, becauseEventSourceonly 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.
Who can subscribe to the gateway
Section titled “Who can subscribe to the gateway”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:
- In the endpoint that returns the state, read the cursor first, then read the state.
- Return the cursor with the state (
pushCursorby convention). - Open the first listen with
lastEventId: cursor. After areset, reload and take a new cursor.
cursor := a.pushes.Cursor() // before the state readorder, err := a.orders.Find(ctx, id)return OrderView{Order: order, PushCursor: cursor}, errJava 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.
6. Turn the gateway on
Section titled “6. Turn the gateway on”| 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.
Troubleshooting
Section titled “Troubleshooting”| 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 |