Your first service on the framework
The application framework is for building business services that live beside the platform: their own database, their own HTTP API and screens, and FlowCatalyst for events, delivery, identity and configuration. Java is the reference implementation; Go is an interchangeable one (a Go service can take over a Java service’s database, because both write the same tables, outbox rows and ids).
This tutorial walks through a shortened orders service, the framework’s own orders-demo
example, piece by piece. Each piece is real code from the example; the example itself is the
complete, runnable version.
flowchart LR SPA[SPA in the browser] -->|session cookie| OP[typed operation POST /api/orders] OP --> UC[use case place-order] UC -->|one transaction| DB[(service DB: orders + outbox_messages)] DB --> R[fcdev outbox relay] --> FC[Platform] FC -->|signed delivery| RC[receiver /fc/dispatch] RC --> UC2[another use case]
Before you start
Section titled “Before you start”JDK 25 and Maven 3.9. The framework is published to GitHub Packages (framework-bom, current
release 0.2.2; reading needs a GitHub token with read:packages). The FlowCatalyst module
also needs the platform’s Java SDK, which is published from 0.0.30 to the platform repository’s GitHub
Packages Maven registry (https://maven.pkg.github.com/flowcatalyst/flowcatalyst, same token): add that repository, or build the tag
java-sdk/v0.0.31 into your local Maven repository. The
framework’s getting-started page has the details.
Go 1.27. The core module is github.com/flowcatalyst/framework/go (current tag go/v0.4.4):
go get github.com/flowcatalyst/framework/go@v0.4.4The FlowCatalyst module (github.com/flowcatalyst/framework/go/flowcatalyst, receivers and sync)
is a separate Go module with its own tags (current go/flowcatalyst/v0.3.5):
go get github.com/flowcatalyst/framework/go/flowcatalyst@v0.3.5.
You also need PostgreSQL for the service’s own data (a database on fcdev’s embedded server is fine
for trying it), and fcdev running for the platform parts.
1. The application is a list of modules
Section titled “1. The application is a list of modules”An application names every module it uses, in code. There is no classpath scanning and no auto-configuration: what is not listed does not run.
public static AppBuilder builder() { return App.builder() .module(new DatabaseModule()) // PostgreSQL, migrations .module(new OutboxModule()) // outbox_messages in this database .module(new UseCaseModule()) // the write path .module(new OrdersModule()); // the service's own module}
try (App app = builder().shutdownHook(true).start()) { ... }A module contributes its migrations and its services:
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())); }}func main() { app := fw.New("orders-demo") d := Declare(app) os.Exit(app.Launch(context.Background(), os.Args[1:], BuildWeb(d)))}
// Declare runs before configuration is read: what the application uses.func Declare(app *fw.App) Declared { d := Declared{db: database.Declare(app), outbox: usecase.Declare(app)} orders.Declare(app) // the orders migrations d.web = httpfw.Declare(app) orders.DeclareAPI(d.web) // the typed operations, for the OpenAPI document authdb.Declare(app) d.auth = auth.Declare(app, d.web) // sessions and login return d}The build function then connects, migrates and builds the services:
dbs, err := database.Connect(ctx, b, d.db)if err := database.Migrate(ctx, b, dbs); err != nil { return nil, err }db, _ := dbs.Default()runner, err := usecase.NewRunner(b, d.outbox, db)svc, err := orders.NewService(runner, b.Ids(), event.NewFactory(b.Clock(), b.Ids()))Configuration holds only connections and secrets (database URL, credentials, ports); everything
else is code. config/application.yaml:
database: default: main instances: main: url: jdbc:postgresql://localhost:15432/orders username: postgres password: "" # in config/secrets.local.yaml or DATABASE_INSTANCES_MAIN_PASSWORD migrate: trueEvery key can be overridden by the environment variable named after its path
(DATABASE_INSTANCES_MAIN_URL). See configuration.
2. A use case: one business operation
Section titled “2. A use case: one business operation”A use case is one business operation: validate the command, authorize the caller, execute into
a plan. The framework applies the plan in one transaction: the aggregate row, the domain
event (an EVENT row in the outbox) and an audit row. A use case cannot write any other way, so
“changed but no event” cannot happen. The write path explains why.
private UseCase<PlaceOrder, OrderPlaced> definePlaceOrder() { return UseCase.named("place-order", PlaceOrder.class, OrderPlaced.class) .validate((context, command) -> command.customer().isBlank() ? Optional.of(UseCaseError.validation("CUSTOMER_REQUIRED", "A customer is required.")) : Optional.empty()) .authorize(PRINCIPAL_REQUIRED) .execute((context, command) -> { Order order = Order.place(new OrderId(ids.generate("ord")), context.client(), command.customer().strip()); return Plan.save(order, repository, new OrderPlaced(events.metadata(context, OrderEvents.PLACED, order.id()), order.id().value(), order.customer())); });}
// running itUseCaseResult<OrderPlaced> placed = useCases.run(orders.placeOrder(), context, new PlaceOrder("Ada Lovelace"));type PlaceOrderUseCase struct { Orders Store Ids *fw.Ids Events *event.Factory}
func (PlaceOrderUseCase) Name() usecase.Name { return usecase.MustName("place-order") }
func (PlaceOrderUseCase) Validate(context.Context, fw.Context, PlaceOrder) error { return nil }
func (PlaceOrderUseCase) Authorize(_ context.Context, cx fw.Context, _ usecase.Valid[PlaceOrder]) (usecase.Grant, error) { return principalRequired(cx)}
func (u PlaceOrderUseCase) Execute(_ context.Context, cx fw.Context, a usecase.Authorized[PlaceOrder], _ *database.DB) (*usecase.Plan[OrderPlaced], error) { order := domain.PlaceOrder(id.New[domain.OrderKind](u.Ids), a.Command().Customer) ev := OrderPlaced{Meta: u.Events.Metadata(cx, Placed, order.ID().String()), OrderID: order.ID(), Customer: order.Customer().String()} return usecase.NewPlan(ev, usecase.Insert(usecase.NewFresh[domain.Order](cx, order), u.Orders)), nil}
// defining and running itplace, err := usecase.Define(runner, PlaceOrderUseCase{Orders: store, Ids: ids, Events: events})done, err := place.Run(ctx, cx, PlaceOrder{Customer: customer})In Go the phases are typed: Execute can only receive a command that passed Validate and
Authorize (usecase.Authorized[T]).
The event’s type is orders:sales:order:placed. Every use case runs in a context: the client
(tenant), the principal, the correlation id. The context is how the service stays multi-tenant
without passing a tenant id through every call.
3. A typed operation
Section titled “3. A typed operation”HTTP routes are typed operations: method, path, parameters, body validation, the permission required and the errors it may answer, declared once as a value. The same value serves the route and writes the service’s OpenAPI document, so the document cannot drift from the code.
public static final Operation<PlaceOrderBody, OrderView> PLACE = Operation.post("/api/orders", PlaceOrderBody.V, OrderView.class) .id("placeOrder") .summary("Place an order") .tag("orders") .status(201) .permission(MANAGE) .build();
// in the API module's boot()routes.bind(OrdersApi.PLACE, r -> then( useCases.run(orders.placeOrder(), r.context(), new PlaceOrder(r.body().customer())), placed -> view(repository, db, r.context(), placed.orderId())));var PlaceOrderOp = httpfw.Post[PlaceOrderBody, OrderView]("/api/orders", placeOrderRules). ID("placeOrder").Summary("Place an order").Tag("orders"). Status(http.StatusCreated).Permission(Manage).Build()
func (a *API) Bind(rt *httpfw.Routes) { rt.Bind(httpfw.Handle(PlaceOrderOp, a.place))}
func (a *API) place(ctx context.Context, cx fw.Context, in httpfw.In[PlaceOrderBody]) (OrderView, error) { customer, err := domain.ParseCustomerName(in.Body.Customer) if err != nil { return OrderView{}, err } done, err := a.Service.PlaceOrder.Run(ctx, cx, PlaceOrder{Customer: customer}) if err != nil { return OrderView{}, err } return a.view(ctx, cx, done.Event().OrderID.String())}A failed use case answers with its error kind and code (400 CUSTOMER_REQUIRED, 403, 409 STALE_AGGREGATE), in the same error envelope the platform uses. The permission (MANAGE) is checked
against the request’s context, which the auth module fills from a session cookie or a platform
bearer token: see sign users in for wiring AuthModule / auth.Declare to
your login client, and typed operations and OpenAPI.
4. A receiver for platform deliveries
Section titled “4. A receiver for platform deliveries”Events your service subscribes to arrive as signed dispatch-job deliveries. The FlowCatalyst module
mounts POST /fc/dispatch (and /fc/scheduled-jobs), verifies the signature, and calls your
handler as the application’s service principal, with the delivered message as the cause:
// in your module's boot(); list FlowCatalystModule in the applicationReceivers receivers = app.get(Receivers.class);receivers.onDispatch("orders:billing:invoice:paid", (Context ctx, DispatchDelivery d) -> { d.once(db, "mark-paid", tx -> markPaid(tx, d.jobId())); // at most once per job return DispatchResult.ack();});fc, err := flowcatalyst.Build(ctx, b, d, flowcatalyst.WithDatabases(dbs))err = flowcatalyst.OnDispatch(fc.Receivers(), "orders:billing:invoice:paid", func(ctx context.Context, cx fw.Context, d flowcatalyst.Delivery[InvoicePaid]) (flowcatalyst.DispatchResult, error) { _, err := flowcatalyst.Once(ctx, d.Meta, db, "mark-paid", func(ctx context.Context, tx *database.Tx) (struct{}, error) { return struct{}{}, markPaid(ctx, tx.Conn(), d.Data.OrderID) }) return flowcatalyst.Ack{}, err })routes, err := fc.Routes() // add to the serveronce makes the handler’s database work happen at most once per dispatch job, even when the
platform delivers it again. Answer ack, defer (come back later, no attempt spent) or reject
(never retry). The module’s settings (flowcatalyst.base-url, application, client-id,
client-secret) are the service account’s credentials, the same values fcdev init writes. Point a
subscription’s target at https://<service>/fc/dispatch; see
receivers.
5. The single-page application
Section titled “5. The single-page application”The service serves its own front end: a built single-page application, embedded in the build, with
the router falling back to index.html for client-side routes. The SPA talks to the typed operations
with the session cookie (no token in the browser), and its API client is generated from the
service’s OpenAPI document.
public final class OrdersSpaModule implements Module { @Override public String id() { return "orders-spa"; }
@Override public void boot(App app) { app.get(Routes.class).forModule("orders-spa").spa(Spa.classpath("fw-spa").build()); }}site, err := spa.New(dist, spa.Options{}) // dist: the embedded build (an fs.FS)if err != nil { return nil, err}rt.SPA(site)The framework’s UI packages (@flowcatalyst/ui, Nuxt UI) give the SPA the shared components; see
UI overview.
6. Run it and see the events
Section titled “6. Run it and see the events”- Create the service’s database (for example
CREATE DATABASE ordersonfcdev’s server) and set its URL inconfig/application.yaml. - Start the service. The migrations create its tables, including
outbox_messages. - Place an order through the operation (or run the example’s scenario command).
- Relay the outbox to the platform:
fcdev outboxwithFC_OUTBOX_SOURCE_DB_URLpointing at the service’s database and the application’s service-account credentials, exactly as in your first event. - The
orders:sales:order:placedevent appears in the console’s Events page.
The full examples go further: line items, optimistic locking with a conflict policy, cancelling,
checked SQL, an admin area, and tests against a real PostgreSQL. Java: examples/orders-demo
(OrdersDemo, OrdersWeb). Go: go/examples/orders-demo (orders-demo, orders-demo serve,
orders-demo openapi).
- What the framework is and its status.
- The orders tutorial, the full version of this page.
- Modules and lifecycle, the write path, HTTP, sessions and login, the FlowCatalyst module.
- Decision: Java is the reference, Go is interchangeable.