Publish events with the outbox
Your application publishes an event by writing it as a row in an outbox_messages table in its
own database, inside the transaction that makes the business change. A relay (fcdev outbox)
then sends the rows to the platform. This page is the how-to; the transactional
outbox explains why it works this way and exactly how the relay claims, orders
and retries rows.
You need an application and its service-account credentials (register an application), and the event types registered with definition sync. An event of a type the platform does not know is stored but matches no subscription.
1. Create the table
Section titled “1. Create the table”Every SDK writes the same table, and fcdev outbox reads it. Create it with your own migrations
from the SDK’s DDL, or with the command:
| Migration source | |
|---|---|
| Any | fcdev outbox create-table --db-url <url> (--db-type postgres, mysql or mongodb); idempotent |
| Go | outboxpgx.InitSchema(ctx, pool) or outboxsql.InitSchema (use your own migrations in production) |
| Java | migrations/postgresql and migrations/mysql in the SDK |
| TypeScript | migrations/postgresql/001_create_outbox_messages.sql (and mysql) in the package |
| PHP | php artisan vendor:publish --tag=flowcatalyst-migrations && php artisan migrate |
| Rust | flowcatalyst_sdk::outbox::schema::init_postgres_schema(&pool) |
fcdev outbox also creates the PostgreSQL table on its first start when it is missing.
2. Write an event with your change
Section titled “2. Write an event with your change”The Go SDK writes outbox rows through a use case: usecaseop.Run applies the plan the
operation returns in one transaction (aggregate, event row, then the audit row when auditing is
on).
Execute: func(_ context.Context, cmd PlaceOrderCommand, ec usecase.ExecutionContext) (usecaseop.Plan[OrderPlaced], error) { order := &Order{ID: tsid.GenerateWithPrefix("ord"), TotalCents: cmd.TotalCents} meta := usecase.NewEventMetadata(ec, "orders:sales:order:placed", "orders:sales", usecase.BuildSubject("sales", "order", order.ID)) meta.MessageGroup = usecase.BuildMessageGroup("sales", "order", order.ID) return usecaseop.Save(order, repo, OrderPlaced{Meta: meta, OrderID: order.ID}), nil},
// wiringsink := outboxpgx.NewSink(outboxpgx.Config{ ClientCode: "acme", // optional: the client the events belong to ApplicationCode: "orders", // required on audit rows for an application-scoped credential AuditEnabled: true,})uow := usecasepgx.New(pool, sink)event, err := usecaseop.Run(ctx, uow, PlaceOrder(repo), cmd, usecase.NewExecutionContext(principalID))With database/sql (PostgreSQL or MySQL) inside a transaction you run yourself:
w, _ := outboxsql.NewWriter(outboxsql.DialectPostgres, outboxsql.WriterConfig{ClientCode: "acme"})
then w.WriteEvent(ctx, tx, event).
var driver = new JdbcOutboxDriver(dataSource);var outbox = new OutboxManager(driver, outboxClientId);
driver.withTransaction(tx -> { orders.insert((Connection) tx, order); // your business write outbox.createEvent(CreateEventDto .create("orders:sales:order:placed", Map.of("orderId", order.id())) .withMessageGroup("sales:order:" + order.id()) .withClientCode("acme"), tx); return null;});import { Pool } from "pg";import { CreateEventDto, OutboxManager, PgOutboxDriver } from "@flowcatalyst/sdk";
const driver = new PgOutboxDriver(new Pool({ connectionString }));const outbox = new OutboxManager(driver, outboxClientId);
await driver.withTransaction(async (tx) => { await tx.query("UPDATE orders SET status = 'placed' WHERE id = $1", [orderId]); await outbox.createEvent( CreateEventDto.create("orders:sales:order:placed", { orderId }) .withMessageGroup(`sales:order:${orderId}`) .withClientCode("acme"), tx, );});use FlowCatalyst\Facades\Outbox;use FlowCatalyst\Outbox\DTOs\CreateEventDto;use Illuminate\Support\Facades\DB;
DB::transaction(function () use ($order) { $order->update(['status' => 'placed']);
Outbox::createEvent( CreateEventDto::create( type: 'orders:sales:order:placed', data: ['orderId' => $order->id], )->withMessageGroup("sales:order:{$order->id}") ->withClientCode('acme') );});The database driver writes on Laravel’s connection (FLOWCATALYST_OUTBOX_CONNECTION, else the
default). Outside a DB::transaction it logs a warning and writes anyway; set
FLOWCATALYST_OUTBOX_STRICT_TRANSACTIONS=true to make that an error.
use flowcatalyst_sdk::outbox::{CreateEventDto, OutboxManager, PgOutboxDriver};
let driver = PgOutboxDriver::new(pool.clone());let outbox = OutboxManager::new(driver.clone(), outbox_client_id)?;let event = CreateEventDto::new("orders:sales:order:placed", &order_placed)? .message_group(format!("sales:order:{id}")) .client_code("acme");
let mut tx = pool.begin().await?;// ... business writes on &mut *tx ...driver.insert_in(&mut tx, &[outbox.prepare_event(&event)?]).await?;tx.commit().await?;The manager’s client id (Java, TypeScript, Rust; Laravel’s FLOWCATALYST_OUTBOX_CLIENT_ID, which
defaults to FLOWCATALYST_CLIENT_ID) fills the row’s client_id column in your table. It labels the
row and is not sent with the event.
What to set on an event
Section titled “What to set on an event”| Field | Set with | Notes |
|---|---|---|
type |
the constructor | Required. Four segments, application:subdomain:aggregate:event, starting with your application’s code; the SDKs refuse anything else before writing. |
data |
the constructor | A JSON object. Keep it to the facts of the change; schemas on the event type are documentation, not validation. |
messageGroup |
withMessageGroup / message_group |
The ordering key: events of one group are delivered in order to each subscriber. Use the aggregate (sales:order:<id>), never a constant (one group for everything serialises everything). See ordering. |
clientCode |
withClientCode / client_code; Go ClientCode on the sink |
The client (tenant) the event belongs to, by identifier. Leave it empty and the platform scopes by the credential. A code the credential cannot reach refuses the whole batch (403). |
source |
withSource |
Defaults to application:subdomain of the type. |
subject |
withSubject |
What the event is about, for example sales.order.<id>. |
correlationId, causationId |
withCorrelationId, withCausationId |
Tie the event to the request or event that caused it. |
deduplicationId |
withDeduplicationId |
Defaults to the row id, so a batch the relay sends twice stores one event. Set your own when the key should be a business identifier. |
contextData |
withContextData (Java, TypeScript, PHP), context (Rust) |
Extra key/value pairs carried to subscribers’ jobs as metadata. |
3. Queue a dispatch job (optional)
Section titled “3. Queue a dispatch job (optional)”A dispatch job is a delivery to one URL without a subscription: “call this endpoint with this payload, reliably”. It goes into the same table and the same transaction.
job, err := outbox.NewDispatchJob("orders:billing:invoice-export", "https://billing.example.com/exports"). WithEventID(event.EventID()). WithClientCode("acme"). WithIdempotencyKey("export-" + inv.ID). WithJSONPayload(map[string]any{"invoiceId": inv.ID})if err != nil { return nil, err}return usecaseop.Save(inv, repo, event).Dispatch(job), niloutbox.createDispatchJob(CreateDispatchJobDto .of("orders:billing:invoice-export", "https://billing.example.com/exports") .withJsonPayload(Map.of("invoiceId", invoiceId)) .withClientCode("acme") .withIdempotencyKey("export-" + invoiceId), tx);await outbox.createDispatchJob( CreateDispatchJobDto.create( "orders", // source "orders:billing:invoice:export", // code "https://billing.example.com/exports", // target { invoiceId }, // payload poolId, // dispatch pool id ).withIdempotencyKey(`export-${invoiceId}`), tx,);use FlowCatalyst\Outbox\DTOs\CreateDispatchJobDto;
Outbox::createDispatchJob(CreateDispatchJobDto::create( source: 'orders', code: 'orders:billing:invoice:export', targetUrl: 'https://billing.example.com/exports', payload: ['invoiceId' => $invoice->id], dispatchPoolId: $poolId, )->withClientCode('acme') ->withIdempotencyKey("export-{$invoice->id}"));use flowcatalyst_sdk::outbox::DispatchJob;
let job = DispatchJob::builder("orders:billing:invoice-export", "https://billing.example.com/exports") .json_payload(&serde_json::json!({ "invoiceId": invoice_id }))? .message_group(format!("invoice:{invoice_id}")) .build()?;driver.insert_in(&mut tx, &[outbox.prepare_dispatch_job(&job)?]).await?;- Idempotency. Dispatch jobs are not deduplicated by id. An
idempotencyKey(at most 100 characters) makes the create idempotent within the job’s application and client: a repeat creates nothing and answers the first job’s id. Keys are kept for 7 days. - Who signs it. Name a connection (
withConnectionId) to have that connection’s service account sign the delivery and to let pausing the connection hold the job; otherwise the application’s service account signs. See who signs a delivery. - Schedule, expiry and codes. The platform (from fcdev 0.36.0) accepts
scheduledFor(the job is not claimed before it),expiresAt(a job still undelivered then is settledEXPIRED, nothing sent; it must be afterscheduledFor) and the pool and connection by code (dispatchPoolCode,connectionCode, used only when the matching id is absent), as RFC 3339 times. Only the PHP SDK (Laravel 0.27.0) sends them today:withScheduledFor,withExpiresAt,withDispatchPoolCodeandwithConnectionCode. The Go, Java, TypeScript and Rust outbox DTOs do not send them: Java and TypeScript keepscheduledForandexpiresAtmethods that have no effect, and Go has no such field. Use the pool and connection ids there. - Fields that are never sent.
headersandretryStrategyexist on some SDKs’ DTOs for compatibility, but the batch endpoint does not take them, so they have no effect. - Naming a direct job. The console names a job raised without a subscription from the
job descriptor catalogue
(one name per job code, kept by an administrator), so you need not send a name with every job. The
descriptorfield (GoWithDescriptor, JavawithDescriptor, Rustdescriptor) is stored on the row and used only when the code has no catalogue entry. - The Rust builder does not offer
clientCode,connectionIdoridempotencyKeyyet; useplatform_client_idfor the client.
A job that does not need to be atomic with a database write can go straight to the platform instead
(client.dispatchJobs().createBatch(...) in Java, FlowCatalyst::dispatchJobs()->create(...) in
PHP); give those an idempotency key, because the client may retry a request. See
call the platform API for which failures each SDK retries.
4. Run the relay
Section titled “4. Run the relay”Rows wait in your table until a relay sends them. Run fcdev outbox beside your application, in
development and in production:
fcdev outboxIt reads ./.env (variables already set win): FC_OUTBOX_SOURCE_DB_URL (your database, required),
FC_OUTBOX_PLATFORM_URL (default http://localhost:8080) and the service-account credentials
FLOWCATALYST_CLIENT_ID / FLOWCATALYST_CLIENT_SECRET, with which it mints and refreshes its own
token. fcdev day to day lists every
setting.
You may run any number of relays against one outbox, for example one beside each task of the application: by default they elect a leader through a lock in your database, only the leader sends, and the others take over when it goes. In production:
- Give the relay a health check:
fcdev outbox healthexits 0 when the relay is healthy and 1 when not (the relay servesGET /healthon--health-addr, default127.0.0.1:9180). Two relays on one machine need different--health-addrvalues, because a port that is taken is a start-up error. - When your own migrations create
outbox_messages, start the relay with--init-schema=falseso it waits for your table instead of creating it first. --max-request-bytescaps a request body (default 8 MiB).ghcr.io/flowcatalyst/fcdevis an image holding thefcdevbinary alone, built for runningfcdev outboxbeside an application whose own image has none.
Which relay drains which store:
| Your outbox is in | Relay |
|---|---|
| Your application’s PostgreSQL | fcdev outbox |
| Your application’s MySQL 8.0+ or MariaDB 10.6+ | fcdev outbox (a mysql:// or mariadb:// URL, or a Go MySQL DSN, naming the database) |
| MongoDB | the fc-server outbox subsystem (FC_OUTBOX_BACKEND=mongo) |
| SQLite | the fc-server outbox subsystem (FC_OUTBOX_BACKEND=sqlite, FC_OUTBOX_SQLITE_PATH) |
With MySQL, every relay must reach the same server (the primary), and the SDK’s MySQL migration creates the table.
5. Check it worked
Section titled “5. Check it worked”- The row disappears from
outbox_messagesonce the platform accepted it. - The event appears in the console under Events, and each matching subscription’s job under Dispatch jobs.
When a row stays:
outbox_messages shows |
Meaning | Do |
|---|---|---|
Status back to pending, a retryable error, rising retry_count |
The platform was unreachable or answered 5xx or 401. The relay retries forever with backoff, so nothing is lost. |
Fix connectivity or credentials; it drains by itself. |
error_message starting [blocking] |
The platform refused the row (400 or 403): a bad type, a client the credential cannot reach. Later rows of its message group wait behind it. |
Fix the cause, then retry or skip the row (below). |
Unblocking a group. The fc-server outbox subsystem serves operator endpoints for this
(POST /outbox/groups/{group}/unblock re-queues the refused row, .../skip leaves it failed and
lets the group move on) on FC_OUTBOX_ADMIN_PORT. fcdev outbox has no such endpoint, and it rebuilds
blocks from the [blocking] marker when it starts, so a restart alone changes nothing. With
fcdev outbox, stop it, then in your database either correct the row and re-queue it
(UPDATE outbox_messages SET status = 0, retry_count = 0, error_message = NULL WHERE id = '...')
or delete it to give it up, and start the relay again.
Related
Section titled “Related”- The transactional outbox and events.
- The write path: use cases: writing the change, event, jobs and audit row as one operation.
- Receive deliveries and verify signatures.
- SDK pages: Go, Java, TypeScript, PHP, Rust.