Skip to content

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.

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 cases

UseCaseModule 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:

@Override
public 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()));
}

Use cases run against the default database instance only.

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.

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:

@Override
public 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;
}

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.

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();

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);

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.

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.

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.

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 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.

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();
};

One attempt:

  1. validate, then authorize; the first error is the result.
  2. execute (with a load phase: load, then authorizeLoaded, then execute); a rejection is the result.
  3. 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.
  4. Begin a transaction (READ COMMITTED) on the default database.
  5. Apply the plan’s writes in order, then write each event to the outbox, then the dispatch jobs, then one audit row.
  6. 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}.

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(...);

A handler that still gets CONFLICT after the attempts can answer with a deferral so the platform delivers the job again later (see Receivers).

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.

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.

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.

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.

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.

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’s CreateEventDto JSON, status 0, and client_id set. deduplicationId is the event id; clientCode is the ClientId value, which must therefore be the platform’s client code (an identifier such as acme), not the clt_... id (Context). In the platform’s own context (_platform) neither the event nor the audit payload has a clientCode; the client_id column still holds the value. The principal and execution id travel as contextData entries;
  • the audit row has type AUDIT_LOG and the SDK’s CreateAuditLogDto JSON: 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);
}
}

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).

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.

  • code is {application}:...; for an application’s own service account the platform requires the first segment to be one of its applications. targetUrl is an absolute http(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 ClientId as the item’s clientCode, the platform resolves it, and delivers the job with X-FlowCatalyst-Client, so the receiver runs it as that client. No clientCode is written when the context is the platform client (_platform, a scheduled job’s context: the job is platform-scoped) or when platformClientId(...) 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_FOUND for an anchor account, 403 otherwise) 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: externalId never 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:export signs as orders); 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, 0 for the numbers above, blank metadata keys). In Java that is an IllegalArgumentException; in Go NewDispatchJob returns an error.
  • Fields the platform’s batch endpoint does not read (headers, retryStrategy, scheduledFor, expiresAt) are not offered. metadata is sent as the platform’s array of key/value pairs.

The exact row and payload are in the specification.

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.

  • Client scoping is yours to write into the SQL. The runner refuses a cross-client plan, but a query you write that forgets client_id leaks. 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, authorize and execute from scratch; do not do side effects (HTTP calls, emails) inside them.
  • Tests run use cases against a real PostgreSQL; see Testing.