Skip to content

Outbox

The Go SDK writes outbox rows; it does not send them. A relay (fcdev outbox, or the fc-server outbox subsystem) reads outbox_messages and posts each row to the platform. Why the pattern exists, how the relay claims, orders and retries rows, and which relay drains which database are in the transactional outbox. This page is the Go API.

Package Role
outbox Builds rows and payloads, validates dispatch jobs and pushes, holds the INSERT. No I/O.
outboxpgx A pgx Sink for the use-case envelope, plus WriteDispatchJob and WritePush for a transaction you run yourself.
outboxsql A Writer for database/sql (Postgres or MySQL).

Use outboxpgx with usecaseop when you use pgx. Use outboxsql when you use database/sql or MySQL. Use outbox directly only if you write your own driver: its row builders and the shared InsertSQL are the contract.

All rows go in one table. The type column decides which platform endpoint the relay posts a row’s payload to, unchanged.

Row Built by Endpoint Payload members
EVENT outbox.EventRow POST /api/events/batch specVersion, type, source, subject, data, correlationId, causationId, deduplicationId, messageGroup, clientCode, contextData
AUDIT_LOG outbox.AuditRow POST /api/audit-logs/batch entityType, entityId, operation, operationData, principalId, performedAt, source, correlationId, applicationCode, clientCode
DISPATCH_JOB outbox.DispatchJobRow POST /api/dispatch-jobs/batch The batch item (id, kind, code, source, targetUrl, payload, ...)
PUSH outbox.PushRow POST /api/push/batch topic, type, data, clientCode, pushId

Points that are particular to the Go SDK:

  • data and operationData are written as the JSON value itself, never as a string holding encoded JSON. The Java, TypeScript, PHP and Rust SDKs write the encoded string; the platform unwraps both forms at ingest, so the stored result is the same.
  • The event row’s id is the event id, and that id is also the deduplicationId. A relay that sends a batch twice does not create a second event.
  • An event with no source is written without one, and the platform defaults it to {application}:{subdomain} of the event type.
  • contextData carries principalId and executionId when the event has them. The event time is not sent; the platform stamps it at ingest.
  • The audit row requires a principalId, and an application-scoped credential requires applicationCode; the platform refuses the row otherwise. The audit source and correlationId are written for parity but the endpoint ignores them.

outboxpgx.Config and outboxsql.WriterConfig take the same members.

Member Meaning
TableName The outbox table. Default outbox_messages. Must be a plain or schema-qualified identifier.
ClientID Stored in each row’s client_id column. The relay does not read it; it is for your own partitioning.
ClientCode The client’s identifier slug, written as clientCode in event and audit payloads. Empty leaves it out and the platform scopes by the credential: an anchor writes platform-scoped events, a single-client credential writes under its client. A code the credential cannot reach is refused (403, the whole batch). An event implementing outbox.ClientCoded overrides it.
ApplicationCode Written as each audit row’s applicationCode. Required when the relay’s credential is application-scoped.
AuditEnabled (pgx only) Write an AUDIT_LOG row beside every event. Off by default.
Now The clock for created_at and updated_at. Default time.Now.

Dispatch jobs that name no client of their own take ClientCode, except under the value _platform (outbox.PlatformClientCode), where they carry no client.

Inside a use case you do not call the sink; usecaseop.Run does. See Use cases. For a transaction you run yourself, call the sink with your pgx.Tx:

sink := outboxpgx.NewSink(outboxpgx.Config{ClientCode: "acme", ApplicationCode: "orders", AuditEnabled: true})
err = sink.WriteDispatchJob(ctx, tx, job) // tx is a pgx.Tx
err = sink.WritePush(ctx, tx, push)

WriteDispatchJob validates the job and writes the row only. It does not order the row against an event or take a correlation id from anywhere, and the transaction is yours.

outboxpgx.InitSchema(ctx, pool) creates the table if it is absent. Use your own migrations in production; the DDL is outboxpgx.CreateOutboxTableSQL.

w, err := outboxsql.NewWriter(outboxsql.DialectMySQL, outboxsql.WriterConfig{ClientCode: "acme"})
// inside the application's own *sql.Tx:
err = w.WriteEvent(ctx, tx, event) // event is a usecase.DomainEvent
err = w.WriteAudit(ctx, tx, event, command)
err = w.WriteDispatchJob(ctx, tx, job)
err = w.WritePush(ctx, tx, push)

NewWriter fails only on an invalid table name. Dialect picks the placeholder style ($1 or ?) and the DDL (outboxsql.CreateOutboxTableSQLPostgres, CreateOutboxTableSQLMySQL; outboxsql.InitSchema(ctx, db, dialect) runs one). The transaction argument is anything with ExecContext, so a *sql.Tx or a *sql.DB both work; pass a *sql.Tx to get the guarantee. examples/outbox-sql is complete.

CREATE TABLE IF NOT EXISTS 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
);

This is the table of outboxpgx.CreateOutboxTableSQL, which also creates the relay’s partial indexes on pending rows (status = 0) and claimed rows (status = 9) and an index on client_id, status, created_at. The writer inserts status 0 (pending), created_at and updated_at at the write time in UTC, and headers NULL; an empty message group or client id is stored as NULL. outboxsql has a Postgres and a MySQL form of the same table (the MySQL one uses LONGTEXT, DATETIME(3) and JSON).

A dispatch job is one item of POST /api/dispatch-jobs/batch. Build it with outbox.NewDispatchJob(code, targetURL) and the With* methods. Each returns a copy, so a job value is safe to share.

