Write path
All behaviour that changes data goes through a use case. A use case validates, authorizes, loads, decides and returns a plan; one runner then applies the plan in a single transaction, together with the domain events and an audit row. Application code never begins, commits or rolls back a transaction. The idea is explained, for all of FlowCatalyst, in The write path: use cases; this page is the framework’s version of it.
The running example is orders-demo (examples/orders-demo for Java, go/examples/orders-demo for
Go): an Order with OrderLines and three use cases, placeOrder, addLine and cancelOrder. The
normative rules are in the write path specification.
The modules
Section titled “The modules”App.builder() .module(new DatabaseModule()) .module(new OutboxModule()) // the outbox table and OutboxWriter .module(new UseCaseModule()) // provides Events and UseCases .module(new OrdersModule()); // yours: migrations and use casesUseCaseModule provides UseCases (the runner, on the default database instance) and Events
(makes event metadata). OutboxModule provides OutboxWriter and contributes the outbox_messages
migration under module id outbox. Your module contributes its own migrations and provides its use
cases:
@Overridepublic void register(AppBuilder app) { MigrationSet.contribute(app, OrdersModule.class, "db/migration/orders"); app.provide( OrderUseCases.class, lookup -> new OrderUseCases( new OrderRepository(), lookup.get(Databases.class).defaultInstance(), lookup.get(Events.class), lookup.get(Ids.class), OrderUseCases.Policies.defaults()));}d := Declared{db: database.Declare(app), outbox: usecase.Declare(app)}// ...runner, err := usecase.NewRunner(b, d.outbox, db)svc, err := orders.NewService(runner, b.Ids(), event.NewFactory(b.Clock(), b.Ids()))usecase.Declare(app) declares the outbox module (id outbox) and contributes its migration set: the
FlowCatalyst SDK’s outbox_messages table byte for byte, then a migration widening client_id.
NewRunner takes the returned *Declared as proof that the migrations are part of the application.
event.NewFactory(clock, ids) makes event metadata. The packages are usecase, event and id.
Use cases run against the default database instance only.
1. Aggregates
Section titled “1. Aggregates”An aggregate holds what its rules need to decide. Methods that change it return a new value and write nothing. Child collections belong to the aggregate: they are saved with it and covered by its version.
An aggregate is a record implementing Aggregate: id() (a typed id), client() (the ClientId it
belongs to) and version() (a long; 0 for an aggregate not yet stored).
public record OrderId(String value) implements AggregateId {}
public record Order( OrderId id, ClientId client, long version, String customer, OrderStatus status, List<OrderLine> lines) implements Aggregate {
public static Order place(OrderId id, ClientId client, String customer) { return new Order(id, client, 0, customer, OrderStatus.OPEN, List.of()); }
public Order withLine(OrderLine line) { ... } // returns a new Order public Order cancel() { ... }}Ids are typed records, usually a prefix and a TSID: new OrderId(ids.generate("ord")) gives ord_
plus 13 time-ordered characters, monotonic within the application.
The aggregate knows nothing of storage. It names itself for the audit row (AuditEntity(), which
returns a usecase.Entity). The runner wraps it in one of two types that carry what storage needs:
usecase.NewFresh(cx, a)is a new aggregate for the Context’s client, written byusecase.Insertat version 1.usecase.LoadedFrom(client, version, a)is what a repository’sFindreturns, written byusecase.Updateorusecase.Deletewhere id, client and version still match.
A loaded aggregate cannot be inserted and a new one cannot be updated: they are different types.
Ids are generic: id.ID[K] for a marker type K, so id.ID[OrderKind] and id.ID[LineKind] are
different types.
// OrderID is an order's id, ord_ and a TSID.type OrderID = id.ID[OrderKind]id.New[K](ids) and id.Parse[K] make and read them. They marshal as text, bind and scan through
driver.Valuer and sql.Scanner, and the zero id is never stored.
2. Repositories
Section titled “2. Repositories”You write the repository, with explicit SQL (or checked SQL). It reads outside the transaction and writes inside the attempt’s transaction.
It implements Repository<I, A>:
| Method | Runs in | Contract |
|---|---|---|
Optional<A> find(Database db, ClientId client, I id) |
no transaction | filters by client_id; returns the aggregate with the stored version |
void insert(Tx tx, A a) |
the attempt’s transaction | stores a with version 1 |
int update(Tx tx, A a) |
the attempt’s transaction | UPDATE ... SET version = <a.version() + 1> ... WHERE id = ? AND client_id = ? AND version = <a.version()>, then writes children; returns the root update’s row count |
int delete(Tx tx, A a) |
the attempt’s transaction | DELETE ... WHERE id = ? AND client_id = ? AND version = ?; returns the row count |
tx.connection() gives the java.sql.Connection to write on. The runner calls insert when
version() == 0 and update otherwise:
@Overridepublic int update(Tx tx, Order order) throws SQLException { Connection c = tx.connection(); int rows = OrderSql.updateOrder( c, order.version() + 1, order.customer(), order.status(), order.id(), order.client(), order.version()); if (rows == 1) { OrderSql.deleteLines(c, order.id()); writeLines(c, order); } return rows;}It implements usecase.Repository[A, I]:
type Repository[A any, I comparable] interface { Find(ctx context.Context, db *database.DB, client fw.ClientID, id I) (Loaded[A], bool, error) Insert(ctx context.Context, tx *database.Tx, client fw.ClientID, a A) error Update(ctx context.Context, tx *database.Tx, client fw.ClientID, a A, v VersionCheck) (int64, error) Delete(ctx context.Context, tx *database.Tx, client fw.ClientID, a A, v VersionCheck) (int64, error)}Find filters by client and returns the stored version. Insert stores version 1. Update and
Delete match id, client and version (VersionCheck{Expected, Next}, which the runner computes) and
return the root row’s row count. The demo’s repository runs sqlc’s generated queries.
usecasetest.Repository checks that an implementation keeps the contract (stale writes affect no row,
Find filters by client).
Optimistic locking
Section titled “Optimistic locking”A row count of 0 from update or delete means the aggregate is stale: someone else committed
a change since it was loaded. The version is on the root row; because the lines are rewritten together
with it, adding a line bumps the order’s version, so a concurrent edit of the header conflicts. A count
above 1 is a bug and fails the attempt as INTERNAL.
You need a version BIGINT NOT NULL column and the WHERE ... AND version = ? guard in every update.
The framework cannot add them for you.
3. Use cases
Section titled “3. Use cases”A use case is defined once and run many times. It has a name matching [a-z][a-z0-9-]*, which appears
in logs, metrics and the audit row.
UseCase.named(name, CommandType.class, EventClass.class) starts a builder (abridged from
OrderUseCases):
UseCase.named("add-line", AddLine.class, OrderLineAdded.class) .validate( (context, command) -> command.quantity() <= 0 ? Optional.of(UseCaseError.validation("QUANTITY_INVALID", "The quantity must be positive.")) : Optional.empty()) .authorize(PRINCIPAL_REQUIRED) .conflict(ConflictPolicy.retry(3, Duration.ofMillis(25))) .execute( (context, command) -> { Optional<Order> found = repository.find(database, context.client(), new OrderId(command.orderId())); if (found.isEmpty()) { return Decision.reject(UseCaseError.notFound("ORDER_NOT_FOUND", "There is no such order.")); } Order updated = found.get().withLine(newLine); return Plan.save(updated, repository, new OrderLineAdded(...)); });| Part | Required | Contract |
|---|---|---|
| name | yes | [a-z][a-z0-9-]* |
validate(Check) |
no | checks the command’s shape without loading data; returns Optional<UseCaseError> |
authorize(Check) |
yes | resource-level access check, same shape. Authorize.PUBLIC declares an operation deliberately open. Calling execute(...) without one throws IllegalStateException when the use case is defined |
conflict(ConflictPolicy) |
no | ConflictPolicy.fail() (the default) or ConflictPolicy.retry(maxAttempts, backoff) |
load(Load, whenMissing), authorizeLoaded(LoadedCheck) |
no | a use case on one stored record (below) |
execute(Execute) |
yes | loads what it needs (once), applies the rules, returns a Decision |
A Check<C> is Optional<UseCaseError> check(Context context, C command) throws Exception. Each phase
receives the Context and the command. The authorize step in the example is a Check<Object> shared
by all three use cases:
private static final Check<Object> PRINCIPAL_REQUIRED = (context, command) -> context.principal() == null ? Optional.of(UseCaseError.authorization("PRINCIPAL_REQUIRED", "Sign in to change orders.")) : Optional.empty();A use case is an interface, usecase.UseCase[C, E], with four methods: Name, Validate,
Authorize and Execute. A use case without Authorize does not compile where it is defined
(usecase.Define takes a usecase.UseCase[C, E]; a test proves it with a type check of
testdata/noauth).
type UseCase[C any, E event.Event] interface { Name() Name Validate(ctx context.Context, cx fw.Context, cmd C) error Authorize(ctx context.Context, cx fw.Context, cmd Valid[C]) (Grant, error) Execute(ctx context.Context, cx fw.Context, cmd Authorized[C], db *database.DB) (*Plan[E], error)}Authorize returns a usecase.Grant: usecase.Public() for a deliberately open operation,
usecase.Require(cx, permission) against the Context’s permissions, or an error. Execute receives a
usecase.Authorized[C], which only the runner makes (a.Command() gives the command):
// AddLineUseCase adds a line to an open order.type AddLineUseCase struct { Orders Store Ids *fw.Ids Events *event.Factory}
// Execute loads the order once; only an open order takes a line.func (u AddLineUseCase) Execute(ctx context.Context, cx fw.Context, a usecase.Authorized[AddLine], db *database.DB) (*usecase.Plan[OrderLineAdded], error) { cmd := a.Command() loaded, found, err := u.Orders.Find(ctx, db, cx.Client(), cmd.Order) if err != nil { return nil, err } if !found { return nil, usecase.NotFound(OrderNotFound, "There is no such order.") } // ... return usecase.NewPlan(ev, usecase.Update(loaded.With(open), u.Orders)), nil}usecase.Define(runner, uc, opts...) registers it, with usecase.WithConflictPolicy(p) to choose the
conflict policy. Run(ctx, cx, cmd) returns (Committed[E], error); the error is always a
*usecase.Error (below). Return usecase.NoChange[E]() or usecase.NoChangeBecause[E](reason)
from Execute for an idempotent no-op — Committed.Changed() returns false,
Committed.NoChangeReason() returns the reason, no write transaction is opened, and metrics record
outcome="no_change". The no-change outcome is
not released yet.
Load once. execute finds each aggregate once; if it needs fresher state the attempt has failed
and runs again from the start.
There is no built-in permission model: authorize is your own check of the Context (its principal
and permissions, see Context). Two checks ship with the framework:
- Public declares an operation open to anyone.
- Service grants only a service principal (the receivers’ contexts, a scheduled job, or a context
you make for an inbound webhook you verified yourself) and refuses everyone else with
AUTHORIZATION/SERVICE_REQUIRED. A service principal carries no permissions, so a permission check cannot say this.
Authorize.PUBLIC and Authorize.SERVICE. Inside your own check, Authorize.requireService(context)
returns the same Optional<UseCaseError>:
UseCase.named("record-delivery", RecordDelivery.class, DeliveryRecorded.class) .authorize(Authorize.SERVICE) // a courier's webhook, never a person .execute(...);
// in the webhook handler, after checking the provider's signature:Context ctx = Context.ofService(new ClientId("acme"), new PrincipalId("svc:courier-webhook"));useCases.run(recordDelivery, ctx, command);usecase.Public() and usecase.RequireService(cx), returned from Authorize. A service principal has
kind fw.PrincipalService; fw.ServiceContextFor(client, principal) makes the context for a provider
webhook. The tests show a user, a field worker, a principal of no kind and a user holding every
permission all being refused.
A rule that needs the record: load and authorizeLoaded
Section titled “A rule that needs the record: load and authorizeLoaded”authorize is permission-level: it sees the command and the context, not the stored record. A rule
that depends on the record belongs after the load. Declare the load, and the record-level check next to
the other access checks.
The order is validate, authorize, load, authorizeLoaded, execute. A missing record is the error
you gave the load and nothing after it runs. A refusal from the record-level check is the result and
execute does not run. A retry after a conflict loads and checks again. Answer with the not-found
error from the record-level check when the rule must not reveal that the record exists. A failing load
is INTERNAL / LOAD; a failing check is INTERNAL / AUTHORIZE.
UseCase.named("add-comment", AddComment.class, TicketCommented.class) .validate(...) .authorize(requires(Permissions.COMMENT)) .conflict(policy) .load((context, command) -> load(context, command.ticketId()), TICKET_NOT_FOUND) .authorizeLoaded( (context, command, ticket) -> context.hasPermission(Permissions.WORK) || requester(context).equals(ticket.requesterId()) ? Optional.empty() : Optional.of(UseCaseError.authorization("NOT_YOUR_TICKET", "You may comment only on tickets you opened."))) .execute((context, command, ticket) -> ...);authorizeLoaded is optional (a load with no record-level rule is fine); authorize is still
required.
usecase.LoadedUseCase[C, E, L] is a second interface, registered with usecase.DefineLoaded; plain
use cases are unchanged. It has Name, Validate and Authorize as before, then:
Load(ctx, cx, cmd, db) (record L, found bool, err error)WhenMissing() *usecase.ErrorAuthorizeLoaded(ctx, cx, cmd, record L) errorExecute(ctx, cx, cmd, record L, db)
The record-level check is part of the type, so a use case that forgets it, or declares it with a
drifted signature, does not compile; the runner never skips it. A use case with no record-level rule
says so by embedding usecase.NoRecordCheck[C, L], which permits every record. (Java makes
authorizeLoaded an optional builder call; Go makes the same choice explicit.) Find filters by
client, so another client’s record is missing.
Plans and no-change outcomes
Section titled “Plans and no-change outcomes”execute returns a rejection (nothing is written), a no-change outcome (idempotent no-op:
valid and authorized, nothing written, no events or audit rows emitted, recorded under
outcome="no_change" rather than business_rule), or a plan: the writes to make and the
events to publish. Every plan carries at least one event; the first is the use case’s result.
Events are written in step order.
Decision.reject(UseCaseError) is a Rejected. Decision.noChange() (or
Decision.noChange(reason)) returns UseCaseResult.Unchanged without opening a write transaction
or polluting business_rule failure metrics. Otherwise return a Plan:
Plan.save(aggregate, repository, event): insert (version 0) or update.Plan.delete(aggregate, repository, event).Plan.emit(event): an event with no aggregate write..andSave(...),.andDelete(...),.andEmit(event)add further steps..andDispatch(DispatchJob)adds a dispatch job..andAppend(row, appender)adds an append-only row..andPush(Push.of(topic, type, data))adds a push to clients.
Plan.save is generic in the aggregate type, so the repository must match it.
Return (*Plan[E], error); a non-nil error that is a *usecase.Error is the rejection.
usecase.NewPlan(firstEvent, steps...): the first event is the result.- Steps:
usecase.Insert(fresh, repo),usecase.Update(loaded, repo),usecase.Delete(loaded, repo),usecase.Append(row, appender),usecase.Push(topic, type, data, opts...). plan.Emit(event)adds a further event;plan.Dispatch(job)adds a dispatch job.
A push is a row of fw_push_outbox for the context’s client, written in the same transaction right
after the steps added so far, and sent only if the transaction commits. It is not an event (not
audited, never the result). An invalid push, or data over push.max-data-bytes, fails the run as
INTERNAL / INVALID_PUSH; a failure writing it is INTERNAL / PUSH. See Push to
clients.
Append-only rows
Section titled “Append-only rows”Some rows are only ever inserted: an activity log line, a live-update record, a projection row. They are not aggregates (nobody loads, changes or deletes them), so they need no version, produce no event and must not become the audit row’s subject. Write them with an appender, a function that does the application’s INSERT, and add them to the plan.
An Appender<R> is void append(Tx tx, R row) throws SQLException:
static final Appender<LogLine> LOG = (tx, line) -> { try (var st = tx.connection().prepareStatement("INSERT INTO thing_log (thing_id, note, things_then) SELECT ?, ?, count(*) FROM thing")) { st.setString(1, line.thingId()); st.setString(2, line.note()); st.executeUpdate(); } };
return Plan.save(a, repo, eventFor(c, THING_CREATED, a)) .andAppend(new LogLine(a.id().value(), cmd.name() + "-a"), LOG) .andSave(b, repo, eventFor(c, THING_CREATED, b)) .andAppend(new LogLine(b.id().value(), cmd.name() + "-b"), LOG);A plan still needs at least one step, the use case’s result event: appends alone are not a plan
(new Plan<>(...) with appends and no step throws IllegalArgumentException, and andAppend is only
offered on a plan that already has a step). A throwing appender fails the attempt like a repository:
UNIQUE_VIOLATION for a unique constraint, otherwise INTERNAL / PERSIST.
An Appender[R] has Append(ctx, tx *database.Tx, row R) error:
// journal appends entries; with fail set it fails.type journal struct{ fail error }
func (j journal) Append(ctx context.Context, tx *database.Tx, e entry) error { /* INSERT */ }
return usecase.NewPlan(e.created(cx, t1), usecase.Append(entry{client: cx.Client(), thing: t1.id, note: "before"}, journal{}), // first in the plan, yet not the audit subject usecase.Insert(usecase.NewFresh(cx, t1), thingRepo{}), usecase.Append(entry{client: cx.Client(), thing: t1.id, note: "after"}, journal{}),), nilThe row carries everything it stores, its client included: take it from the Context when the plan is
built, because the runner’s client check covers aggregates only. A plan of appends and no aggregate
step is refused as INTERNAL / APPEND_ONLY_PLAN (logged as a bug): appends belong to an aggregate
change.
- An append is written in plan order: right after the steps added before it (so it may refer to an aggregate the plan just inserted) and before the steps added after it, in the attempt’s transaction. A failed attempt rolls it back with everything else; a retried one writes it again.
- It is never version-checked and never the audit row’s subject: the audit row still names the plan’s first aggregate, wherever the appends are.
Append or aggregate? If the application ever updates or deletes the row, or a rule reads it to decide, it is an aggregate (with a version). If it is written once and only read by screens, reports or other services, append it. Do not fake an append-only row as an insert-only aggregate: it would need a version column, and placing it first would make it the audit row’s subject.
4. Running a use case
Section titled “4. Running a use case”UseCaseResult<OrderEvents.OrderPlaced> placed = useCases.run(orders.placeOrder(), context, new PlaceOrder("Ada Lovelace"));UseCaseResult<E> is sealed: Committed(E event) or Failed(UseCaseError error). It never throws for
an expected outcome.
return switch (result) { case UseCaseResult.Committed<?> ok -> "committed " + ok.event().metadata().type(); case UseCaseResult.Failed<?> failed -> failed.error().kind() + " " + failed.error().code();};committed, err := placeOrder.Run(ctx, cx, PlaceOrder{Customer: "Ada Lovelace"})if ue, ok := usecase.AsError(err); ok { // ue.Kind(), ue.Code(), ue.Message(), ue.Details(), ue.Status()}ev := committed.Event()Run returns (Committed[E], error); the error is always a *usecase.Error.
One attempt:
validate, thenauthorize; the first error is the result.execute(with a load phase:load, thenauthorizeLoaded, thenexecute); a rejection is the result.- Every aggregate in the plan must belong to the context’s client. A mismatch fails as
INTERNAL/CROSS_CLIENT_WRITE, is logged as a bug, and writes nothing. - Begin a transaction (READ COMMITTED) on the default database.
- Apply the plan’s writes in order, then write each event to the outbox, then the dispatch jobs, then one audit row.
- Commit.
| Failure | Result |
|---|---|
| stale aggregate (row count 0) | conflict: the use case’s policy applies |
SQLSTATE 40001 or 40P01 (serialization failure, deadlock) |
conflict: the policy applies |
SQLSTATE 23505 (unique violation) |
CONFLICT / UNIQUE_VIOLATION, constraint name in the details, not retried |
| any other exception from a phase, repository or the database (Go: or a panic in a phase) | INTERNAL; the code names the step (VALIDATE, AUTHORIZE, LOAD, EXECUTE, BEGIN, PERSIST, OUTBOX, AUDIT, COMMIT); the cause is logged, never put in the message |
| interrupted (Go: the context ends) while waiting between attempts | INTERNAL / INTERRUPTED |
Every failed attempt rolls back fully: a failing line insert rolls back the order header and the
outbox rows too. The Go runner reports fw_usecase_runs_total{usecase,outcome} and
fw_usecase_duration_seconds{usecase}.
Conflict policy
Section titled “Conflict policy”fail() returns CONFLICT / STALE_AGGREGATE. retry(n, backoff) runs the whole use case again
from step 1, up to n attempts in total (2 to 10, anything else is refused), waiting backoff
randomised between half and one and a half times its value; when attempts run out the result is
CONFLICT / STALE_AGGREGATE.
The default is fail(). A use case that does not choose a policy gives up at the first conflict.
That suits a person editing a form: they get 409 STALE_AGGREGATE, reload and decide again. It rarely
suits a use case that a receiver (a dispatch or scheduled-job handler) or a process step runs:
nobody is there to reload, and a concurrent request or another delivery touching the same aggregate
fails the attempt where running it again on fresh state would have succeeded. Those use cases usually
want retry; opt in where you define them. A test that runs two of them at once (two deliveries
claiming one order) is what finds a missing opt-in.
UseCase.named("add-line", AddLine.class, OrderLineAdded.class) .validate(...) .authorize(PRINCIPAL_REQUIRED) .conflict(ConflictPolicy.retry(3, Duration.ofMillis(25))) // without this line: ConflictPolicy.fail() .execute(...);retry, err := usecase.Retry(3, 25*time.Millisecond)if err != nil { return err}def, err := usecase.Define(runner, AddLineUseCase{...}, usecase.WithConflictPolicy(retry))usecase.Fail() is the default. Every attempt reloads, so the retry sees the other writer’s change.
A handler that still gets CONFLICT after the attempts can answer with a deferral so the platform
delivers the job again later (see Receivers).
Errors
Section titled “Errors”An error has a kind, a code (UPPER_SNAKE), a message (safe to show a caller) and details (a
string map). Build them with validation, authorization, notFound, conflict, businessRule
(each takes a code and a message) and internal(code).
| Kind | HTTP status |
|---|---|
VALIDATION |
400 |
AUTHORIZATION |
403 |
NOT_FOUND |
404 |
CONFLICT |
409 |
BUSINESS_RULE |
409 |
INTERNAL |
500 |
In Java the builders are UseCaseError.validation(...) and so on, and ErrorKind.httpStatus() gives the
status. In Go they are usecase.Validation(...), usecase.NotFound(...) and so on, codes are
usecase.ErrorCode values (ParseErrorCode, MustErrorCode), (*Error).WithDetails adds details and
Status() gives the status. Java’s UseCaseError implements core’s ServiceError, so
HttpErrors.of(error) turns one into the error response (HTTP) without the HTTP
module depending on the write path.
Inside another transaction
Section titled “Inside another transaction”Work that owns the transaction (a receiver’s idempotency step) can run a use case in it, so the delivery’s record, the use case’s writes, its events and its audit row commit together or not at all.
OnceResult<UseCaseResult<InvoiceSent>> once = d.once(db, "send-invoice", connection -> useCases.run(sendInvoice, context, new SendInvoice("42"), Tx.of(connection)));run(useCase, context, command, Tx) writes the plan, the events and the audit row on that connection
under a savepoint and never commits. A failed or conflicting attempt rolls back to the savepoint only,
so the caller’s earlier work survives; the conflict policy retries on the same transaction (assuming
READ COMMITTED, which once uses). The connection must be in a transaction, else
IllegalArgumentException.
Defined.RunJoined(ctx, cx, cmd, tx) runs the same attempts on a *database.Tx the caller owns, for
example the one flowcatalyst.Once hands to its work. Each attempt runs under a savepoint; a stale
aggregate, a serialization failure, a deadlock, a unique violation or any failed step rolls back to
the savepoint, so the caller’s earlier work survives and the transaction stays usable. The runner
never commits or rolls back the caller’s transaction: Committed means “applied in your transaction”.
It is a method of the defined use case, not of the runner, because Go has no generic methods.
usecasetest.Begin plays the caller in tests.
What still does not compose: reads through a repository’s find use their own connections and do not
see the caller’s uncommitted writes; and an HTTP call, an email or a message is in no transaction at
all (a rolled-back transaction does not unsend it). Make those calls idempotent, using the dispatch job
id as the key.
5. Events
Section titled “5. Events”A domain event carries metadata and its own data fields. The type is four segments,
application:domain:aggregate:action, each matching [a-z][a-z0-9-]*.
A domain event is a record implementing DomainEvent, with EventMetadata metadata() first:
public static final EventType PLACED = new EventType("orders", "sales", "order", "placed");
public record OrderPlaced(EventMetadata metadata, String orderId, String customer) implements DomainEvent {}events.metadata(context, OrderEvents.PLACED, order.id()) (an Events, provided by UseCaseModule)
fills in the metadata. The event’s data payload is the record’s own fields as JSON (Jackson 3;
records only), without metadata. Keep event records plain: strings, numbers, nested records, lists.
An event is a struct with its data as json-tagged fields (the Java record’s component names) and its
event.Metadata in a field tagged json:"-" (marshalling metadata fails, so a missing tag is found at
once):
var Placed = event.MustType("orders:sales:order:placed")
// OrderLineAdded is the result of add-line.type OrderLineAdded struct { Meta event.Metadata `json:"-"` OrderID domain.OrderID `json:"orderId"` LineID domain.LineID `json:"lineId"` SKU string `json:"sku"` Quantity int32 `json:"quantity"` UnitPriceCents int64 `json:"unitPriceCents"` LineCount int `json:"lineCount"`}
func (e OrderLineAdded) Metadata() event.Metadata { return e.Meta }event.Factory.Metadata(cx, type, subjectID) fills the metadata. JSON is encoding/json/v2 with
options that make it write what Jackson writes (times as Java’s Instant.toString, floats as Java’s
Double.toString, upper-case \u escapes). Use pointers with omitzero for optional data (Jackson’s
NON_NULL); a nil slice is written [].
The factory fills in:
| Field | Value |
|---|---|
| event id | a TSID |
| spec version | 1.0 |
| type | orders:sales:order:placed (application:domain:aggregate:action) |
| source | orders:sales |
| subject | sales.order.<id> (domain.aggregate.id) |
| time | from the injected clock |
| correlation id, principal id | from the Context |
| causation id, execution id | from the Context when present |
| message group | sales:order:<id> (domain:aggregate:id), so one aggregate’s events stay in order. withMessageGroup(group) changes it |
The event type must also exist on the platform for it to be delivered. The framework’s definition sync can declare it.
6. The outbox
Section titled “6. The outbox”Events and audit rows are written to outbox_messages in the same transaction as the aggregate.
The table and the payloads are those of the FlowCatalyst SDKs, so the platform’s outbox processor reads
them unchanged (see The transactional outbox):
- an event row has type
EVENT, the event’s message group, the SDK’sCreateEventDtoJSON, status0, andclient_idset.deduplicationIdis the event id;clientCodeis theClientIdvalue, which must therefore be the platform’s client code (an identifier such asacme), not theclt_...id (Context). In the platform’s own context (_platform) neither the event nor the audit payload has aclientCode; theclient_idcolumn still holds the value. The principal and execution id travel ascontextDataentries; - the audit row has type
AUDIT_LOGand the SDK’sCreateAuditLogDtoJSON: entity type and id from the first aggregate (or the event subject),operation= the use case name, the principal, time, correlation id and client; - a command’s data goes into the audit row only if the command opts in. Otherwise just the fact of the operation is recorded. Take care not to put secrets in it.
The command implements AuditData (Map<String, Object> auditData()):
public record PlaceOrder(String customer) implements AuditData { @Override public Map<String, Object> auditData() { return Map.of("customer", customer); }}The command implements usecase.AuditData, returning ordered fields (usecase.Field("customer", ...)):
Java’s LinkedHashMap order, which a Go map cannot keep. The outbox rows (EVENT, DISPATCH_JOB,
AUDIT_LOG) are written with the shared conformance/sql/outbox/insert.sql and equal
conformance/outbox/outbox.json byte for byte, payload text included.
An application that already ran the SDK’s outbox migration by other means has the table and must not
also list the framework’s outbox migration. The first migration file’s content (and checksum) is the
SDK’s, and a second migration widens client_id to VARCHAR(100).
Dispatch jobs
Section titled “Dispatch jobs”A plan can carry dispatch jobs: work the platform delivers to a URL, such as a webhook to another
system. Each becomes an outbox row of type DISPATCH_JOB, written after the events in the same
transaction, and the platform’s outbox processor sends it to /api/dispatch-jobs/batch. See Dispatch
jobs for what the platform does with them.
Plan<ThingEvent> plan = Plan.save(t, repo, new ThingEvent(events.metadata(c, CREATED, t.id()), cmd.id(), t.name(), t.code()));for (DispatchJob job : cmd.jobs()) { plan = plan.andDispatch(job);}return plan;and a job:
DispatchJob.builder("orders:billing:export", TARGET) .payload("<invoice id=\"inv_1\"/>", "application/xml") .messageGroup("invoice:inv_1") .mode(DispatchJob.Mode.BLOCK_ON_ERROR) .maxRetries(5) .metadata("invoice", "inv_1") .queue(DispatchJob.Queue.HIGH_PRIORITY) .build();The payload is payload(text, contentType) or jsonPayload(value) (Jackson, application/json);
kind(EVENT) changes the kind; id(...) sets the job id.
job, err := usecase.NewDispatchJob("test:things:notify", "https://hooks.example.com/n", usecase.JobID("job-1"))if err != nil { return nil, err}plan := usecase.NewPlan(ev, steps...).Dispatch(job)NewDispatchJob(code, targetURL, options...) checks every rule of the specification with the Java
builder’s messages. Options include JobID, KindOf, TextPayload(text, contentType),
JSONPayload(v), DataOnly, MessageGroup, Mode, Sequence, TimeoutSeconds, MaxRetries,
Metadata(key, value), Queue, ExternalID, EventID, SubscriptionID, ServiceAccountID,
DispatchPoolID, PlatformClientID, IdempotencyKey and ConnectionID. Plan.Dispatch writes it
after the events and before the audit row.
codeis{application}:...; for an application’s own service account the platform requires the first segment to be one of its applications.targetUrlis an absolutehttp(s)URL.- Without a payload it is
{}.dataOnly(true)delivers it without the platform’s envelope. - Defaults: kind
TASK, source = the code’s application segment, correlation id = the context’s. Mode, sequence, timeout and retries are left to the platform (NEXT_ON_ERROR, 99, 30 s, 3) unless set; when set they must be at least 1. - A job id is at most 17 characters; otherwise one is generated. The id travels in the payload, so if the processor sends a batch twice the platform gets the same id and a receiver’s once-only step runs the work once (Receivers).
- The context’s client. A job made in a client’s context carries that client: the writer sends the
ClientIdas the item’sclientCode, the platform resolves it, and delivers the job withX-FlowCatalyst-Client, so the receiver runs it as that client. NoclientCodeis written when the context is the platform client (_platform, a scheduled job’s context: the job is platform-scoped) or whenplatformClientId(...)names the platform’s id of the client explicitly, which wins. The code must be a client the platform knows and the application’s service account may write for, as for the events of the same use case; otherwise the platform refuses the whole batch (400 CLIENT_NOT_FOUNDfor an anchor account,403otherwise) and the row stays undelivered. - Idempotency.
idempotencyKey(key)(not blank, at most 100 bytes) makes the create idempotent: the platform keeps a key for 7 days, scoped by the application (the code’s first segment) and the client, and answers a later item with the same key with the first job’s id, creating nothing. It is explicit only:externalIdnever becomes the key, because two jobs that share a reference must not silently merge. - Who signs the delivery.
connectionId(id)names the connection (the platform’s id) the job is delivered through: pausing the connection holds the job, and for a job without a subscription the connection’s service account signs the delivery. Without a connection (and without a subscription) the platform signs with the oldest active service account of the application named by the code’s first segment (orders:billing:exportsigns asorders); a job with a subscription is signed by the subscription’s own account, else its connection’s. The platform refuses the whole batch when the connection does not exist, belongs to another client or application, or is not the named subscription’s connection. - Values the platform would refuse for the whole batch are refused when the job is built (a malformed
code or URL, text over the platform’s column sizes, platform ids over 17 characters,
0for the numbers above, blank metadata keys). In Java that is anIllegalArgumentException; in GoNewDispatchJobreturns an error. - Fields the platform’s batch endpoint does not read (
headers,retryStrategy,scheduledFor,expiresAt) are not offered.metadatais sent as the platform’s array of key/value pairs.
The exact row and payload are in the specification.
7. Reading
Section titled “7. Reading”Screens and lists do not load aggregates. They use plain typed queries on the database, written as
checked SQL. Always filter by client_id.
public static List<Summary> summaries(Database db, ClientId client) throws SQLException { try (Connection c = db.dataSource().getConnection()) { return OrderSql.summaries(c, client).stream().map(r -> new Summary(...)).toList(); }}For dynamic queries (optional filters, a variable IN list) there is a small JDBC helper in
io.flowcatalyst.framework.usecase.jdbc: Jdbc.query(dataSource, sql, mapper, params...),
Jdbc.queryOne(...), Jdbc.update(...), a Row with typed column getters (string, integer,
longValue, instant, optionalString, optionalInstant, uuid, bytes, decimal, …) and
Jdbc.nullOf(sqlType) for a null parameter.
Parameter types Jdbc can bind. Anything else throws IllegalArgumentException at run time naming
the parameter position and the class (for example parameter 2 has unsupported type java.sql.Timestamp):
| You pass | Bound as |
|---|---|
String |
text |
Integer, Long, Short, Double, Boolean |
the matching SQL type |
BigDecimal |
numeric |
Instant |
timestamptz, as a UTC OffsetDateTime |
UUID |
uuid |
byte[] |
bytea |
any Enum |
its name() as text |
AggregateId, ClientId, PrincipalId, CorrelationId |
their value() as text |
Jdbc.nullOf(Types.X) |
a typed SQL NULL |
Rejected: a bare null (a NullPointerException; write Jdbc.nullOf(Types.VARCHAR)),
float/Float, byte/Byte, char, and every date and time type except Instant
(java.sql.Timestamp, java.sql.Date, java.util.Date, LocalDateTime, LocalDate,
OffsetDateTime, ZonedDateTime). The helper has exactly one way to say “a moment in time”: the other
types either carry no zone or the JVM’s default one, so the helper does not guess. Convert instead:
timestamp.toInstant(), localDateTime.toInstant(ZoneOffset.UTC) (choose the zone yourself),
offsetDateTime.toInstant(). A LocalDate is passed as its ISO text with an explicit cast in the SQL
(localDate.toString() bound to ?::date), or the query is written as checked SQL.
Reads go through sqlc-generated queries (or database.DB directly) and the pool. There is no
framework JDBC-style helper to learn: see Checked SQL.
8. What to watch for
Section titled “8. What to watch for”- Client scoping is yours to write into the SQL. The runner refuses a cross-client plan, but a
query you write that forgets
client_idleaks. The repository contract requires it. - Use cases and migrations use the default database instance. You may configure several named instances, each with its own pool, and query another one yourself; only the runner, the outbox and the migrations are tied to the default (Database and Redis).
- Idempotence of retries. A retried use case re-runs
validate,authorizeandexecutefrom scratch; do not do side effects (HTTP calls, emails) inside them. - Tests run use cases against a real PostgreSQL; see Testing.