The write path: use cases
Every change to business data in FlowCatalyst goes through a use case: one business operation (“place an order”, “suspend a user”, “create a connection”) written as one unit. The platform’s own operations are written this way, the SDKs give applications the same shape, and both application frameworks build on it.
One operation, four phases
Section titled “One operation, four phases”A use case has named phases, and a runner executes them in a fixed order:
- Validate. Check the command’s shape: required fields, formats, lengths. Nothing is loaded.
- Authorize. Check the caller may do this. This phase is required: an operation that is
deliberately open says so explicitly (
Public,publicAuthorize,Authorize.PUBLIC), and one that leaves it out fails closed. - Execute. Load what the decision needs, apply the business rules, and return either a rejection or a plan: the aggregate to save or delete, the domain event that records what happened, and optionally dispatch jobs or pushes.
- Apply. The runner, not the use case, opens one transaction and writes the plan: the aggregate, then the event, then any dispatch jobs and pushes, then one audit row. Then it commits.
flowchart LR
cmd["Command"] --> v["Validate"]
v -->|ok| a["Authorize"]
a -->|ok| e["Execute"]
e -->|plan| tx
v -->|error| out["Failure result"]
a -->|error| out
e -->|rejected| out
subgraph tx["One transaction (the runner)"]
direction TB
s["Save or delete the aggregate"] --> ev["Write the event"]
ev --> dj["Write dispatch jobs and pushes"]
dj --> au["Write the audit row"]
end
tx --> res["Committed event"]
The result is the committed event, or a typed error whose kind maps to an HTTP status: validation 400, authorization 403, not found 404, conflict and business rule 409, anything unexpected 500.
Why a plan, and why only the runner applies it
Section titled “Why a plan, and why only the runner applies it”The plan is the heart of the pattern. A use case cannot reach the database except by returning one: the plan type is sealed, so only its own constructors can build it, and only the runner consumes it. The consequence holds by construction rather than by discipline:
If a business row was written, its event and its audit row were written too, in the same transaction. If the transaction rolled back, none of them exist.
That matters because the event is how every other system learns of the change. A row saved without its event is a change the rest of the world never hears about; an event sent for a change that rolled back is a lie. Making the event part of the same commit as the row closes both gaps. The audit row rides along for the same reason: the record of who did what can never disagree with what was done.
Separating the decision (execute) from the writing (apply) has two more effects. A use case is easy to test, because its decision is a value you can inspect. And the runner can do the risky parts uniformly for every operation: ordering the writes, mapping database errors, redacting secrets from the audit data, and in the frameworks retrying a conflict.
Why authorization is a required phase. A permission check that each handler “remembers” to make is a check that one handler eventually forgets. Making authorization a phase that the runner always runs, with “deliberately open” spelled out in code, turns a missing check into something a reviewer and a static analyser can see.
Why “one business operation”. A use case is named for what the business does, not for the table it touches. That keeps one transaction around one decision, keeps each event meaningful (“order placed”, not “order row updated”), and stops a request handler from stitching several writes together outside any rule.
Where the event and audit row go
Section titled “Where the event and audit row go”The runner writes to an outbox in the application’s own database: the outbox_messages table,
with one row per event (EVENT), dispatch job (DISPATCH_JOB), push (PUSH) and audit entry
(AUDIT_LOG). After commit, a relay sends those rows to the platform’s batch endpoints, which is
how the change enters the messaging pipeline. See
the transactional outbox.
The platform itself is the one exception. Its use cases run through the same envelope, but its sink writes events and audit rows straight into its own event and audit tables in the same transaction: the platform has no outbox to hop through, because it is the destination.
The same shape in every language
Section titled “The same shape in every language”The SDKs and the frameworks implement the same envelope, so a team moving between languages finds the same phases and the same guarantee.
The Go SDK’s usecaseop package (github.com/flowcatalyst/go-sdk/usecaseop), which the platform
uses for its own operations. Run applies the plan through a usecasepgx.UnitOfWork whose sink
writes the outbox rows.
func PlaceOrder(repo OrderRepository) usecaseop.Operation[PlaceOrderCommand, OrderPlaced] { return usecaseop.Operation[PlaceOrderCommand, OrderPlaced]{ Name: "PlaceOrder", Validate: func(_ context.Context, cmd PlaceOrderCommand) error { if cmd.TotalCents <= 0 { return usecase.Validation("TOTAL_INVALID", "totalCents must be positive") } return nil }, Authorize: usecaseop.Public[PlaceOrderCommand], // or a real check Execute: func(_ context.Context, cmd PlaceOrderCommand, ec usecase.ExecutionContext) (usecaseop.Plan[OrderPlaced], error) { order := &Order{ID: tsid.GenerateWithPrefix("ord"), CustomerID: cmd.CustomerID, TotalCents: cmd.TotalCents} event := OrderPlaced{Meta: newMeta(ec, "sales", "order", "placed", order.ID), OrderID: order.ID} return usecaseop.Save(order, repo, event), nil }, }}
// in the handlerevent, err := usecaseop.Run(ctx, uow, PlaceOrder(repo), cmd, usecase.NewExecutionContext(principalID))Plans are built with Save, Delete, Emit, SaveAll and Sync, and carry dispatch jobs with
.Dispatch(jobs...). For the rare command that must write several aggregates and return something
other than one event, TxOperation and RunTx keep the same phases around one transaction. The Go
application framework has its own usecase package with the same phases, plus optimistic locking
and pushes.
The Java application framework (UseCase.named(...)). The Java SDK has no use-case envelope; Java
services get it from the framework.
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(...)); });
// run ituseCases.run(addLine, context, command);A use case without authorize fails when it is defined. Plans add steps with andSave,
andDelete, andEmit, andAppend, andDispatch and andPush.
usecase in @flowcatalyst/sdk. run applies the plan through an OutboxUnitOfWork, which owns
the transaction.
import { usecase } from "@flowcatalyst/sdk";
const placeOrder: usecase.Operation<PlaceOrder, OrderPlaced> = { name: "PlaceOrder", validate(cmd) { return cmd.totalCents > 0 ? null : usecase.UseCaseError.validation("TOTAL_INVALID", "totalCents must be positive"); }, authorize: usecase.publicAuthorize, // or a real check async execute(cmd, ctx) { const order = newOrder(cmd); return usecase.Plan.save(order, orderRepo, orderPlaced(ctx, order)); },};
const result = await usecase.run(uow, placeOrder, cmd, ctx);Plan.save, Plan.delete and Plan.emit build plans; Plan.andPush(plan, ...pushes) adds
pushes written after the event.
FlowCatalyst\UseCase in the Laravel SDK. An operation implements Operation; Runner::run
applies the plan through the OutboxUnitOfWork the service provider binds.
use FlowCatalyst\UseCase\{Command, ExecutionContext, Operation, Plan, UseCaseError};
final class PlaceOrderOperation implements Operation{ public function __construct(private OrderRepo $orders) {}
public function validate(Command $command): ?UseCaseError { return $command->totalCents > 0 ? null : UseCaseError::validation('TOTAL_INVALID', 'totalCents must be positive'); }
public function authorize(Command $command, ExecutionContext $context): ?UseCaseError { return null; // deliberately open; coarse access is checked by the controller }
public function execute(Command $command, ExecutionContext $context): Plan|UseCaseError { $order = Order::place($command); return Plan::save($order, $this->orders, OrderPlaced::from($context, $order)); }}
$result = Runner::run($unitOfWork, new PlaceOrderOperation($orders), $command, $context);Plan::save, Plan::delete and Plan::emit build plans; ->andPush(...) adds pushes.
The samples are abridged: the event type, the repository and the command are the application’s own. The SDK and framework pages have complete, runnable versions.
What the frameworks add
Section titled “What the frameworks add”The application frameworks (Java and Go) follow a written contract for the write path that builds on the SDK envelope:
- Optimistic locking. Every aggregate has a version. An update or delete that finds the version
changed means someone else committed first; the use case’s declared conflict policy either
fails with
CONFLICTor runs the whole use case again from the start, up to a limit. - A load phase. A use case on one stored record can load it once per attempt and check access
against the record itself (
authorizeLoaded), beforeexecutesees it. - Client scoping. Every aggregate in a plan must belong to the caller’s client; a plan that would write another client’s data fails as a bug.
- Running inside the caller’s transaction, on a savepoint, for work that already owns one, such as handling a dispatch-job delivery.
Read next
Section titled “Read next”- The transactional outbox: how the rows the runner writes reach the platform.
- Go SDK: use cases
- Framework: the write path and its specification
- Publish events with the outbox
- Decision: a use case is one domain operation