job, err := outbox.NewDispatchJob("ingest:orders:record", "https://api.example.com/records").
WithID(recordID).
WithClientCode("acme").
WithMessageGroup(fileID).
WithSequence(lineNumber).
WithMetadata("source", "sftp").
WithJSONPayload(row) // marshals row; use WithPayload(text, contentType) for other content
Method Sets
WithID The job id and the row id; at most 17 characters of [0-9A-Za-z_-]. Generated (a 13-character TSID) when empty. It is in the payload, so a batch the relay re-sends creates a job with the same id.
WithKind EVENT or TASK. Default TASK.
WithSource, WithSubject Source (default: the code’s application segment) and subject.
WithPayload(text, contentType), WithJSONPayload(v) The body delivered to the target. Default {} as application/json.
DataOnlyEnabled Deliver the payload as the body, with no envelope.
WithExternalID, WithEventID, WithCorrelationID Cross references.
WithClientCode, WithPlatformClientID The client, by identifier slug or platform id. Set at most one.
WithSubscriptionID, WithServiceAccountID, WithDispatchPoolID Delivery routing, by platform id.
WithConnectionID The connection the job is delivered through. Pausing the connection holds the job; with no subscription its service account signs the delivery.
WithMessageGroup, WithMode, WithSequence Ordering. Mode is IMMEDIATE, NEXT_ON_ERROR or BLOCK_ON_ERROR.
WithTimeoutSeconds, WithMaxRetries At least 1 when set. Unset leaves the platform’s defaults (30 seconds, 3 retries).
WithQueue DEFAULT or HIGH_PRIORITY.
WithDescriptor, WithMetadata(key, value) A label, and up to 100 metadata pairs, written as the platform’s [{"key","value"}] array.
WithIdempotencyKey Makes the create idempotent: the first job with a key in its application and client wins; a repeat answers that job’s id and creates nothing. Not blank, at most 100 bytes, kept 7 days.

The builder has no field for delaySeconds or maxAgeSeconds. Those are subscription settings; set them through client.Subscriptions(). It also has no scheduledFor or expiresAt: the platform accepts both on a dispatch job (RFC 3339, UTC), but this SDK does not send them yet. The Laravel SDK does.

The writers validate before they write, so a row the platform would refuse terminally is never stored. job.Validate() applies the rules and returns the first one broken:

  • the code is {application}:{rest}, the application matching [a-z][a-z0-9-]*, at most 255 characters;
  • the target is an absolute http or https URL with a host and no user info;
  • ids (id, eventId, platformClientId, subscriptionId, serviceAccountId, dispatchPoolId, connectionId) match [0-9A-Za-z_-]{1,17};
  • platformClientId and clientCode are not both set; clientCode is 1 to 100 characters;
  • sequence, timeoutSeconds and maxRetries are at least 1 (the platform turns 0 into its default, so 0 cannot be sent);
  • source, message group, external id, subject and descriptor are 1 to 255 characters;
  • mode, kind and queue are known values; metadata has at most 100 entries and no blank key.

An unknown clientCode is refused by the platform for the whole batch: 400 for an anchor, 403 otherwise. A job in a plan is validated before the transaction opens, so nothing is written when one is invalid.

A push is a small signal to browsers, apps and field devices listening on a topic. Write it in the same transaction as the change it announces, so it is sent only if the change commits.

push := outbox.NewPush("orders:customer:cus_42", "order.updated", map[string]any{"orderId": orderID})
err = sink.WritePush(ctx, tx, push) // outboxpgx, a pgx.Tx
err = w.WritePush(ctx, sqlTx, push) // outboxsql
Rule Value
Topic {application}:{segment}(:{segment})*, the first segment [a-z][a-z0-9-]*, the others [0-9A-Za-z_.-]+, at most 255 characters. The writer’s credential must be allowed to push for the application.
Type [a-z][a-z0-9-]*(.[a-z][a-z0-9-]*)*, at most 100 characters. reset, auth-expired, subscribed and anything starting fw. are reserved.
Data A JSON object. 16,384 bytes by default; WithMaxDataBytes(n) raises it to at most 65,536. Set it to the application’s push.max-data-bytes.
Message group The topic by default, so one topic’s pushes reach the gateway in order. WithMessageGroup(g) replaces it. WithUngrouped() writes no group, which lets the relay batch such rows concurrently and keeps no order; use it for signal-only topics.
Client WithClientCode, otherwise the writer’s ClientCode (none under _platform).
Id WithID, up to 26 characters; generated otherwise. The row id is the push id.

A refused push is a *outbox.PushError whose Code is one of 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 Postgres the insert also runs pg_notify on the channel fc_outbox_push in the same statement, so a relay that listens delivers the push as soon as the transaction commits; the poll is the fallback. MySQL has no notification, so the poll interval is the latency.

Push is a separate, opt-in platform service. See push to clients before you rely on it. The Go SDK writes push rows; it does not mint listening tickets or sync topic rules (the Java, TypeScript, PHP and Rust SDKs do).

The rows, the INSERT statement and the dispatch-job rules are pinned against the application framework’s outbox conformance vector by outbox/conformance_test.go. The one deliberate difference is the unencoded data described above.

The writers return a plain error from building a row (before anything is written) or the driver’s error from the INSERT. Inside usecaseop.Run both become usecase.Internal errors with the codes EVENT_WRITE, DISPATCH_JOB_WRITE or AUDIT_WRITE, and the transaction rolls back. See Errors.