Skip to content

Orders

orders-demo is the framework’s smaller example service, and it exists in both languages with the same table, the same use cases and the same events, so the same outbox rows. It is deliberately small: one aggregate (an order with its lines), three use cases, a checked-SQL repository, and a typed HTTP API on top. Read it first; the support tickets tutorial adds everything this one leaves out (a status machine, receivers, definitions, per-client settings).

The page walks through the service in the order you would build it. Every snippet is from the example’s source. The ideas behind it are on the write path; this page shows them working.

An order belongs to a client (the tenant). You can place an order, add lines to it while it is open, and cancel it. A cancelled order accepts nothing more. Each successful operation:

  1. changes the order (one row, plus its lines);
  2. writes a domain event and an audit row to the outbox, in the same transaction.
Use case Command Event (orders:sales:order:...)
place-order customer name placed
add-line order id, SKU, quantity, unit price in cents line-added
cancel-order order id, reason cancelled

Nothing delivers the events inside the service. The platform’s outbox relay does that (The transactional outbox).

One migration, owned by the application’s module (Java and Go share the file byte for byte). The orders row carries the client and a version used for optimistic locking; the lines belong to the order, are rewritten with it and are covered by its version.

CREATE TABLE orders (
id VARCHAR(26) PRIMARY KEY,
client_id TEXT NOT NULL,
version BIGINT NOT NULL,
customer TEXT NOT NULL,
status TEXT NOT NULL
);
CREATE INDEX idx_orders_client ON orders (client_id, id);
CREATE TABLE order_lines (
order_id VARCHAR(26) NOT NULL REFERENCES orders (id) ON DELETE CASCADE,
position INTEGER NOT NULL,
line_id TEXT NOT NULL,
sku TEXT NOT NULL CHECK (length(sku) <= 20),
quantity INTEGER NOT NULL CHECK (quantity > 0),
unit_price_cents BIGINT NOT NULL CHECK (unit_price_cents >= 0),
PRIMARY KEY (order_id, position)
);

The CHECK constraints are the last line of defence; the use cases validate before they get there.

The aggregate is an immutable record. State changes return a new value; nothing mutates.

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 boolean isOpen() { return status == OrderStatus.OPEN; }
public Order withLine(OrderLine line) {
List<OrderLine> more = new ArrayList<>(lines);
more.add(line);
return new Order(id, client, version, customer, status, more);
}
public Order cancel() {
return new Order(id, client, version, customer, OrderStatus.CANCELLED, lines);
}
}

OrderId is a one-line record implementing AggregateId (ord_ plus a TSID); OrderStatus is OPEN or CANCELLED.

A command says what the caller wants; it also says what goes in the audit row. An event says what happened; its fields are the outbox row’s data.

public record AddLine(String orderId, String sku, int quantity, long unitPriceCents)
implements AuditData {
@Override
public Map<String, Object> auditData() {
return Map.of("orderId", orderId, "sku", sku, "quantity", quantity);
}
}
public static final EventType LINE_ADDED = new EventType("orders", "sales", "order", "line-added");
public record OrderLineAdded(
EventMetadata metadata, String orderId, String lineId, String sku,
int quantity, long unitPriceCents, int lineCount)
implements DomainEvent {}

A use case is one business operation, defined once, with a fixed shape: validate the command, authorize the caller, then execute, which loads what it needs once, applies the rules and returns a plan: the entity change plus the event. The framework runs the plan in one transaction together with the audit row and the outbox rows. A rule that rejects returns an error with a kind (VALIDATION, AUTHORIZATION, NOT_FOUND, CONFLICT, BUSINESS_RULE, INTERNAL) and a code; nothing is written.

add-line shows all of it:

UseCase.named("add-line", AddLine.class, OrderLineAdded.class)
.validate((context, command) -> {
if (command.sku().isBlank()) {
return Optional.of(UseCaseError.validation("SKU_REQUIRED", "A sku is required."));
}
if (command.quantity() <= 0) {
return Optional.of(UseCaseError.validation("QUANTITY_INVALID", "The quantity must be positive."));
}
return Optional.empty();
})
.authorize(PRINCIPAL_REQUIRED)
.conflict(ConflictPolicy.retry(3, Duration.ofMillis(25)))
.execute((context, command) -> {
Optional<Order> found = load(context, command.orderId());
if (found.isEmpty()) {
return orderNotFound();
}
Order order = found.get();
if (!order.isOpen()) {
return orderNotOpen();
}
OrderLine line = new OrderLine(ids.generate("lin"), command.sku(), command.quantity(), command.unitPriceCents());
Order updated = order.withLine(line);
return Plan.save(
updated,
repository,
new OrderLineAdded(
events.metadata(context, OrderEvents.LINE_ADDED, order.id()),
order.id().value(), line.lineId(), line.sku(),
line.quantity(), line.unitPriceCents(), updated.lines().size()));
});

Where PRINCIPAL_REQUIRED is a Check that returns UseCaseError.authorization("PRINCIPAL_REQUIRED", ...) when context.principal() is null. orderNotFound() and orderNotOpen() return Decision.reject(UseCaseError.notFound(...)) and Decision.reject(UseCaseError.businessRule(...)).

Every update is UPDATE ... WHERE id = ? AND client_id = ? AND version = ?. If the row count is not 1, someone else changed the order since this use case loaded it, and the use case’s conflict policy decides: retry(3, 25 ms) loads again and re-applies the rule on fresh state, fail() returns CONFLICT with the code STALE_AGGREGATE (the default).

