Push to clients
The push module sends small messages to browsers, apps and field devices listening over server-sent events. The normative text is the push specification; for the idea see push, and for the client side see the push guides.
A push is written in the same transaction as the change it announces, so it is sent only if that transaction
commits. One relay at a time moves committed pushes, in order, into a log that every instance follows. Each instance’s
hub fans them out to its streams, replays what a reconnecting client missed, and sends a reset to one that was away
too long. Say what changed, not the state: the client reads the state through the API, with its normal access checks.
flowchart LR UC[Use case transaction<br/>change + push row] --> OB[(push outbox)] OB --> R[Relay<br/>one at a time, locked] R --> L[(Log<br/>Postgres or Redis)] L --> H1[Hub, instance 1] L --> H2[Hub, instance 2] H1 --> S1[streams] H2 --> S2[streams]
The Java module is framework-push (with framework-push-redis for the Redis driver) and the Go package is push.
A Java host and a Go host on one database share the tables, the notification channels and the relay lock. Conformance
vectors under conformance/push/ pass in both.
Log drivers
Section titled “Log drivers”push.driver |
Where the log lives | Notes |
|---|---|---|
postgres (default) |
Tables fw_push_outbox and fw_push_log in the default database; ids max(id)+1, pg_notify('fw_push_log') |
Both languages |
redis |
A Redis stream <prefix>fw:push and channel <prefix>fw:push:end; the database still holds the outbox and the relay lock |
Both languages. Redis 6.2 or Valkey, one standalone server |
platform |
The platform’s push gateway holds the log and serves the routes | Go only. See the platform gateway driver |
Setting up
Section titled “Setting up”List the module after the database, locks, use case, HTTP and (for the auth authenticator) auth modules. It declares
the settings push.* (specification section 10), a claim on the push component, and the migration set push
(applied to the default database instance). The relay needs a lock instance for svc:push-relay.
PushModule.Builder builder = PushModule.builder().application(new ApplicationCode("test")).authenticate(lookup -> HEADER_AUTH);b.topic("test:order:{id}", "test:order:view");b.topic("test:user:{principal}");b.topic("test:client:{client}:news", "test:news:view");b.publicTopic("test:public");With the auth module:
b.authenticate(PushAuth.authModule());b.topic("test:field-worker:{principal}:jobs");basePath("/api") serves /api/push/subscriptions.
pd := Declare(app)pd.Topic("test:order:{id}", Requires("test:order:view"))pd.Topic("test:field-worker:{principal}:jobs")p, err := pd.Build(ctx, b, db, lk, Authenticate(AuthModule(am)))if err != nil { return nil, err}srv, err = httpfw.NewServer(b, web, []*httpfw.Routes{am.Routes(), p.Routes()}, httpfw.WithResolver(am.Resolver()))Options: Authenticate (without it every subscribe needs tickets), Application(code) (default: the application’s name;
the first segment of every topic and the issuer of its tickets), BasePath("/api"), and, for the Redis driver,
RedisClients(clients, prefix) or RedisLog(...) for a driver of your own.
push.stream.secret (at least 32 characters, the same on every instance) and push.ticket.key are required
secrets. push.ticket.key is <kid>:<base64url of a 32-byte Ed25519 seed>, comma separated, with the signing key
first and the previous key second during a rotation. Every range of the specification is checked when the module is
built and reported together as a start-up failure, as is a rule with neither {principal} nor a required permission,
a topic outside the application’s code, and a bad base path.
The module registers:
- the loops
push-relay(gated) andpush-retention(every minute: deletes log rows older thanpush.retention, never the newest); - the informational health check
push:log(Java alsobackground:push-relay); - the hub, which starts with the application once it follows the log and stops at shutdown;
- the three routes (below).
The hub holds one pooled connection for as long as it runs (it listens for new log rows) and the relay one more while it
holds the lock: keep pool.max of the default database comfortably above that.
The relay’s lock has the lease push.relay.lease (default 5 s, 1 s to 60 s), refreshed every third of it. A relay that
stops cleanly releases the lock, so another instance takes over at once (a rolling deploy). After a crash, the pushes
committed meanwhile wait for the lease, then arrive. A relay run, or a log read by the hub, that is under way when the
application stops is let finish (bounded by 10 s), not interrupted. Before the server starts, the hub reads the newest
push.recent pushes of the log into memory in one read, so the clients of a just-restarted instance resume from
memory like those of one that stayed up.
Publishing
Section titled “Publishing”In a use case, adding a push to the plan writes it in the attempt’s transaction right after the steps added so far, for the context’s client (the platform client’s push is stored with a null client and goes to every stream on the topic). A push is not an event: it is not audited and is never the result.
Plan<Tick> plan = Plan.emit(new Tick(events.metadata(c, TICKED, new TickId(cmd.id()))));return plan.andPush(Push.of("test:order:" + cmd.id(), "order.updated", Map.of("orderId", cmd.id(), "version", cmd.version())));Push.of takes a map (keys sorted), a record or a Jackson tree and stores compact JSON. Push.ofJson takes JSON text,
kept as written apart from whitespace outside strings. An invalid topic, type or data throws InvalidPushException
(reason() is one of the codes of conformance/push/topics.json).
Outside a use case, write in a transaction you own, or in one of its own:
try (Connection tx = n.dataSource.getConnection()) { tx.setAutoCommit(false); n.pushes.publish(Tx.of(tx), Context.of(ACME), Push.of("test:order:1", "order.updated", Map.of("v", "rolled back"))); tx.rollback();}// Pushes.publishAlone(context, push) uses a transaction of its ownreturn usecase.NewPlan(e.created(cx, t1), usecase.Push("test:thing:thg_push", "thing.creating", map[string]any{"z": 1, "a": "x"}), usecase.Insert(usecase.NewFresh(cx, t1), thingRepo{}), usecase.Push("test:thing:thg_push", "thing.created", map[string]any{"id": t1.id})), nilPass pushes.RunnerOption() to usecase.NewRunner so the runner refuses data over push.max-data-bytes.
Outside a use case, push.New(topic, type, data) checks a push (the error is an *InvalidPushError with a reason code),
Publish writes it in a transaction the caller owns (a pgx.Tx), and PublishAlone in one of its own:
p, _ := New("test:order:1", "order.updated", map[string]any{"v": "rolled back"})err := pgx.BeginTxFunc(ctx, n.db.Pool(), pgx.TxOptions{}, func(tx pgx.Tx) error { if err := n.p.Publish(ctx, tx, fw.ContextFor(acme), p); err != nil { return err } return errors.New("roll back")})PublishBatch(ctx, tx, items...) and PublishBatchAlone(ctx, items...) write pushes, each with its own client, in one
statement: all or none, every item checked first.
Data is a JSON object: a map or struct (marshalled, map keys sorted) or JSON text as jsontext.Value or []byte; it is
stored compact.
An invalid push thrown while a use case is decided, or data over push.max-data-bytes, fails the run as INTERNAL /
INVALID_PUSH (logged as a bug) before anything is written. A failure writing the row is INTERNAL / PUSH.
Subscribing and listening
Section titled “Subscribing and listening”Three routes, under the base path:
| Route | What |
|---|---|
POST {base}/push/subscriptions |
Takes {"topics": [...], "tickets": [...]} and answers the stream token, its expiry and the granted and denied topics. A topic is granted by a rule for the request’s context or by a ticket |
GET {base}/push/stream?st=<token> |
The stream: the retry field, a subscribed event, then the pushes missed since Last-Event-ID (the header or lastEventId) or a reset, then live pushes |
GET {base}/push/keys |
The ticket keys’ JWKS |
A Last-Event-ID that is present but not a non-negative integer gets a reset with the reason unknown-id, never a
silent live start; an empty one is no cursor. The access log never records the query string, so the stream token is not
logged.
The auth authenticator (PushAuth.authModule() / AuthModule(m)) authenticates a subscribe with the auth module: a
bearer token, a field token with its DPoP proof, or the session cookie with its CSRF rule. A request with none of them is
not refused; it needs a valid ticket, which then names the stream’s client. Bad credentials are 401 even with good
tickets. Any other scheme implements the authenticator interface (a Credentials value: the context, the credential’s
expiry, and for a field worker the DPoP key thumbprint, device and login family). See sessions and
login and field workers.
Snapshot with a cursor
Section titled “Snapshot with a cursor”A client that loads its state from a read endpoint and then listens can miss a change committed between the two. Return
the push cursor with the state, and have the client open its first listen with it as Last-Event-ID (the field
client libraries’ lastEventId option of PushStream). Take the cursor before reading the state. Every push at or
below it was logged before, so its change is in a read that starts after; any change the read lacks has a push above the
cursor. The cursor is the hub’s in-memory last id as a decimal string ("0" for an empty log) and costs no I/O. One that
lags the log only replays more pushes. After a reset, the client reloads its state and takes a new cursor.
String cursor = n.pushes.cursor(); // before the state readfunc (a *API) getOrder(ctx context.Context, id string) (OrderView, error) { cursor := a.pushes.Cursor() // before the state order, err := a.orders.Find(ctx, id) if err != nil { return OrderView{}, err } return OrderView{Order: order, PushCursor: cursor}, nil // PushCursor `json:"pushCursor"`}Rules and tickets
Section titled “Rules and tickets”A rule lets a context subscribe without a ticket. {principal} must be the context’s principal, {client} its
client, any other {name} matches one segment, and every required permission must be held. A rule with neither
{principal} nor a permission is refused at start-up; a deliberately open one is declared with publicTopic. Rules are
data, so a gateway can apply them.
Anything a rule cannot express is a ticket, minted by the application’s own endpoint after its own access check.
String ticket = n.pushes.ticket(Context.of(ACME).withPrincipal(new PrincipalId("prn_9")), "test:order:{id}", "test:public");String bound = n.pushes.ticketWith(Context.of(ACME), new Pushes.TicketOptions("jkt-1", null), "test:order:{id}");ticket, err := n.p.Ticket(fw.ContextFor(acme).WithPrincipal(fw.MustPrincipalID("prn_9")), "test:order:{id}", "test:public")bound, _ := n.p.TicketWith(fw.ContextFor(acme), TicketOptions{ProofKey: "jkt-1"}, "test:order:{id}")A ticket is an EdDSA JWS, valid for two minutes, for the context’s client. The proof-key option binds it to a device key:
the subscribe must then be authenticated with a field token bound to that key (the token’s cnf.jkt). A stream-expiry
option caps the stream’s life.
Tickets and stream tokens are verified only in the spelling they were issued in: every part must be canonical
base64url (no = padding, no + or /, no whitespace, no spare bits set). A ticket that is not is malformed
(400 VALIDATION), and a stream token that is not is 401 STREAM_TOKEN_INVALID. Tickets from the framework’s own
minters, and stream tokens it issued, are unaffected; a ticket minter written by hand, for an SDK of your own, must use a
standard unpadded base64url encoder. See the token spelling contract.
Streams, backpressure and ends
Section titled “Streams, backpressure and ends”- Each stream has a queue of
push.stream.bufferpushes. A stream that falls further behind is ended without an event and resumes from itsLast-Event-ID. A push is encoded once as its SSE event and the same bytes go to every stream; a queue exists only while its stream is behind. - Each instance keeps
push.recentpushes in memory and replays from there when it holds everything after the client’s id, from the log otherwise, one page of 1000 entries at a time. Streams resuming from the same id share each page read. - Over
push.max-streamsorpush.max-streams-per-principal, a subscribe, or a stream opened with a token, is429 PUSH_LIMIT. - At the token’s expiry the stream sends
auth-expiredand ends. - When the server’s drain begins, the hub ends every open stream at once (reason
drain), opens no more (503) and stops reading the log. Clients reconnect to another instance after theretry, with jitter. - A client that goes away is noticed at once in Go and at the next write (at the latest at the heartbeat,
http.sse.heartbeat) in Java, and only then does its slot under the limits come free.
endStreams(holder) ends the matching streams on every instance with auth-expired. For field revocations, the
FlowCatalyst module maps each event to a holder, so a revoked worker’s streams end from the same handler:
receivers.onFieldRevocation((ctx, event) -> pushes.endStreams(PushHolders.of(event)));flowcatalyst.OnFieldRevocation(receivers, func(ctx context.Context, cx fw.Context, ev flowcatalyst.FieldRevocation) error { return pushes.EndStreams(ctx, flowcatalyst.PushHolder(ev))})Ending streams when a session signs out is not built yet.
The log driver interface
Section titled “The log driver interface”The relay, the hub and the HTTP layer use one interface, so another driver plugs in without them changing: append,
readAfter, newest (the hub’s memory at start), latest, trimmed (the highest id deleted: a Last-Event-ID below
it gets a reset), prune, follow (wake-ups and the ends of streams), end and ping. A driver outside the database
appends at once and keeps each entry’s outbox id, and the hub drops an outbox id it has already seen. Java’s builder takes
redis(provider) or log(provider) (a driver of your own, used whatever push.driver says); Go’s takes RedisClients
or RedisLog.
The Redis driver
Section titled “The Redis driver”Set push.driver=redis and give the builder the Redis instances; push.redis-instance names one (the default instance
otherwise). In Java add framework-push-redis and list RedisModule.
- Keys. The stream
<prefix>fw:push(one entry per push with the fieldstopic,type,client,data,outbox,logged_atin that order) and the pub/sub channel<prefix>fw:push:end. The Java and Go drivers write the same layout, so one stream can be shared. - Ids. The entry id
ms-seqis sent asms * 2^20 + seq, so ids increase but are not contiguous and are far above the 1, 2, 3 of the Postgres driver. A sequence of 2^20 or more is an error, not a wrong id. Clients treat ids as opaque. - Append is one
MULTI/EXECofXADDin the relay’s order, before the relay deletes the outbox rows. A crash between the two adds the rows again; the hub drops an outbox id it has seen, live and in a replay. - Follow blocks in
XREAD BLOCK(one second at a time) and subscribes to the end channel. When the connection fails, the hub calls it again after a pause (one second, doubling to thirty) and polls everypush.relay.intervalmeanwhile, so the application stays ready and pushes are late by at most the interval. An end published while the subscription is down is lost. The follower holds two pooled connections. - Retention.
prunedeletes (XDEL, in batches of 1000) the entries whose id is below the Redis server’s millisecond at the retention edge, never the newest. It does not useXTRIM, because onlyXDELmovesmax-deleted-entry-id, which is whattrimmedreports. The ids are the server’s clock, so keep it within seconds of the application’s.
The platform gateway driver (Go)
Section titled “The platform gateway driver (Go)”With push.driver=platform, the application does not host push: its pushes go to the platform’s push gateway, which
holds the log and serves the routes. The gateway is a separate, opt-in platform service (FC_PUSH_ENABLED). Nothing
changes in the code that publishes (usecase.Push, Publish, PublishAlone, PublishBatch). The module then keeps no
log, hub, relay or retention loop, serves no routes, needs no push.stream.secret, and requires push.ticket.key:
tickets are minted here and the gateway verifies them.
A push becomes a PUSH row of the application’s outbox_messages, written in the use case’s transaction together with a
pg_notify('fc_outbox_push'), so the platform’s outbox processor delivers it as soon as the transaction commits. The
message group is the topic by default, so the pushes of one topic reach the gateway in order. The
FlowCatalyst module sends the gateway the topic rules and the public ticket keys as the category PUSH of sync:
p, err := pd.Build(ctx, b, db, lk)fc, err := flowcatalyst.Build(ctx, b, fcd, flowcatalyst.WithPushes(p))No cursor. The gateway owns the log, so Cursor() returns "" and HasCursor() is false. A snapshot endpoint has
nothing to hand the client; the client’s first listen is live, and it reads its state once more when the stream reports
subscribed to close the gap. EndStreams and EndPrincipal return ErrPlatformDriver: the gateway ends the streams of
a platform sign-out and of a revoked field login. The Java framework does not have this driver yet.
Multi-application hosts (Go)
Section titled “Multi-application hosts (Go)”A host that serves the topics of many applications, such as the platform’s push gateway, builds the module with
MultiApplication. The rules, the ticket keys and the limits of each application come from providers that the host may
change while it runs; the module reads them for every subscribe and listen and keeps nothing.
- Rules. A topic is granted only by the rules of its own application (its first segment). An application the provider
knows nothing of has its topics denied (
TOPIC_FORBIDDEN), never an error for the whole subscribe. - Tickets. A ticket is checked with the key the resolver gives for its
issandkid, and may grant topics of its issuer’s application only. Tickets of several issuers compose in one subscribe. - Limits. Per application:
MaxStreamsandMaxDataBytes. A stream counts against every application of its granted topics. Over the limit is429 PUSH_LIMITwith"details":{"scope":"application","application":"beta"}. - The client member. A subscribe body may name the client it wants (
"client": "globex"). A host whose credentials can act for several clients givesAuthenticatean authenticator that also implementsClientAuthenticator. For any authenticator the module requires a named client to equal the context’s client (403 CLIENT_FORBIDDEN). - Without the framework HTTP server.
Pushes.Handler()serves the three routes as anhttp.Handler; callPushes.Drain()at shutdown. A host that owns the tables declares the module withExternalMigrations().
Reading pushes in a Vue app
Section titled “Reading pushes in a Vue app”The shared UI has a reader for a Vue application, in two parts. @flowcatalyst/push (ui/packages/push) is the
reader itself: PushCore follows the contract’s sections on subscribing and listening (subscribe, listen with fetch
or EventSource, keep the last id, reconnect with jitter, subscribe again on auth-expired, report reset, denied
and errors) and has no DOM; PushStream is its EventTarget face. Its src/core.ts is the one source of the core:
the platform’s field-js and field-react-native carry synced copies. @flowcatalyst/ui/push (also exported from
@flowcatalyst/ui, and importing no Nuxt UI) adds the Vue layer: one stream per page, and two composables. Like the
other UI packages, both are linked by path, not installed from a registry (see
the UI package). The reader passes the push conformance vectors; verifying tickets is the
server’s half.
One stream per page. The application provides a hub once, and components declare topics:
// app setupprovidePushHub({ baseUrl: "/api", getTickets });// in a componentusePushTopics(() => ["orders:order:" + props.orderId]);providePushHub(options) creates one stream (createPushHub is the same without provide, for tests). The subscribe
goes through the application’s own HTTP: by default fetch with credentials: "same-origin", so the session cookie
goes with it and no CSRF header is needed; pass fetch for anything else. The stream request uses streamFetch
(default globalThis.fetch), because the stream token is the capability. usePushTopics holds its topics from mount to
unmount (a ref or getter is watched). Topics are reference-counted: two components asking for the same topic make one
entry, which goes when the last drops. Changes in one tick are batched into one subscription change; the core keeps its
last id, and the host replays every push after it on the new topic set, so nothing is lost. The stream starts with the
first topic and stops with the last. More than 100 topics are not truncated: the hub keeps the previous subscription and
reports a PUSH_LIMIT error in hub.error, and the server’s own limit (20 streams per principal) is reported the same
way. The hub also exposes state, lastPushAt, denied (the topics the server refused), on(pattern, fn) and
onReset(fn).
A list that stays current: useLiveList.
const { rows, status, lastAppliedAt, apply, reload } = useLiveList({ topics: ["orders:order:board"], load: async (signal) => { /* GET the rows and the push cursor */ return { rows, pushCursor }; }, id: (row) => row.id, version: (row) => row.version, toChange: rowChange,});toChange(push) returns { kind: "put", row }, { kind: "remove", id, version } or null; rowChange handles pushes of
type row.upserted ({id, version, row}) and row.removed ({id, version}). rows is a read-only array in load order,
with rows first seen by a push appended. status is loading, live, reconnecting or stopped.
- The version rule. A push replaces the held row only when its version is higher; a repeat changes nothing; an
unknown id is added. Versions are numbers or strings, compared numerically when both parse as numbers, otherwise as
strings. A removal drops the row and remembers the id with its version, so a later put that is not newer is ignored.
apply(change)follows the same rule, so a screen can apply the answer to its own command at once and an older push still on the stream cannot bring the row back. The removed-id memory holds at most 10,000 ids; aresetor a change of topics clears it. - No gap between the snapshot and the stream. If the hub is not streaming, the list loads first and the stream opens
with the load’s
pushCursorasLast-Event-ID, so the endpoint must read the cursor before its rows. If the hub is already streaming, the list adds its topics first, waits until the stream confirms them (at most 10 seconds, then it loads anyway), then loads, and applies the pushes that arrived meanwhile by the version rule. A load without apushCursorcannot be followed gap-free. resetloads again from scratch, as doesreload(). A failed load keeps the rows and setserror.
A record: useLiveRecord. For a detail page, it takes topics, load(signal), version(record) and signal(push),
which returns the version a push signals or null when the push is not about the record. The record is read again when a
signal’s version is higher than the held one (at most one read in flight and one queued for a burst), and again on
reset. It returns { record, status, lastAppliedAt, error, reload }. Its load returns no cursor, so the stream is
opened and confirmed first.
Metrics
Section titled “Metrics”fw_push_published_total, fw_push_relay_lag_seconds (a timer), fw_push_log_id, fw_push_streams_open,
fw_push_delivered_total, fw_push_streams_ended_total{reason} (client, slow, expired, revoked, drain),
fw_push_resets_total{reason} and fw_push_replay_source_total{source} (memory, log). See background work and
metrics.
What is not built
Section titled “What is not built”A reader for client platforms other than the browser, the field libraries and the shared Vue UI, a sign-out hook that ends a user’s streams, and the full load test of the specification’s section 11 on the target environment. A local Go run exists; Java has not been measured the same way.