Outbox
Events are not published over HTTP. Your code writes a row to the outbox_messages table in the same
database transaction as the business change, and a relay sends the rows to the platform. Why, and
how the relay behaves, are in the transactional outbox. This page is the Java API.
Create the table with the SDK’s migration for your database (migrations/postgresql or
migrations/mysql in the SDK directory). The PostgreSQL migration is:
CREATE TABLE outbox_messages ( id VARCHAR(26) PRIMARY KEY, type VARCHAR(20) NOT NULL, message_group VARCHAR(255), payload TEXT NOT NULL, status SMALLINT NOT NULL DEFAULT 0, retry_count SMALLINT NOT NULL DEFAULT 0, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), error_message TEXT, client_id VARCHAR(26), payload_size INTEGER, headers JSONB);The migration also creates the relay’s partial indexes on pending (status = 0) and claimed
(status = 9) rows, and an index on client_id, status, created_at. A relay (fcdev outbox or the
fc-server outbox subsystem) must be running against the database. fcdev outbox reads a MySQL 8.0+ or
MariaDB 10.6+ outbox as well as a PostgreSQL one; see
which relay drains which database.
var driver = new JdbcOutboxDriver(dataSource); // table "outbox_messages"var outbox = new OutboxManager(driver, "clt_0HZXEQ5Y8JY5Z"); // the owning client's idnew JdbcOutboxDriver(dataSource, "my_outbox") uses another table name. OutboxManager also has
constructors that take an InstantSource clock and a clientCode (the client’s identifier slug, used
as the default client for dispatch jobs and pushes that name none; under OutboxManager.PLATFORM_CLIENT_CODE
(_platform) they carry none).
The manager’s first argument is the client id written to each row’s client_id column. It is
required; an empty value throws IllegalStateException.
Writing in your transaction
Section titled “Writing in your transaction”The transaction handle is opaque to the SDK; for JdbcOutboxDriver it is a java.sql.Connection. Pass
the same handle to your business writes and to the outbox:
driver.withTransaction(tx -> { var connection = (Connection) tx; // business writes on connection ... outbox.createEvent(CreateEventDto .create("orders:sales:order:placed", Map.of("orderId", orderId)) .withMessageGroup(orderId), tx); return null;});withTransaction opens a transaction on a connection from the data source, runs the callback, commits,
and rolls back on a RuntimeException. If you already manage the transaction (Spring, jOOQ, a
connection you hold), pass your Connection as tx and the row joins it.
With no tx argument the write is not atomic with your data. outbox.createEvent(dto) writes on
its own connection and its own commit. That is rarely what you want. Pass the handle.
Events
Section titled “Events”CreateEventDto.create(type, data) takes the event type and a Map<String, Object> of data.
var event = CreateEventDto.create("orders:sales:order:placed", Map.of("orderId", orderId)) .withSource("orders:sales") .withSubject("sales.order." + orderId) .withMessageGroup("sales:order:" + orderId) .withClientCode("acme") .withCorrelationId(correlationId);String eventId = outbox.createEvent(event, tx);| Method | Sets |
|---|---|
withSource, withSubject |
Source and subject. A blank source is left out and the platform defaults it to the type’s application:subdomain. |
withCorrelationId, withCausationId |
Tracing ids. |
withDeduplicationId |
Your own dedup key. Unset, the row id is used, so a batch the relay sends twice does not create a second event. |
withMessageGroup |
The ordering key. |
withClientCode |
The client, by identifier slug. The platform resolves it at ingest. |
withContextData(List<ContextEntry>) |
Key and value pairs carried with the event. |
withHeaders(Map) |
SDK-side headers stored in the row’s headers column. |
- The event
typemust be fully qualified,application:subdomain:aggregate:action, four non-empty segments. The SDK throwsIllegalArgumentExceptionon a bare code, because the platform facets on the segments and resolves delivery credentials from the application. datais written as one encoded JSON string, as the framework’s writer does. The platform unwraps it at ingest, so subscribers get the object.createEvents(List<CreateEventDto>, tx)writes a batch in one statement and returns the ids.
Dispatch jobs
Section titled “Dispatch jobs”A dispatch job is one item of POST /api/dispatch-jobs/batch. CreateDispatchJobDto.of(code, targetUrl)
uses the platform’s defaults: kind TASK, source the code’s application segment, payload {},
dataOnly false, and the sequence, timeout and retries left to the platform.
outbox.createDispatchJob(CreateDispatchJobDto .of("ingest:orders:record", "https://api.example.com/records") .withId(recordId) // the row id and the job id; generated when unset .withClientCode("acme") // the client's identifier; or withPlatformClientId(id) .withPayload(line, "text/csv") .withDataOnly(true) .withMessageGroup(fileId) .withSequence(lineNumber) // at least 1 .withMetadata("source", "sftp"), tx);- Every job is checked by
validate()before it is written or sent, so a job the platform would refuse is never stored. The rules are the same as in the Go SDK: a{application}:{rest}code, an absolute http(s) target with no user info, ids matching[0-9A-Za-z_-]{1,17}, positive sequence, timeout and retries, at most 100 metadata entries.createDispatchJobs(list, tx)validates every job before writing any row. metadatais written as the platform’s[{"key","value"}]array.connectionIdandidempotencyKeyare written when set.idempotencyKeyis never defaulted: set one when a re-sent batch must not create a second job (within the job’s application and client, kept 7 days; at most 100 bytes).- An unknown
clientCoderefuses the whole batch (400 for an anchor, 403 otherwise). headersandretryStrategyare not written: the batch endpoint ignores them.scheduledForandexpiresAtare not written either, although the platform now accepts both on a dispatch job: this SDK does not send them yet (withScheduledForandwithExpiresAtare deprecated no-ops). The Laravel SDK sends them.- The older
CreateDispatchJobDto.create(source, code, targetUrl, payload, dispatchPoolId)keeps the 0.0.12 defaults (dataOnlytrue, 30 seconds, 5 retries, a four-segment code). Preferof. - Jobs that do not need to be atomic with a database write can go straight to the platform:
client.dispatchJobs().createBatch(jobs).
Audit entries
Section titled “Audit entries”outbox.createAuditLog(CreateAuditLogDto.create("User", userId, "CREATE") .withOperationData(Map.of("email", "user@example.com")) .withPrincipalId(principalId) .withApplicationCode("orders") .withClientCode("acme"), tx);performedAt defaults to the manager’s clock. The platform refuses an audit entry without a
principalId, and requires applicationCode from an application-scoped credential; the Java writer does
not check either, so set them. operationData is written as an encoded JSON string. The Java writer
does not redact it (the Go SDK redacts before it writes); the platform redacts the value it stores.
Keep secrets out of operationData anyway: the row sits in your outbox table in the clear until the
relay has sent it.
Push to clients
Section titled “Push to clients”A push is a signal to the browsers and apps listening on a topic. It is written to the
outbox in the same transaction as the change, as a PUSH row, which the relay sends to
POST /api/push/batch. Upgrade the relay before an application writes one: an older relay fails the
row.
driver.withTransaction(tx -> { // business writes ... outbox.createPush(CreatePushDto.create("shop:orders:ord_2", "order.updated", Map.of("status", "shipped")), tx); return null;});| Rule | Value |
|---|---|
| Topic | {application}:{segment}(:{segment})*, at most 255 characters. |
| Type | [a-z][a-z0-9-]*(.[a-z][a-z0-9-]*)*, at most 100 characters. reset, auth-expired, subscribed and fw.* are reserved. |
| Data | A JSON object of at most 16 KiB. withMaxDataBytes(n) raises the limit to 64 KiB at most. |
| Message group | The topic by default, so one topic’s pushes reach the gateway in order. withUngrouped() batches for signal-only topics; withMessageGroup(...) replaces it. |
A refused push throws PushException with a code() (TOPIC_INVALID, TYPE_INVALID,
TYPE_RESERVED, DATA_INVALID, DATA_NOT_OBJECT, DATA_TOO_LARGE, PUSH_ID_INVALID or
CLIENT_INVALID) and nothing is written. On PostgreSQL JdbcOutboxDriver runs pg_notify on
fc_outbox_push in the insert statement, so the relay delivers at once; other databases rely on the
relay’s poll.
Who may listen: rules and tickets
Section titled “Who may listen: rules and tickets”Who may listen is declared per application and synced with the other definitions. Clients without credentials listen with a ticket that your backend mints after its own access check:
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/sync; SyncResult.push()
String ticket = minter.mint(TicketMinter.Request.of("acme", List.of("shop:orders:{id}")).withSub("prn_1"));- Tickets are
EdDSA(Ed25519) JWTs with the audiencefw-push. The default lifetime is 60 seconds and the maximum 300; a ticket names at most 100 topics. withSub,withJkt,withTtlSecondsandwithStreamExprefine a request.- Key rotation. Pass the old public keys as the minter’s previous keys, sync, wait one ticket lifetime after signing with the new key, then drop the old key and sync again.
See push to clients and topics and tickets.
Messages and statuses
Section titled “Messages and statuses”The driver writes status 0 (pending) and the relay owns every later state. OutboxMessage.MessageType
is EVENT, DISPATCH_JOB, AUDIT_LOG or PUSH. A write failure is a
JdbcOutboxDriver.OutboxPersistenceException wrapping the SQLException.
A different database layer
Section titled “A different database layer”OutboxDriver is the seam: insert(message, tx), insertBatch(messages, tx) and an optional
withTransaction. Implement it to write through another persistence layer, keeping the INSERT byte
for byte as in JdbcOutboxDriver.insertSql(). OutboxConformanceTest pins the SDK’s rows against the
framework’s conformance vectors.
Read next
Section titled “Read next”- The transactional outbox: the relay, ordering, retries and idempotency.
- Publish events with the outbox
- Dispatch jobs