The demo chooses per use case, and the reasoning is worth copying: adding a line is safe to repeat on fresh state, so it retries; a cancellation made on a stale view is for the caller to decide again, so it fails.

The repository is the only place that touches SQL. It reads through the database pool and writes inside the use case’s transaction, always filtered by client_id, so one client can never load another’s order.

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

OrderSql is generated from OrderSql.sql by checked SQL: the queries are checked against the migrated schema at build time.

The application’s module declares its migrations and provides its use cases.

public final class OrdersModule implements Module {
public static final String ID = "orders";
@Override
public String id() { return ID; }
@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()));
}
}
public static AppBuilder builder() {
return App.builder()
.module(new DatabaseModule())
.module(new OutboxModule())
.module(new UseCaseModule())
.module(new OrdersModule());
}

Configuration is one PostgreSQL; every value can be overridden by the environment variable named after its path:

database:
default: main
instances:
main:
url: jdbc:postgresql://localhost:5432/app
username: app
password: ""
pool: { max: 10, min-idle: 1, connect-timeout: 5s }
migrate: true

Set DATABASE_INSTANCES_MAIN_URL and DATABASE_INSTANCES_MAIN_PASSWORD rather than editing the file; put secrets in config/secrets.local.yaml (never committed). The example’s flowcatalyst module is off (flowcatalyst.enabled: false), so it runs with no platform.

Both languages ship a scenario that places an order, adds two lines, cancels it, then tries to add a line after the cancel, and prints the result.

Context context = Context.of(client).withPrincipal(new PrincipalId("usr_demo"));
UseCaseResult<OrderEvents.OrderPlaced> placed =
useCases.run(orders.placeOrder(), context, new PlaceOrder("Ada Lovelace"));
// ...
String orderId = ((UseCaseResult.Committed<OrderEvents.OrderPlaced>) placed).event().orderId();
useCases.run(orders.addLine(), context, new AddLine(orderId, "ANALYTICAL-ENGINE", 1, 120_000));
useCases.run(orders.cancelOrder(), context, new CancelOrder(orderId, "changed my mind"));
useCases.run(orders.addLine(), context, new AddLine(orderId, "PUNCH-CARDS", 1, 3)); // fails

UseCaseResult is Committed (with the event) or Failed (with the error). Run with OrdersDemo.main.

The output shows each step’s outcome. The last add fails with a business-rule error and writes nothing:

place: committed orders:sales:order:placed
add: committed orders:sales:order:line-added
add: committed orders:sales:order:line-added
cancel: committed orders:sales:order:cancelled
add after cancel: BUSINESS_RULE ORDER_NOT_OPEN
order ord_... CANCELLED v<n>: 2 lines, <total> cents

(Ids and versions vary.) Afterwards outbox_messages holds an event row and an audit row for each of the four successful steps, and none for the failed one; they were written in the same transactions as the orders.

The same use cases sit behind typed operations. An operation declares its method, path, request body with its validation rules, response type, permission and documented errors, and the framework derives the OpenAPI document from them (typed operations):

public static final Operation<AddLineBody, OrderView> ADD_LINE =
Operation.post("/api/orders/{orderId}/lines", AddLineBody.V, OrderView.class)
.id("addOrderLine")
.summary("Add a line to an open order")
.tag("orders")
.path(ORDER_ID)
.permission(MANAGE)
.error(404, "ORDER_NOT_FOUND", "there is no such order")
.error(409, "ORDER_NOT_OPEN", "the order is cancelled and cannot change")
.error(409, "STALE_AGGREGATE", "the order was changed by someone else; reload it and try again")
.build();
public record AddLineBody(String sku, int quantity, long unitPriceCents) {
static final Validator<AddLineBody> V =
Validator.of(AddLineBody.class)
.field("sku", AddLineBody::sku, notBlank(), maxLength(64), pattern("[A-Z0-9][A-Z0-9-]*"))
.field("quantity", AddLineBody::quantity, range(1, 10_000))
.field("unitPriceCents", AddLineBody::unitPriceCents, range(0, 100_000_000));
}

The API sits behind sessions and login: the user’s client in the session becomes the request context’s client, which is what scopes every repository query. Roles map to permissions in the application’s sign-in configuration; the demo has a clerk and a viewer for the orders API and an administrator and an auditor for the admin area.

  • One path for every change. An HTTP handler, a receiver or a script all call the same use case, so the validation, the permission check, the transaction, the audit row and the event are never skipped.
  • The event is part of the change. It is written in the same transaction, so a committed order always has its event and a rolled-back one never leaks one.
  • Tenancy is not optional. The client is in the context, in every table and in every WHERE.
  • Concurrency is a policy. Choose retry or fail per use case, from the nature of the operation.
  • Same behaviour in both languages. The Go build runs against a database the Java build created: same table, same version column, same outbox rows.

The Java example’s tests run real use cases against a real PostgreSQL: the life of an order, rollback on failure, client isolation (a second client cannot see or change the first client’s order), concurrent add-line calls that both land through retry, and the same conflict without retry, which fails and leaves the other use case’s line and the outbox untouched. The API tests use real session cookies for users of two clients. The Go tests do the same in orders_test.go and ordersweb/. See Testing.