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.
What the service does
Section titled “What the service does”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:
- changes the order (one row, plus its lines);
- 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).
The schema
Section titled “The schema”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 domain
Section titled “The domain”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.
Go makes the invalid states unrepresentable instead. Ids are typed (id.ID[OrderKind] is not
id.ID[LineKind]), fields are value types whose only constructor validates, and the aggregate is a sealed
sum of its states, so a switch over it must name both (the linter gochecksumtype enforces it):
type OrderKind struct{}func (OrderKind) Prefix() string { return "ord" }type OrderID = id.ID[OrderKind] // "ord_" + 13 Crockford characters
type CustomerName struct{ v string }
func ParseCustomerName(raw string) (CustomerName, error) { s := strings.TrimSpace(raw) switch { case s == "": return CustomerName{}, usecase.Validation(CustomerRequired, "A customer is required.") case utf8.RuneCountInString(s) > 100: return CustomerName{}, usecase.Validation(CustomerTooLong, "At most 100 characters.") } return CustomerName{v: s}, nil}
//sumtype:decltype Order interface { ID() OrderID Customer() CustomerName Lines() []OrderLine AuditEntity() usecase.Entity isOrder()}
type OpenOrder struct{ /* id, customer, lines */ } // accepts linestype CancelledOrder struct{ /* ... */ } // accepts nothing
func (o OpenOrder) WithLine(l OrderLine) OpenOrder { /* ... */ }func (o OpenOrder) Cancel() CancelledOrder { return CancelledOrder(o) }SKU, Quantity, Cents and CancelReason follow the same pattern (ParseSKU, NewQuantity,
NewCents, ParseCancelReason). A command built from them is valid by construction.
Commands and events
Section titled “Commands and events”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 {}type AddLine struct { Order domain.OrderID SKU domain.SKU Quantity domain.Quantity UnitPrice domain.Cents}
func (c AddLine) AuditData() []usecase.AuditField { return []usecase.AuditField{ usecase.Field("orderId", c.Order.String()), usecase.Field("sku", c.SKU.String()), usecase.Field("quantity", c.Quantity.Int()), }}
var LineAdded = event.MustType("orders:sales:order:line-added")
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"`}The JSON keys are the Java record’s components, so the outbox row’s data is identical in both languages.
The use cases
Section titled “The use cases”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(...)).
A use case is a struct with methods Name, Validate, Authorize and Execute. Validation of the
command’s shape already happened when it was parsed, so Validate here has nothing to do.
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.") } var open domain.OpenOrder switch o := loaded.Get().(type) { case domain.OpenOrder: open = o case domain.CancelledOrder: return nil, usecase.BusinessRule(OrderNotOpen, "The order is cancelled and cannot change.") } line := domain.NewOrderLine(id.New[domain.LineKind](u.Ids), cmd.SKU, cmd.Quantity, cmd.UnitPrice) open = open.WithLine(line) ev := OrderLineAdded{ Meta: u.Events.Metadata(cx, LineAdded, cmd.Order.String()), OrderID: cmd.Order, LineID: line.ID(), SKU: line.SKU().String(), Quantity: line.Quantity().Int(), UnitPriceCents: line.UnitPrice().Int(), LineCount: len(open.Lines()), } return usecase.NewPlan(ev, usecase.Update(loaded.With(open), u.Orders)), nil}The use cases are defined once on a runner, with their conflict policies:
add, err := usecase.Define(r, AddLineUseCase{Orders: store, Ids: ids, Events: events}, usecase.WithConflictPolicy(p.AddLine)) // usecase.Retry(3, 25*time.Millisecond)cancel, err := usecase.Define(r, CancelOrderUseCase{Orders: store, Events: events}, usecase.WithConflictPolicy(p.Cancel)) // usecase.Fail()Conflicts and the two policies
Section titled “Conflicts and the two policies”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
Section titled “The repository”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.
@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;}OrderSql is generated from OrderSql.sql by checked SQL: the queries are
checked against the migrated schema at build time.
func (Repository) Update(ctx context.Context, tx *database.Tx, client fw.ClientID, o domain.Order, v usecase.VersionCheck) (int64, error) { q := dbq.New(tx.Conn()) n, err := q.UpdateOrder(ctx, dbq.UpdateOrderParams{ NewVersion: v.Next, Customer: o.Customer().String(), Status: domain.StatusOf(o), ID: o.ID(), ClientID: client.String(), Version: v.Expected, }) ...}The queries live in sql/orders.sql with sqlc annotations, for example:
-- name: UpdateOrder :execrows-- The optimistic-locking write: the row count says whether the version still matched.UPDATE orders SET version = @new_version, customer = @customer, status = @status WHERE id = @id AND client_id = @client_id AND version = @version;go run ./tools/fwsql check runs sqlc’s checks against a PostgreSQL migrated by the framework’s runner
(checked SQL).
Wiring
Section titled “Wiring”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());}Go splits an application into a declaration step (settings, migrations, claims; before configuration is read) and a build step (connections and services):
func DeclareScenario(app *fw.App) Declared { d := Declared{db: database.Declare(app), outbox: usecase.Declare(app)} orders.Declare(app) // app.Module("orders").Migrations(Migrations()) return d}
func BuildScenario(d Declared, x Deps) fw.BuildFunc { return func(ctx context.Context, b *fw.Boot) (fw.Serve, error) { dbs, err := database.Connect(ctx, b, d.db) if err != nil { return nil, err } if err := database.Migrate(ctx, b, dbs); err != nil { return nil, err } db, _ := dbs.Default() runner, err := usecase.NewRunner(b, d.outbox, db) if err != nil { return nil, err } svc, err := orders.NewService(runner, b.Ids(), event.NewFactory(b.Clock(), b.Ids())) ... }}(error handling shortened). app.Launch(ctx, args, build) runs the result.
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: trueSet 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.
Running a scenario
Section titled “Running a scenario”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)); // failsUseCaseResult is Committed (with the event) or Failed (with the error). Run with
OrdersDemo.main.
cx := fw.ContextFor(client).WithPrincipal(fw.MustPrincipalID("usr_demo"))customer, _ := domain.ParseCustomerName("Ada Lovelace")placed, err := svc.PlaceOrder.Run(ctx, cx, orders.PlaceOrder{Customer: customer})orderID := placed.Event().OrderID
cmd, _ := orders.ParseAddLine(orderID, "ANALYTICAL-ENGINE", 1, 120_000)_, err = svc.AddLine.Run(ctx, cx, cmd)A failure is an error that usecase.AsError(err) turns into a kind and a code. Run with
go run . from go/examples/orders-demo (no arguments runs the scenario).
The output shows each step’s outcome. The last add fails with a business-rule error and writes nothing:
place: committed orders:sales:order:placedadd: committed orders:sales:order:line-addedadd: committed orders:sales:order:line-addedcancel: committed orders:sales:order:cancelledadd after cancel: BUSINESS_RULE ORDER_NOT_OPENorder 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.
Over HTTP
Section titled “Over HTTP”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));}orders-demo serve serves the API behind sessions and login, the embedded single-page application and
the admin area; orders-demo openapi --out web/openapi.json writes the OpenAPI document with no
configuration or database. The operations are declared in orders/api.go and bound to the use cases with
api.Bind(rt); the request is parsed at the edge into the validated command types shown earlier.
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.
What to take from it
Section titled “What to take from it”- 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.