Push to clients (server-sent events)
Status: accepted 2026-11-08 (ruling in section 16). P1a built in Go (2026-11-08): the core
module (go/push), the A1 postgres driver, usecase.Push, tickets, the HTTP routes, the
conformance vectors and the A1 contract tests; amendments from that build in section 17. A2
(redis) built in Go the same day (RedisStreamLog; the contract tests run on both drivers;
amendment 10 of section 17). First local load test the same day; its four findings fixed in Go
(amendment 11 of section 17, 2026-11-08). The snapshot cursor (9.1) and the reset for an invalid
Last-Event-ID (amendments 12 and 13 of section 17, 2026-11-09). P2a built in Java (2026-11-09):
module framework-push (the core, the A1 postgres driver, Plan.andPush, tickets, the routes,
the four conformance vector files, the contract test suite of section 14 on A1; amendment 14 of
section 17). The Java Redis driver (A2) built the same day: module framework-push-redis, the contract
tests of section 14 on both drivers (amendment 15 of section 17). The framework changes the A4 platform
push gateway needs, built in Go (2026-11-09, amendment 16 of section 17): many applications in one
host, per-application stream limits, the optional client member of the subscribe body, Handler,
Drain, ExternalMigrations, PublishBatch. Readers: PushStream in the platform’s field-js and field-react-native; not yet one in the shared UI
packages. Not yet: the load test on the target,
the Java side of amendment 16 and of push.driver=platform. push.driver=platform, the publish sink
for applications that use the gateway, is built in Go (2026-11-09, amendment 17 of section 17).
Drivers: postgres (A1) and
redis (A2), behind one contract. A platform push gateway (A4) is sketched in section 12 so that
nothing here rules it out.
An application pushes small messages to browsers, apps and field devices that are listening over
server-sent events. A push is not a domain event: it is whatever a screen needs to hear (“order 7
changed”, “a job was assigned to you”). The transport is the framework’s SSE stream (HTTP contract
section 13.5: Last-Event-ID, heartbeat, drain). This contract adds what a stream needs to be
robust with more than one instance: a push written in the same transaction as the change, one
ordered log every instance follows, replay after a reconnect, an answer for a client that was away
too long, topics with access rules, and backpressure.
The guarantee. A push is sent only if its transaction commits, and every committed push is
delivered to every stream subscribed to its topic, in log order, once, as long as the stream is
open or resumes within the retention window. A stream that resumes from further back gets a reset
event and reloads its state (section 7). The log is per host: ids from one host mean nothing to
another.
1. Topics and types
Section titled “1. Topics and types”- Topic:
{application}:{segment}(:{segment})*. The application segment is the application’s code ([a-z][a-z0-9-]*, as permission codes); each further segment is[0-9A-Za-z_.-]+. At most 255 characters, at least two segments. Examples:shop:order:ord_0ABCDEFGH01,shop:store:12:dock,shop:user:prn_0ABC. Every topic starts with its application’s code, so topics from different applications never collide on a shared host (section 12). - Type:
[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)*, at most 100 characters, for exampleorder.updated. The typesreset,auth-expired,subscribedand every type startingfw.are reserved (section 6). - Data: a JSON object, at most
push.max-data-bytes(default 16 KiB, at most 64 KiB) of UTF-8. - Signals, not state (default). A push should say what changed (
{"orderId": "...", "version": 7}); the client reads the state through the application’s API, which applies its normal access checks and never shows a stale copy. A push may carry state when the data is fine for everyone allowed on the topic and fits the limit; that is the application’s call, per topic.
Invalid topics, types or data are refused when the push is built (Java IllegalArgumentException;
Go the plan fails as INTERNAL / INVALID_PUSH, logged as a bug). The refusal codes (amended
2026-11-08, section 17): TOPIC_INVALID, TYPE_INVALID, TYPE_RESERVED, DATA_INVALID (not
JSON), DATA_NOT_OBJECT, DATA_TOO_LARGE. The data is stored as compact JSON (no whitespace), so
its data line on the wire is one line; the limit counts those bytes.
2. Publishing
Section titled “2. Publishing”A push is published in a transaction, always:
- In a use case (write-path contract section 3):
plan.andPush(Push.of(topic, type, data))(Gousecase.Push(topic, type, data)). The runner writes it in the attempt’s transaction, in plan order, at step 5 (step codePUSH). It is not an event: it is not audited, is never the use case’s result and does not count toward “every plan carries an event”. A failed attempt writes no push. - Outside a use case:
Pushes.publish(tx, context, push)(Gopushes.Publish(ctx, tx, cx, p), a method of the built module, which knowspush.max-data-bytesand the clock;txis apgx.Tx) inside a transaction the caller owns, orPushes.publish(context, push)(Gopushes.PublishAlone(ctx, cx, p)) in its own transaction.
Each push records the Context’s client (section 5): the client is part of the push.
Writing a push inserts one row into fw_push_outbox and issues pg_notify('fw_push_outbox', '').
Both are transactional: the row and the notification exist only if the transaction commits. The
outbox is always on the default database instance, whatever the driver.
-- module push, V0001__create_push_tables.sqlCREATE TABLE fw_push_outbox ( id BIGSERIAL PRIMARY KEY, topic VARCHAR(255) NOT NULL, type VARCHAR(100) NOT NULL, client VARCHAR(100), -- NULL: the platform client (section 5) data TEXT NOT NULL, -- the JSON object as written created_at TIMESTAMPTZ NOT NULL);3. The relay
Section titled “3. The relay”One instance at a time, the relay, moves pushes from the outbox into the log. It is a background
loop (background contract section 1) gated by the lock LockKey.service("push-relay"), so the
fencing token protects it (locks contract section 3).
One run: take up to push.relay.batch (default 500) outbox rows in id order, append them to the
log in that order, delete them, commit (A1: one transaction; A2: append, then delete, section 4).
The relay runs when fw_push_outbox is notified and at least every push.relay.interval (default
1 s) in case a notification was missed.
The lock’s lease is push.relay.lease (default 5 s), refreshed every third of it. A relay that
stops cleanly releases the lock, so another instance’s relay takes over at once (a rolling deploy).
After a crash the lock is free when the lease ends: pushes committed meanwhile wait in the outbox
for up to the lease, then arrive, none lost.
Why a relay. Log ids must follow commit order: a client that has seen id 41 must never later be owed an id 40. A sequence assigned when the row is inserted does not give that, because two transactions can commit in the other order. The relay assigns log ids only to rows that are already committed, one writer at a time, so the log has no gaps and never reorders. A row whose transaction commits after the relay’s read is simply picked up by a later run.
A push therefore reaches a stream about one relay run plus one hub wake-up after its commit (target p99 under 250 ms, section 11).
4. The log and the drivers
Section titled “4. The log and the drivers”The log holds, per push: the id (a positive increasing 64-bit integer, the SSE event id), the
topic, type, client, data, and the time it was logged. The driver decides where it lives
(push.driver):
A1 postgres (default) |
A2 redis |
|
|---|---|---|
| log | table fw_push_log (below) on the default instance |
the Redis stream fw:push on push.redis-instance |
| id | max(id) + 1, assigned by the relay inside its transaction; PRIMARY KEY (id) refuses a second relay |
the Redis entry id ms-seq, sent as ms * 2^20 + seq (seq below 2^20) |
| instances woken by | pg_notify('fw_push_log', <highest id>) in the relay’s transaction |
XREAD BLOCK on the stream |
| retention | rows older than push.retention deleted by a loop |
entries below the retention edge deleted by a loop with XDEL (not XTRIM: section 17.10) |
| relay step | insert into the log and delete from the outbox, one transaction | XADD each row, then delete the rows; a crash between the two can add a row twice, so each entry carries the outbox id and the hub drops an outbox id it has already seen |
CREATE TABLE fw_push_log ( id BIGINT PRIMARY KEY, topic VARCHAR(255) NOT NULL, type VARCHAR(100) NOT NULL, client VARCHAR(100), data TEXT NOT NULL, logged_at TIMESTAMPTZ NOT NULL);CREATE INDEX fw_push_log_logged_at ON fw_push_log (logged_at);push.retention defaults to 24 h and is configurable from 10 minutes up to 24 h, never more (decided 2026-11-08). Each driver passes the same contract tests and
conformance vectors (section 13); application code and clients cannot tell them apart.
5. Clients (tenants) and who receives what
Section titled “5. Clients (tenants) and who receives what”Every push has the client of the context that wrote it. A stream belongs to one client (section 6). A stream receives a push when the push’s topic is one it subscribed to and:
- the push’s client is the stream’s client, or
- the push’s client is the platform client (written as NULL): it goes to every stream subscribed to the topic, whatever the stream’s client.
A stream opened in the platform client’s context (an anchor tier user or a platform service) receives the topic’s pushes of every client. The client check is made for every push, on every stream, after the topic match. Even if two clients’ topics have the same name, one never hears the other.
6. Subscribing and the stream
Section titled “6. Subscribing and the stream”A client opens a stream in two steps. Both steps are the same on every host (A1, A2, A4).
6.1 Subscribe. POST {base}/push/subscriptions, JSON:
{ "topics": ["shop:order:ord_1", "shop:user:prn_0ABC"], "tickets": ["<ticket>", "..."] }The request is authenticated the application’s usual way (session cookie with its CSRF rule,
bearer token, or a field token with DPoP), or not at all when the tickets grant every topic. Each
topic is granted when a rule (6.3) allows it for the request’s Context, or a ticket (6.4)
grants it. The answer is 200:
{ "streamToken": "<opaque>", "expiresAt": "2026-11-08T13:00:00Z", "granted": ["shop:order:ord_1"], "denied": [{ "topic": "shop:user:prn_0ABC", "code": "TOPIC_FORBIDDEN" }]}Other answers:
400 VALIDATION: the body is malformed, a topic is invalid, there are more thanpush.max-topicstopics (default 100), or a ticket is malformed.401: authentication was given and failed.403 NO_TOPICS: nothing was granted.
A denied topic is reported, never an error for the others. The stream token names the granted
topics, the stream’s client, the principal (when there is one) and the expiry. The expiry is the
earliest of the credential’s expiry (session, access token), every ticket’s stream-exp, and
push.stream.max-lifetime (default 1 h). The token is signed by the host with push.stream.secret
(HMAC-SHA256), which every instance of the host shares. It is a capability to listen, nothing else.
Amended 2026-11-19 (token spelling): both parts of a stream token are canonical
base64url, else 401 STREAM_TOKEN_INVALID.
6.2 Listen. GET {base}/push/stream?st=<streamToken>, with Last-Event-ID (header, or
lastEventId in the query) when resuming. This works from a browser EventSource, which cannot set
headers. The query parameter st is redacted in access logs. Answers:
401 STREAM_TOKEN_INVALID/STREAM_TOKEN_EXPIRED: subscribe again.200 text/event-stream, with the SSE stream of HTTP contract section 13.5, as follows:- A
subscribedevent:{"granted": [...], "latest": <highest log id now>}, without an id. - If
Last-Event-IDis given and still inside retention, every push after it on the granted topics (subject to section 5), in id order. If it is older than the oldest id kept, aresetevent instead (section 7). WithoutLast-Event-ID, nothing from the past: the client loaded its state before subscribing. - The live pushes, each once, in id order.
- A
Each push is sent as:
id: 1042event: order.updateddata: {"topic":"shop:order:ord_1","data":{"orderId":"ord_1","version":7}}The data line is one JSON object: topic and data. The vectors (section 13) pin these bytes.
6.3 Rules (declared in code, kept as data). An application declares, per topic pattern, who may subscribe without a ticket:
push.topic("shop:order:{id}").requires("shop:order:view"); // any order of the stream's clientpush.topic("shop:user:{principal}"); // only your ownpush.topic("shop:store:{id}:dock").requires("shop:dock:view");push.topic("shop:announcements").requires("shop:app:use");- A pattern’s segments are literals or placeholders.
{principal}must equal the context’s principal id.{client}must equal the context’s client.- Any other
{name}matches one segment. requires(permission)needs the permission in the context, and may be given more than once (all needed).- A rule without a principal placeholder or
requiresis refused when declared, so no topic is open to anyone by accident;publicTopic(pattern)declares a deliberately open one. - Rules are data, not callbacks, so a gateway can apply them as well (section 12). Anything a rule cannot express (this user may see order 7 but not order 8) is a ticket.
6.4 Tickets. A ticket is minted by the application, in its own endpoint, after its own access
check. It grants topics to whoever holds it, so it is short-lived and only minted for an
authenticated caller. Format: JWS compact, alg EdDSA (Ed25519), header kid. Claims:
| claim | meaning |
|---|---|
iss |
the application code (the topics’ first segment must equal it) |
aud |
fw-push |
client |
the stream’s client (the platform client’s value for platform-wide) |
topics |
patterns as in 6.3, placeholders matching any one segment, at most 100 |
sub |
optional: the principal; recorded in the stream token, for logs |
cnf |
optional: {"jkt": "<thumbprint>"}, then the subscribe request must carry a DPoP proof with that key |
iat, exp |
exp at most 5 minutes after iat: the time to subscribe with it |
stream-exp |
optional: the latest the stream may live (default exp + push.stream.max-lifetime) |
Pushes.ticket(context, topics...) (Go push.Ticket(cx, topics...)) mints one with the key
push.ticket.key (secret). The host serves its public keys at GET {base}/push/keys (JWKS), the
current and the previous key during a rotation. A ticket from another application, with a bad
signature, an unknown kid, an expired exp or a topic outside iss grants nothing (the topic is
denied with TICKET_INVALID). Tickets from several applications in one request are each checked
against their own issuer’s keys; an application host knows only its own (section 12 for A4).
Amended 2026-11-19 (token spelling): the three parts of a ticket are canonical
base64url; a ticket that is not is malformed (400 VALIDATION, amendment 17.6). A ticket minter of
an SDK of one’s own must use a standard unpadded base64url encoder.
7. Reconnecting, resets and expiry
Section titled “7. Reconnecting, resets and expiry”- Resume: a stream that drops is reopened with the same stream token and
Last-Event-ID; the pushes in between are replayed (6.2 step 2). Clients reconnect after theretry(3 s) with jitter. - Reset: when
Last-Event-IDis older than the oldest id still kept, the host sendsevent: resetwithdata: {"reason":"retention","latest":<id>}and the idlatest, then continues live. The client must reload its state from the API. ALast-Event-IDhigher than the highest id the host has (the log was rebuilt, or the client talked to another host) gets the same reset with the reasonunknown-id; so does aLast-Event-IDthat is present but is not a non-negative integer (the host never starts such a stream live without telling the client). An empty value is noLast-Event-ID. - Expiry: at the stream token’s expiry the host sends
event: auth-expired, data{}, and ends the stream. The client subscribes again (new token, new tickets if it used them) and resumes with itsLast-Event-ID: nothing is lost. A stream token presented after its expiry is401. - Revocation: a field login family revoked (sessions-and-login contract section 15.7) ends that
principal’s open streams with
auth-expired. A session signed out does the same. Other credential changes take effect at the next subscribe, at mostpush.stream.max-lifetimelater.
8. Backpressure and limits
Section titled “8. Backpressure and limits”- Each stream has a buffer of
push.stream.bufferpushes (default 256). A stream that falls further behind is ended (no event; a slow client cannot get one). It resumes from itsLast-Event-IDlike any other drop. A slow client therefore never slows the others, and loses nothing within retention. - Each instance keeps the most recent
push.recentpushes (default 10 000) in memory and replays from there when it can, from the log only when it must. An instance reads the newestpush.recentpushes of the log into that memory, in one read, before it serves (amended 2026-11-08, section 17.11). After a deploy or a restart, thousands of clients resuming together are then served from memory, not the database, on the restarted instance as on one that stayed up; only a client away for longer thanpush.recentpushes reads the log, one page at a time. - Limits, each refused with
429 PUSH_LIMITat subscribe:push.max-streamsper instance (default 50 000);push.max-streams-per-principal(default 20).
- An instance that is draining (HTTP contract 13.1) ends its streams, all at once when the drain
begins (not at each stream’s next write or heartbeat), and answers no new subscribes or streams
(
503). Its clients reconnect to another instance after theretry, with jitter.
9. Clients (the SDKs)
Section titled “9. Clients (the SDKs)”The SDKs provide one reader per platform, all following sections 6 and 7:
- TypeScript (web, Node) and field-js (React Native):
- subscribe with the caller’s credentials (cookie, bearer, or DPoP through field-js) and tickets fetched from the application;
- listen with
fetchstreaming (headers allowed) orEventSource, and keep the last id; - reconnect with jitter;
- expose
onPush(topic, handler),onResetandonAuthExpired(resubscribe by default).
- Server-rendered pages (Datastar): a helper that subscribes and turns a push into a fragment reload.
- Android (field-android): the same reader in the foreground. In the background a device does not hold a stream: a mobile push notification (out of scope here) wakes it, and it resumes with its last id.
9.1 Snapshot with a cursor
Section titled “9.1 Snapshot with a cursor”A client loads its state through an ordinary read endpoint and then listens. A change committed
between the read and the listen would be missed. So the read endpoint also returns the push cursor
(a push log id, as a decimal string), and the client opens its first listen with it as
Last-Event-ID: it then receives every push after the cursor. Pushes are signals (“read X again”),
so a push for a change the snapshot already holds is harmless; a missed one is not.
- The rule: the host reads the cursor BEFORE it reads the state (before the read transaction takes its snapshot: in a REPEATABLE READ transaction before its first statement, in READ COMMITTED before the state query). Every push at or below the cursor was in the log when the cursor was read, and the relay logs a push only after the publishing transaction committed, so the change behind it is visible to a state read that starts afterwards. A change the snapshot lacks therefore has a push above the cursor.
- A cursor that lags the log is correct (more pushes are replayed), so a host may use its
in-memory last id: no I/O. Go:
pushes.Cursor;"0"for an empty log, which replays everything after 0 (or resets withretentionif the log has trimmed past it). - The endpoint chooses the field name;
pushCursoris recommended for JSON bodies. - The client passes it as
Last-Event-IDon its first listen (field-js: thelastEventIdoption ofPushStream). After aresetit reloads its state, taking a new cursor with it.
10. Configuration
Section titled “10. Configuration”| key | default | range |
|---|---|---|
push.driver |
postgres |
postgres, redis, platform (amendment 17) |
push.redis-instance |
the default Redis instance | a configured instance |
push.retention |
24h | 10m to 24h |
push.max-data-bytes |
16384 | 1 to 65536 |
push.max-topics |
100 | 1 to 1000 |
push.relay.batch / push.relay.interval |
500 / 1s | 1–5000 / 50ms–10s |
push.relay.lease |
5s | 1s to 60s |
push.stream.buffer |
256 | 16 to 10 000 |
push.stream.max-lifetime |
1h | 1m to 24h |
push.recent |
10000 | 0 to 1 000 000 |
push.max-streams / push.max-streams-per-principal |
50000 / 20 | |
push.stream.secret, push.ticket.key |
(secrets, required) | push.stream.secret is not needed with platform (amendment 17) |
11. Metrics, health and the load test
Section titled “11. Metrics, health and the load test”Metrics:
fw_push_published_total;fw_push_relay_lag_seconds(a timer: per relay run, the age of the oldest outbox row it moved; amended 2026-11-08, section 17);fw_push_log_id(gauge);fw_push_streams_open;fw_push_delivered_total;fw_push_streams_ended_total{reason}, withclient,slow,expired,revoked,drain;fw_push_resets_total{reason};fw_push_replay_source_total{source}, withmemoryorlog.
Health: background:push-relay comes from the loop. Also push:log: the log or Redis is
reachable.
Load test (P1, with the router benchmark rig). It must reach these before the module is called done, on one 8 GB Fargate task:
- Idle connections: 100 000 idle streams. Record memory per stream, and the open-file limit the task needs.
- Fan-out: 1 000 pushes/s spread over 10 000 topics. Delay from commit to client: p99 under 250 ms.
- Broadcast: one push to 50 000 streams on one topic. Time until the last stream has it.
- Restart storm: restart one of two tasks under load. Record how long until every client has resumed with nothing lost, and the database load during it (reads from memory, not the log).
12. A4: a platform push gateway (sketch, not in P0 to P4)
Section titled “12. A4: a platform push gateway (sketch, not in P0 to P4)”The platform’s specification of the gateway is docs/push-gateway-spec.md of the platform repository
(accepted 2026-11-09); it turns this sketch into a buildable plan, and its section 2.1 lists the
framework changes, built in Go as amendment 16 of section 17 (multi-application hosts, per-application
limits, the client member, hosting without the framework HTTP server, batch publishing), and
push.driver=platform, the publish sink for framework applications, as amendment 17 (Go; not Java).
The platform will host a push gateway, its own service (like the router), built on this module. Applications that cannot hold streams themselves use it, Laravel and PHP-FPM in particular. So do clients that listen to several applications on one stream (a field device), and operations that want one view. It fits on top of this contract:
- Publishing: a third sink. The push is written to the application’s outbox as a
PUSHrow, in the same transaction (every SDK writes outbox rows, Laravel included). The platform’s outbox processor hands it to the gateway, whose relay logs it. Application code does not change:andPushis the same, onlypush.driverdiffers (platform). - Topics: every topic starts with its application code (section 1), so they never collide. The gateway accepts pushes for an application only on that application’s topics.
- Rules are synced to the platform like permissions (they are data, 6.3). The gateway applies them to its own authentication: platform users, portal users, field workers.
- Tickets are verified with each application’s public keys, which the platform holds
(registered or fetched from
/push/keys). One subscribe may carry tickets of several applications (6.4). - Wire: sections 6 and 7 unchanged; the SDK readers point at the gateway’s base URL.
- Isolation: per-application limits on publish rate, data size and open streams, plus a pause. One application’s burst or storm must not slow another’s streams.
- Console:
- topics and rules per application;
- open streams per application and client;
- relay lag and delay;
- a recent pushes view per topic, gated like ingestion traces;
- retention, a test send and the pause.
- Scale: gateway tasks at 25k to 50k streams each behind the ALB; Redis (A2) between them past a few tasks.
13. Conformance vectors
Section titled “13. Conformance vectors”In conformance/push/, shared by Go and Java (and later Rust and the gateway):
topics.json: valid and invalid topics, types and data sizes, and rule patterns with(context, topic) → allowed | denied.tickets.json: a fixed Ed25519 key pair, tickets (valid, expired, wrongaud,kid,iss, topic outsideiss,cnfmismatch) and the granted and denied topics for each.wire.json: the exact bytes of a push event,subscribed,resetandauth-expired.replay.json: a log (ids, topics, clients) plus a subscription and aLast-Event-ID. Expected: the ids sent, or aresetwith its reason, covering the client rule of section 5.spelling.json(2026-11-19, written by Java): tickets and stream tokens as issued and re-spelled every way, with the answer each gets;issued-before.json: tickets and stream tokens the Go and Java code issued before the spelling rule, which must still verify (token spelling).
14. Tests (contract test suite, each driver)
Section titled “14. Tests (contract test suite, each driver)”- Pushes from a rolled-back transaction are never sent.
- Pushes from concurrent transactions committing out of id order arrive in log order with no gap and no reorder.
- Two hosts on one database: a push published on one reaches streams on the other.
- A relay killed mid-run: its replacement neither loses nor repeats a push. A2’s crash between
XADDand delete is deduplicated. - Resume after a drop; a reset for an id older than retention and for an unknown id; expiry with
auth-expired; a slow stream ended and resumed losslessly. - The client filter of section 5, including the platform client.
- Each rule and ticket case of the vectors.
- Drain ends streams and refuses subscribes.
15. Not in this contract
Section titled “15. Not in this contract”- Client-to-server messages (WebSocket).
- Presence (“who is listening”).
- Mobile push notifications.
- Ordering across hosts.
- Exactly-once beyond what the ids give: a client that resumes from an older id gets those pushes again, and drops ids it has already applied.
16. Ruling (2026-11-08)
Section titled “16. Ruling (2026-11-08)”- Tickets are EdDSA from the start, so the A4 gateway verifies them without the application’s secret.
- One subscribe mode: subscribe, then listen. No direct
GET /push/stream?topic=...with header authentication. - Retention is configurable, 24 h at most (
push.retention, 10 minutes to 24 hours). One value per host; no per-topic retention. - The first consumer (P4) is field workers’ job updates: a worker’s device listens to its own
topic (
{application}:field-worker:{principal}:jobs, rule{principal}, principal kindFIELD_WORKER) through field-js, subscribing with its field token and DPoP.
17. Amendments from the Go build (P1a, 2026-11-08)
Section titled “17. Amendments from the Go build (P1a, 2026-11-08)”Smallest calls made where the text was silent or could not be built as written:
- Publishing (section 2). Go
usecase.Push(topic, type, data)is a plan step (passed toNewPlanlikeInsertorAppend); a failure writing it isINTERNALwith step codePUSH. A plan whose only steps are pushes is valid (it is not “appends only”). The runner learnspush.max-data-bytesfromusecase.WithPushMaxDataBytes(pushes.RunnerOption; default 16384).fw_push_published_totalis counted by the relay as it logs (committed pushes only). - The relay (section 3) holds its lock (lease
push.relay.lease, default 5 s, refreshed every third of it; 15 s fixed until amendment 11) for as long as it runs: one gated run listens onfw_push_outboxand drains the outbox until shutdown or the lock is lost; another instance retries everypush.relay.interval. It takes rows withSELECT ... ORDER BY id LIMIT n FOR UPDATE, always from the head of the queue, never after a remembered id. - Retention (section 4) never deletes the newest log row, so A1’s
max(id) + 1never starts again at 1. “Older than the oldest id kept” (section 7) means: the log may have deleted a push after the client’sLast-Event-ID. A driver reports the highest id deleted (Trimmed; A1: the oldest id kept minus one, its ids having no gaps; A2: the stream’smax-deleted-entry-id), and the reset is sent whenLast-Event-IDis below it. ALast-Event-IDequal to the oldest id kept minus one loses nothing and is not reset. Replaying from the log checks this after each page it reads; a replay from memory (everything afterLast-Event-IDstill held) is never a reset. - Subscribe (6.1).
topicsmust hold 1 topush.max-topicsentries (counted as sent); duplicates are dropped;deniedis always present (an empty list). Without credentials the stream’s client is the first valid ticket’s; a request with neither credentials nor a valid ticket is401. A ticket whoseclientis not the stream’s client grants nothing (TICKET_INVALID). The limits of section 8 are also checked when the stream opens (429 PUSH_LIMITon theGET), because a stream token can be used more than once. A host that is draining answers503 UNAVAILABLE. - Rules (6.3). A pattern’s first segment is a literal and must be the application’s code (a
start-up problem otherwise); a placeholder name is
[a-z][A-Za-z0-9]*.{client}alone does not make a rule safe: it needs{principal}orrequires. A public rule allows a request without credentials. - Tickets (6.4).
push.ticket.keyis<kid>:<base64url of a 32-byte Ed25519 seed>, comma separated, the signing key first and the previous one second (at most two);GET /push/keyslists both. A minted ticket’sexpisiat+ 2 minutes. Also invalid: a header withcrit, aniatmore than a minute ahead of the host’s clock, astream-expalready past. “A DPoP proof with that key” (cnf) means the subscribe request is authenticated with a field token bound to that key (sessions contract section 15); there is no proof without a token. A ticket that names a requested topic but grants nothing makes its denialTICKET_INVALID; a malformed ticket (not a JWS compact with JSON header and claims) is400. - Revocation (section 7). Go
pushes.EndStreams(ctx, Holder{Principal, Device, Session})ends the matching streams on every instance (A1:pg_notify('fw_push_end', <holder>), which every hub follows; a hub serves streams only once it follows the log, so no such signal is missed), withauth-expired.flowcatalyst.PushHolder(event)turns a field revocation event into the holder; the application calls both from itsOnFieldRevocationhandler. A sign-out hook is not built yet. - Configuration (section 10).
push.stream.secrethas at least 32 characters;push.max-streamsandpush.max-streams-per-principalare at least 1. - Metrics (section 11).
fw_push_relay_lag_secondsis a timer: the framework’s registry refuses a gauge named_seconds.push:logis an informational health check (the database’s own check is the critical one). - A2 retention uses
XDEL(Go build, 2026-11-08). Redis moves a stream’smax-deleted-entry-idonXDELonly, not onXTRIMorXADD ... MINID(checked on Redis 8.x), andTrimmed(amendment
- is that field. So
Prunereads the entries below the edge and deletes them withXDELin batches, never the newest. The edge is a Redis entry id, that is the Redis server’s clock; the application’s clock should agree with it to within seconds.Latestislast-generated-idandTrimmedismax-deleted-entry-id; ids arems * 2^20 + seq, not contiguous. A1’s and A2’sLoginterface is the same. The channel forEndisfw:push:end(PUBLISH/SUBSCRIBE); both keys take an optional prefix.
- After the first load test (Go, 2026-11-08; [resultsnull, section “After the fixes”). Four findings fixed:
- Relay failover (sections 3 and 10). The lease is
push.relay.lease, default 5 s (1 s to 60 s), refreshed every third of it; a cleanly stopping relay releases the lock (it did, once its run returned; a run is now let finish instead of being cancelled, see the drain). After akill -9the pushes committed meanwhile arrived up to 12 to 31 s late; now about 5 s. A shorter lease is also lost sooner when the database stalls (the relay then takes the lock again). - Memory after a restart (section 8). The hub reads the newest
push.recent + 1entries in one read before it serves (Log.Newest, a method added to the driver interface: A1ORDER BY id DESC LIMIT, A2XREVRANGE). It then holds every push after the oldest of them; when the log holds no more thanpush.recent, every push after the log’sTrimmed(read after the entries, so a push pruned meanwhile is not counted as held, and a client belowTrimmedstill gets its reset from the log). A replay from the log holds one page (1000 entries) and the last 10 000 outbox ids (an A2 duplicate is logged again within one relay batch, at most 5000), never the whole replay; streams resuming from the same id at the same time share each page read. Overlapping reads from different ids are not merged: with the memory warmed they are the clients away for longer thanpush.recentpushes, and a topic filter in the read would serve them better than merging. - The drain (section 8). When the server’s drain begins, the hub ends every open stream in
one pass (reason
drain), opens no more (503 UNAVAILABLE) and stops reading the log (no stream is left to hear it). The slow shutdown was not the streams: shutdown cancelled the hub’s read of the log (and could cancel a relay run) half-way, and pgx then abandons the connection after a cancel request to PostgreSQL that it waits up to 15 s to be acknowledged; closing the pool waited for it (shutdown action overranondb). A log read or relay run under way at shutdown, or when the lock is lost, is now let finish, bounded by 10 s; a relay run that overlaps the next relay’s is safe (section 3:FOR UPDATE, A1’s primary key, A2’s outbox ids). On the test Mac, closing tens of thousands of loopback connections at once also stalls the kernel for seconds; that is the machine’s, not the module’s. - Memory per stream (section 8). The stream buffer holds pointers to the pushes, each encoded
once as its SSE event and shared by every stream; it grows only as far as the stream falls
behind (an idle stream holds none).
push.stream.bufferstill counts pushes and a full buffer still ends the stream. A stream keeps two goroutines (the handler and net/http’s read of the connection, which notices a client that left at once); one would need a hijacked connection that notices a closed client only at its next write.
-
Snapshot cursor (section 9.1, 2026-11-09). Go
pushes.Cursorreturns the hub’s highest dispatched id as a decimal string (“0” for an empty log), with no context and no error. It is read before the state; a lagging cursor is safe.Last-Event-ID: 0works as any other id: it replays everything after 0, or resets withretentionif the log has trimmed past it. -
Invalid
Last-Event-ID(section 7, 2026-11-09). ALast-Event-ID(header orlastEventIdquery) that is present but not a non-negative integer (12-34,abc,-1) is answered withreset(reasonunknown-id, idlatest) aftersubscribed, then the stream continues live. Before, it was treated as absent and the client silently missed changes. An empty or blank value is still no cursor.conformance/push/replay.jsonhas the case. -
The Java build (P2a, 2026-11-09).
framework-pushimplements sections 1 to 11 and the amendments above; a Java host and a Go host on one database share the tablesfw_push_outboxandfw_push_log, the channelsfw_push_outbox,fw_push_logandfw_push_end(the same payloads), the relay locksvc:push-relayand the migration history keypush. Stream tokens are valid on the hosts that sharepush.stream.secretonly, as before. What the Java build settled:- Layout. One module,
framework-push, holds the core and the A1 driver: the outbox is always on the default database and the relay is database-bound, so there is no database-free core to split off asframework-locks/framework-locks-databaseare. TheLoginterface is public, so a Redis driver can be its own module (framework-push-redis, likeframework-locks-redis);PushModule.Builder.redis(provider)plugs the Redis one in, andpush.driverrediswithout it is a start-up problem (amendment 15 replaced the first form of this,Builder.log). The valuePushand the writing of the outbox row (PushOutbox) are inframework-usecase, which the runner needs and whichframework-pushdepends on, as Go’sinternal/pushrowis shared byusecaseandpush. - Publishing (section 2).
plan.andPush(push)adds a push after the steps added so far (and after the appends of the last of them), written by the runner in the attempt’s transaction (step codePUSH); a plan always has an event step, so the Go case “a plan of pushes only” does not arise.Push.of(topic, type, data)(a map, a record or a Jackson tree; map keys sorted) andPush.ofJson(...)refuse a bad topic, type or data with anInvalidPushException(anIllegalArgumentExceptionwith the reason code oftopics.json); thrown while a use case is decided it fails the run asINTERNAL/INVALID_PUSH(notEXECUTE), logged as a bug, as does a push overpush.max-data-bytes. The module tells the runner the limit when it boots (UseCases.pushMaxDataBytes; default 16384).Pushes.publish(tx, context, push)takes the framework’sTx; over the limit it throwsInvalidPushExceptionDATA_TOO_LARGE. - Relay (section 3, amendments 2 and 11). The loop
push-relayis gated by the locksvc:push-relaywith the leasepush.relay.lease; its task holds the lock for as long as it runs, listening onfw_push_outbox(a connection of its own) and polling everypush.relay.interval. The lock’s loss interrupts the loop’s thread; a run is made on a thread of its own that nothing interrupts and is waited for up to 10 s, so a stop or a lost lock never leaves a run half-way. - The hub. Streams run on the HTTP server’s virtual threads, one each, parked on a queue; the
hub keeps two virtual threads (the reader of the log and the driver’s follower, whose pooled
connection it holds for as long as it runs). It warms its memory when the application boots,
before the server is started, and the application’s start waits up to 10 s for the follower.
The server’s drain reaches the hub through
HttpServer.beforeDrain, so every stream ends at once. Difference from Go: a client that went away is noticed at the stream’s next write, at the latest at the heartbeat (http.sse.heartbeat, 25 s by default, which the push stream uses), not at once; its slot under the limits of section 8 is freed then. - Authentication (6.1).
PushAuth.authModuleauthenticates a subscribe through the auth module as Go’sAuthModuledoes. The build addedAuthContextResolver.carriesCredentialsandAuthContextResolver.authenticatedandFieldPrincipal.keyThumbprint(the token’scnf.jkt), the parallels of Go’sModule.CarriesCredentials,auth.CurrentandFieldPrincipal.KeyThumbprint. - Revocation (amendment 7).
PushHolders.of(FieldRevocation)inframework-flowcatalystis Go’sflowcatalyst.PushHolder(the module depends onframework-pushoptionally);Pushes.endStreams(Holder)isEndStreams. - Configuration (section 10). The ranges are checked when the module is built and reported
together as a start-up failure; topic rules are declared on the module’s builder (
topic,publicTopic), and an open rule is a start-up problem as in Go.
- Layout. One module,
-
The Java Redis driver (A2, 2026-11-09).
framework-push-redis(RedisPushLog,RedisPushLogs) is the GoRedisStreamLogon Jedis: the same keys (<prefix>fw:push,<prefix>fw:push:end), the same fields in the same order, the same payload on the end channel, the same id mapping (ms * 2^20 + seq, a sequence of 2^20 or more is an error),Appendas oneMULTI/EXECofXADD,ReadAfterby exclusiveXRANGE,NewestbyXREVRANGE,Latestthe stream’slast-generated-id,Trimmeditsmax-deleted-entry-id,PrunebyXDELin batches of 1000 that never deletes the newest and sends nothing for an edge at or before the epoch, andFollowbyXREAD BLOCK(one second) plus a subscription to the end channel. The contract tests of section 14 and the wire and replay vectors run on both drivers. What differs from Go, and why:- Selection. Go’s
RedisClients(clients, prefix)option becomesPushModule.Builder.redis(RedisPushLogs.redis(prefix)): the provider readspush.redis-instance(the default Redis instance when unset) from the framework’sRedisConnections, soRedisModuleis listed too.push.driver=rediswithout the builder call is a start-up problem naming it; withpush.driver=postgresthe call is ignored, as in Go.Builder.log(provider)stays for a driver of your own and wins over both settings. This is amendment 14’s “layout” rule, refined:framework-pushcannot depend on the driver module (no scanning, no reflection for wiring). - Failure.
FollowthrowsLogExceptionwhere Go returns an error;LogExceptiongained a constructor with a message only (a stored entry that cannot be read has no cause). - Connections. Jedis has no cancellable blocked read, so the subscription runs on a virtual
thread of its own and
followunsubscribes and joins it when it returns; a follower holds two pooled connections (the subscription and theXREAD). - Tests. The Java contract suites take a
LogBackend;framework-pushpublishes its test classes (atest-jar) andframework-push-redisextends them. The replay vector’s host starts its clock at the epoch for every driver, because A2’s vector ids are milliseconds near 0 and a retention edge of “clock less retention” would otherwise prune them while the test loads the log (the same race Go fixed).
- Selection. Go’s
-
Multi-application hosts (A4, Go, 2026-11-09). The framework side of the platform gateway (
docs/push-gateway-spec.mdof the platform repository, sections 2.1, 4, 9 and 10), in Go only for now (the gateway is Go; the Java module has none of it). A host that serves one application behaves exactly as before: every item below is opt-in, and the error bodies and codes of the existing limits and denials are unchanged.- Many applications in one host (6.3, 6.4, 1).
push.MultiApplication(rules, keys, opts...)is aBuildoption.rulesis aRuleProvider(Rules(application) []Rule),keysaTicketKeyResolver(PublicKey(issuer, kid) (ed25519.PublicKey, bool)). Both are read for every subscribe and listen, so the host may change what they answer at any time (the gateway reloads on sync); the module caches nothing. A topic is granted by a rule of its own application only: the application is the topic’s first segment, and the rules arerules.Rules(application), those of another application’s pattern ignored. A ticket is verified with the key the resolver gives for itsissandkid(anissthat is not an application code, an unknown issuer or kid grants nothing), and grants topics of its issuer’s application only (a ticket ofalphanaming abetatopic grants nothing:topic-outside-iss). Tickets of several issuers compose in one subscribe. A ticket naming another client than the stream’s grants nothing, as 17.4 says: the stream’s client is the credentials’ or, without credentials, that of the first valid ticket (or the client the body names, below), whatever the issuers. An application the providers do not know has its topics deniedTOPIC_FORBIDDEN(orTICKET_INVALIDwhen a ticket that fails names the topic), never an error for the whole subscribe. In this mode the rules declared onDeclared(Topic,PublicTopic) are a start-up problem: the providers are the only source.push.ticket.keyis used only to mint tickets (Ticketmints for the host’sApplication) and to serveGET {base}/push/keys;DeclareWith(app, OptionalTicketKey)makes it optional for a host that mints nothing, and the endpoint then answers{"keys":[]}andTicketfails. A single-application host still needs the key, andBuildreports its absence. - Limits per application (8).
AppLimits{MaxStreams, MaxDataBytes}come from anAppLimitProvider(AppLimitsFrom(p), read for every subscribe, listen and publish, so the gateway’s console edits apply at once), with a default (DefaultAppLimits(l); initiallyDefaultAppMaxStreams= 20 000 streams and push.max-data-bytes); a field that is zero or less takes the default. The hub counts the open streams of each application on the instance; a stream whose granted topics span several applications counts against each of them. A subscribe or a listen that would take an application over itsMaxStreamsis429 PUSH_LIMIT, checked with the existing limits (after them), with the scope and the application in the envelope’sdetails:{"error":"PUSH_LIMIT","message":"...","details":{"scope":"application","application":"beta"}}. The existing limits keep their body withoutdetails.MaxDataBytesreplaces push.max-data-bytes for the topics of the application (at most 65536) when a push is published:Publish,PublishAloneandPublishBatchaccept a push for any application in this mode and refuse data over its application’s limit withDATA_TOO_LARGE. Left to the gateway: publish rate and the pause (it limits at ingest, before it writes), refusing pushes for an application it does not know, and theusecase.Pushrunner, whose limit stays the host’s push.max-data-bytes. - The
clientmember (6.1). The subscribe body takes an optionalclient([A-Za-z0-9._-]{1,100}, else400 VALIDATION):{"topics":[...],"tickets":[...],"client":"..."}. An authenticator that can act for several clients implementsClientAuthenticator(AuthenticateClient(r, client),clientbeing “” when the body names none), which the module calls instead ofAuthenticate; it answers400 VALIDATIONfor a credential with several clients and none named, and403 CLIENT_FORBIDDENfor one that cannot use the client named. The module checks once more, for every authenticator, that a client named equals the Context’s client, else403 CLIENT_FORBIDDEN; anAuthenticatorthat is not aClientAuthenticator(AuthModule) behaves as before whenclientis absent. Without credentials the stream’s client is the first valid ticket’s that names the client given; if none does,401. A platform-wide stream is aclientof the platform client’s value (_platform) that the authenticator permits. - Hosting without the framework server.
Pushes.Handler(opts ...httpfw.Option)serves the three routes underBasePathas anhttp.Handler(mount it without stripping the prefix), through the framework’s dispatcher: the error envelope, the correlation id, the body limit and an access log that never records the query (so the stream token is not logged).httpfw.WithDrain(new, public) gives a dispatcher the drain signal thathttpfw.Drainingreturns.Pushes.Drainbegins the module’s drain for a host without an httpfw server: the hub ends every stream at once (reasondrain) and a subscribe or listen is503 UNAVAILABLE(8, 17.11). It is idempotent, and the module also calls it when the application shuts down.DeclareWith(app, ExternalMigrations)leaves the module’s migration set out: the host createsfw_push_outboxandfw_push_logitself, byte for byte asgo/push/migrations/V0001__create_push_tables.sql, and keeps them identical to it when the module changes. - Batch publishing (2).
Pushes.PublishBatch(ctx, tx, items ...Publication)andPublishBatchAlone(ctx, items...)write pushes, each aPublication{Context, Push}with its own client, with one statement in the caller’s transaction (or one of its own): all of the rows and the one notification exist when it commits, or none. Every item is checked before anything is written (a zero Context or Push, data over its limit), and the error names the item’s position. The rows get outbox ids in the order given, so the log keeps it. - Release. The core module
github.com/flowcatalyst/framework/gois versioned by the taggo/vX.Y.Z(make -C go release-go BUMP=0.1.0for the first); the platform imports it from the first such tag.
- Many applications in one host (6.3, 6.4, 1).
-
push.driver=platform(A4, Go, 2026-11-09). The publish sink for an application that uses the platform’s push gateway (docs/push-gateway-spec.mdof the platform repository, sections 2.1 item 4, 6.1, 6.4 and 8) instead of hosting push itself. Application code does not change (usecase.Push,Pushes.Publish); the application moves between the two by configuration.- Setting.
push.driveracceptsplatformnext topostgresandredis. With it the module keeps no log, hub, relay or retention loop and nopush:loghealth check, serves no routes (Routesis empty,Handleranswers 404,Draindoes nothing), and needs nopush.stream.secret(a value that is set is ignored, so a deployment can switch by changing one key;AuthenticateandRedisLogoptions are ignored with a warning,BasePathhas no effect).push.ticket.keyis required (tickets are still minted here and verified by the gateway), the lock instances are not used, the default database instance is.platformwithMultiApplicationis a start-up problem (a gateway does not publish through another). - The row.
usecase.Push(any use case),Pushes.Publish,PublishAlone,PublishBatchandPublishBatchAlonewrite onePUSHrow per push to the application’soutbox_messages, in the caller’s transaction (the run’s transaction forusecase.Push, in plan order; the caller’stxforPublishandPublishBatch; its own for the...Aloneforms), with the columns of the sharedinsert.sqland the statementWITH woken AS (SELECT pg_notify('fc_outbox_push', '')) INSERT ... SELECT ... FROM woken, so the platform’s outbox processor wakes when the transaction commits and not before. Row:ida TSID (or the push’s own id),typePUSH,message_groupthe topic by default,status0,client_idthe Context’s client,payload_sizethe payload’s bytes,headersnull. Payload, compact, members in this order:topic,type,data(the JSON object itself),clientCode(the Context’s client, absent for the platform client, like a dispatch job),pushId(= the row id). It is the vectorconformance/outbox/outbox-push.json, which the Go outbox conformance test writes and compares byte for byte, with itsinvalidPushes(the codes of section 1, andPUSH_ID_INVALID,CLIENT_INVALID). - Options.
usecase.Push(topic, type, data, opts...)takesPushUngrouped(no message group: the processor sends such rows concurrently, no order),PushMessageGroup(g),PushID(id)(the row id andpushId,[0-9A-Za-z_-]{1,26}) andPushClientCode(code)(a client other than the Context’s, by identifier). The first two are ordering hints the hosted drivers ignore (they log in commit order).PushIDandPushClientCodeexist only in this row: with a hosted driver a push that carries them fails the run asINTERNAL/INVALID_PUSH(reasonOPTION_UNSUPPORTED) rather than lose them silently. The runner learns the driver fromPushes.RunnerOption(usecase.WithPlatformPushes);usecase.NewRunner(b, outbox, db, pushes.RunnerOption)is unchanged. The data limit ispush.max-data-bytes, as before. - Ordering. The guarantee “log order = commit order” is the gateway’s (spec 6.5): the pushes of one message group (default one topic) of this application arrive in outbox order.
- Sync. The
flowcatalystmodule (flowcatalyst.WithPushes(pushes)) sends the gateway the rules declared onpush.Declaredand the JWKS ofpush.ticket.keywithPOST /api/applications/{app}/push/sync, body{"rules": [{"pattern", "requires", "public"}], "keys": <JWKS>}(Pushes.GatewaySync), a declarative full replace, as a categoryPUSHafter the definitions: by thesynccommand (with--dry-runit lists the patterns and sends nothing) and, whenflowcatalyst.sync.on-bootis set, at start-up (a failure is logged, never fatal). WithoutWithPushes, or with another driver, the module does nothing for push. With the module disabled the rules are not synced (warned at start). The private seeds never leave the application. - No local cursor. The gateway owns the log, so
Pushes.Cursorreturns""(andHasCursoris false) instead of a number that means nothing to the gateway. A snapshot endpoint that returns""gives the client nothing to send asLast-Event-ID; its first listen is then live, and the client closes the gap between its state read and the listen by reading the state once more when its stream reportssubscribed(section 9.1’s reasoning, applied by the client). A cursor read from the gateway is a platform API that does not exist yet. - Streams.
Pushes.EndStreamsandEndPrincipalreturnErrPlatformDriver: the gateway ends the streams of a platform sign-out and of a revoked field login itself (spec section 5). An application’s own ticket-only sessions cannot be ended from here yet. - Moving between hosting and the gateway. The clients’
baseUrlchanges and they reload once; their last ids mean nothing on the other host (resetwithunknown-id, spec 6.4). - Java has none of this (
framework-push,Plan.andPush, theflowcatalystsync): it would need the sameplatformdriver value, aPUSHrow writer inframework-usecaseforPlan.andPushandPushes.publish,Pusheswithout hub or routes, and the push category in theflowcatalystmodule’s sync.
- Setting.