The transactional outbox
Applications do not call the platform to publish an event. They write the event as a row in an
outbox_messages table in their own database, in the same transaction as the business change.
A separate process, the outbox relay, reads those rows and sends them to the platform. This is
the transactional outbox pattern, and every FlowCatalyst SDK and both application frameworks use it.
The problem it solves
Section titled “The problem it solves”An order service that saves an order and then calls an HTTP API to announce it has two writes that can disagree:
- the order commits, then the process dies before the call: the order exists and nobody hears of it;
- the call succeeds, then the transaction rolls back: the world hears of an order that does not exist.
Retrying the call does not fix either case. Writing the event into the same database transaction does: if the transaction commits, the event row exists and will be sent; if it rolls back, there is no event. The relay can then take its time, retry, and survive restarts, because the row waits in the table until the platform has accepted it.
sequenceDiagram
participant App as Order service
participant DB as App database
participant Relay as Outbox relay
participant FC as Platform
App->>DB: one transaction: save order, insert outbox row
loop every poll
Relay->>DB: claim pending rows
Relay->>FC: POST /api/events/batch
FC-->>Relay: one result per item
Relay->>DB: delete accepted rows
end
The application commits the order and the outbox row together. The relay claims pending rows, posts them, and deletes each one the platform accepted.
What gets written
Section titled “What gets written”One table, outbox_messages, holds three kinds of row:
| Row type | Sent to | Holds |
|---|---|---|
EVENT |
POST /api/events/batch |
An event: type, source, subject, data, correlation and causation ids, deduplication id, message group, client code, context data |
DISPATCH_JOB |
POST /api/dispatch-jobs/batch |
A dispatch job item: code, target URL, payload and options |
AUDIT_LOG |
POST /api/audit-logs/batch |
An audit entry for the change: entity, operation, operation data (redacted), principal |
Each row also carries its message_group (the ordering key), a status (0 pending, 9 claimed),
a retry_count, the last error_message and timestamps. The SDKs ship the table’s migration, and
fcdev outbox creates it on first start if it is missing; both produce the same schema.
Writing to the outbox
Section titled “Writing to the outbox”Each SDK writes the row on the transaction or connection you give it. The samples publish
orders:sales:order:placed together with the order change.
// A use case returns a plan; usecaseop.Run applies it in ONE transaction:// the order row, the EVENT outbox row and the AUDIT_LOG outbox row.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},
// wiring (github.com/flowcatalyst/go-sdk/outboxpgx, usecasepgx, usecaseop)sink := outboxpgx.NewSink(outboxpgx.Config{ClientCode: "acme", ApplicationCode: "orders", AuditEnabled: true})uow := usecasepgx.New(pool, sink)event, err := usecaseop.Run(ctx, uow, PlaceOrder(repo), cmd, usecase.NewExecutionContext(principalID))var driver = new JdbcOutboxDriver(dataSource);var outbox = new OutboxManager(driver, "clt_0HZXEQ5Y8JY5Z");
driver.withTransaction(tx -> { // business writes on (Connection) tx ... outbox.createEvent(CreateEventDto .create("orders:sales:order:placed", Map.of("orderId", orderId)) .withMessageGroup("sales:order:" + orderId), 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, "clt_0HZXEQ5Y8JY5Z");
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}`), 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}") );});use flowcatalyst_sdk::outbox::{CreateEventDto, OutboxManager, PgOutboxDriver};
let driver = PgOutboxDriver::new(pool.clone());let outbox = OutboxManager::new(driver.clone(), "clt_0HZXEQ5Y8JY5Z")?;let event = CreateEventDto::new("orders:sales:order:placed", &order_placed)? .message_group(format!("sales:order:{id}"));
let mut tx = pool.begin().await?;// ... business writes on &mut *tx ...driver.insert_in(&mut tx, &[outbox.prepare_event(&event)?]).await?;tx.commit().await?;Event types and dispatch-job codes must be fully qualified (application:subdomain:aggregate:event);
the SDKs refuse bare codes before writing. The Laravel database driver logs a warning when it writes outside a
DB::transaction; set FLOWCATALYST_OUTBOX_STRICT_TRANSACTIONS=true to make it refuse instead, so
a row cannot be committed on its own by accident.
How the relay sends rows
Section titled “How the relay sends rows”The relay is one process per outbox table. Each poll (every second by default) it:
- Claims up to 100 pending rows (
FC_OUTBOX_BATCH_SIZE) withFOR UPDATE SKIP LOCKED, in the ordermessage_group, created_at, id, and marks them claimed. It then sorts the claim back into the order the rows were written (created_at, thenid; a TSID grows with time). - Sends grouped rows in order. Rows with a message group go to that group’s serial lane and
are sent one at a time, in order. At most 10 groups drain at once by default
(
FC_OUTBOX_MAX_CONCURRENT_GROUPS). - Batches ungrouped rows. Rows without a group carry no order, so all claimed rows of one type go in a single request.
- Reads one result per item, matched by position (see below), and deletes every row the platform accepted.
- Handles failures by status:
INTERNAL_ERROR,UNAUTHORIZEDandGATEWAY_ERROR(including502,503,504, other5xx, timeouts, unreadable answers and network errors) are retryable. The row goes back to pending and is tried again, with no attempt limit: the relay never gives up on a row the platform could not take, so an outage of any length loses nothing. The failing group (or, for ungrouped rows, the type or the single row) is held with a backoff that starts at 1 second and doubles per consecutive failure up to 5 minutes, with some jitter.BAD_REQUESTandFORBIDDENare refusals: the platform will never accept this row as it stands. The row stays in the table with its failure code and its group is blocked (next step).
- Keeps the group in order when a row fails. A held group’s later rows are never sent ahead of
the held row: the relay checks the hold before sending and puts back any later row of the same
group in the claim, and claims skip held, paused and blocked groups so they cannot starve the
rest. A claim also skips a group that still has a row claimed (
IN_PROGRESS) by a relay that died, so a crash does not let the group’s later rows overtake the stranded ones; the group waits for crash recovery (step 8) and then continues from its oldest row. With block-on-error (on by default,FC_OUTBOX_BLOCK_ON_ERROR) a refused row blocks its group until an operator unblocks it (the row is re-queued) or skips it. The refusal is stored with a[blocking]marker at the start of itserror_message, and the relay rebuilds its blocked groups from those rows when it starts or becomes leader, so a restart never moves a group past a refused row. - Honours back-pressure. A
429is not a failure. The relay holds that message group (or, for ungrouped rows, that row type) for theRetry-Aftertime (1 second to 5 minutes, 5 seconds when absent) and puts the rows back without counting it as a failure. Every later row of a held group in the same claim is put back too, so nothing overtakes the held row. - Recovers rows left claimed by a relay that died: every minute, rows claimed more than 5 minutes ago go back to pending.
Upgrading from an older relay
Section titled “Upgrading from an older relay”Older versions gave up on a row after 3 attempts and left it failed, and did not remember blocks across a restart. On start (and on becoming leader) the relay:
- returns rows an older version left in a retryable failure status to pending, and logs how many;
- marks refusals from older versions
[skipped before upgrade]: their groups had already moved on, so these rows do not block anything. They stay in the table for inspection.
MaxRetries (the old attempt limit) is deprecated and ignored.
The positional batch API
Section titled “The positional batch API”All three batch endpoints answer {"results": [...]} with exactly one result per submitted item,
in submission order. Each result has the platform resource id, a status and, on failure, an error:
| Status | Meaning for the relay |
|---|---|
SUCCESS |
Stored (or recognised as a duplicate). Delete the row. |
SKIPPED |
The platform did not store this item (for example an audit row whose application cannot be resolved). The relay treats it as a refusal: the row is kept with status 2 and a message starting SKIPPED: the platform did not store this item, and is not retried. It is never deleted as delivered. |
BAD_REQUEST |
This item is invalid. A refusal: the row is kept and blocks its group. |
INTERNAL_ERROR, UNAUTHORIZED, GATEWAY_ERROR |
Retryable: the row stays and is retried with backoff, forever. |
FORBIDDEN |
A refusal, like BAD_REQUEST: the row is kept and blocks its group. |
The result’s id is the platform’s id for the event, job or audit entry, which is not always the
outbox row id, so results are matched by position, never by id. A response with the wrong
number of results fails the whole batch as retryable (it is retried with backoff) rather than risk pairing outcomes with the
wrong rows.
Why one result per item. A batch of 100 events with one bad item should store 99 events and
report one problem, not reject 100. Per-item results let the relay delete what was accepted, retry
what can be retried, and keep only the bad row back. Some refusals still apply to the whole request:
a client the caller cannot reach (403), or more items than the endpoint takes (1,000 events or
dispatch jobs, 100 audit entries).
Idempotency
Section titled “Idempotency”The relay is at-least-once: if the platform stores a batch but the answer is lost, the relay sends it again.
- Events are deduplicated on
deduplicationId: a resent event whose key is already stored is reported asSUCCESSwithout a second copy. Every SDK (Go, Java, TypeScript, PHP and Rust) sets the key to the outbox row id by default, so a resent row is never a second event. Set your own (withDeduplicationId,deduplication_id) when the key should be a business identifier. - Dispatch jobs are not deduplicated by their id. Give a job an
idempotencyKey(at most 100 characters) when a repeat would matter: a later job with the same key, in the same application and client, creates nothing and answers the first job’s id. Keys are kept for 7 days.
Which relay drains which database
Section titled “Which relay drains which database”| Your outbox lives in | Relay |
|---|---|
| The application’s own PostgreSQL, or MySQL 8.0+ / MariaDB 10.6+ | fcdev outbox, run beside the application, in development and in production. It reads FC_OUTBOX_SOURCE_DB_URL (the kind of database is read from the URL; FC_OUTBOX_DB_TYPE=postgres|mysql overrides it), posts to FC_OUTBOX_PLATFORM_URL, and mints its own token with the application’s service-account credentials. |
| The platform’s own PostgreSQL database | The fc-server outbox subsystem (FC_OUTBOX_ENABLED=true, FC_OUTBOX_PLATFORM_URL, a static FC_OUTBOX_PLATFORM_AUTH_TOKEN). It reads the platform’s database pool by default. |
MySQL / MariaDB, MongoDB or SQLite read by fc-server |
The fc-server outbox subsystem with FC_OUTBOX_BACKEND set to mysql (FC_OUTBOX_MYSQL_URL), mongo (FC_OUTBOX_MONGO_URI) or sqlite (FC_OUTBOX_SQLITE_PATH). Any other value is an error at start. |
Any number of fcdev outbox pollers may run against one outbox, for example one per application
task. By default (FC_OUTBOX_LEADER=true, flag --leader) they elect a leader through a lock held
in the source database; only the leader claims and sends, and the others stand by and take over
when it goes. The lock is per outbox table, so outboxes in other schemas or databases elect
separately. On MySQL / MariaDB the election uses a named lock, so every poller must reach the same
server (the primary), and it does not work across the nodes of a Galera or Group Replication
cluster. Set FC_OUTBOX_LEADER=false only when something else guarantees a single poller.
For production, fcdev outbox has these controls:
- Health check. The poller serves
GET /healthonFC_OUTBOX_HEALTH_ADDR(default127.0.0.1:9180), andfcdev outbox healthasks it and exits 0 or 1, so a container can use it as its health check. A leader that stalls forFC_OUTBOX_STALL_TIMEOUT_MSgives up the leadership and the command exits with status 1. - Schema creation. By default the poller creates
outbox_messagesif it is missing. Pass--init-schema=false(FC_OUTBOX_INIT_SCHEMA=false) when the application’s own migrations create the table: the poller then runs no DDL and waits until the table exists. - Request size.
--max-request-bytes(FC_OUTBOX_MAX_REQUEST_BYTES, default 8 MiB) caps the request body it sends; keep it at or under half of the platform’sFC_INGEST_BATCH_MAX_BYTES. - Image. The release workflow builds
ghcr.io/flowcatalyst/fcdevfor linux/amd64 and linux/arm64: thefcdevbinary alone, for running the poller beside an application whose own image has none (a PHP application, for instance). Check that the image is published and public for your release before you depend on it.
Under fc-server with FC_STANDBY_ENABLED, the outbox subsystem is leader-gated: only one copy
polls.
Read next
Section titled “Read next”- Publish events with the outbox: the how-to, per language.
- Events and event types and dispatch jobs: what the rows become.
- Ordering and message groups: how the relay’s order fits the rest.
- Outbox processor: the relay’s internals and tuning.
- The write path: use cases: how a use case writes event, jobs and audit in one transaction.
- SDK pages: Go, Java, PHP, TypeScript, Rust.
- fcdev CLI and environment variables.
- Decision: transactional outbox on the producer side.