Skip to content

Modules and lifecycle

An application is a set of capabilities (database, locks, HTTP, the platform client) plus your own code, wired in a defined order. Both implementations follow the same specification (Core contract) and the same start-up and shutdown sequence, but the shape of the code differs because the languages do.

Java Go
Unit of assembly a Module, listed in code on App.builder() a capability package with a Declare function, called on an fw.App
How services find each other typed lookup (app.get(Locks.class)), with providers run in dependency order none; you build services in one function and pass each its dependencies, so a missing one is a compile error
Configuration problems all reported together all reported together
Problems while building (a database that does not answer) collected where possible stop at the first failing component
Replacing a service in a test AppBuilder.override(type, instance) when APP_ENV=test the build function takes the collaborators a test replaces as parameters
  1. Declare. Every module or package says what it needs: settings, instance sections, migration sets, commands, the configuration components it claims.
  2. Configure. Configuration is loaded and every declared setting is validated. Every problem is reported at once, naming the key.
  3. Build. Services are constructed.
  4. Boot. Each module reads its configuration, registers health checks, routes and background loops.
  5. Started. Work that needs every module booted (the HTTP server compiles its route table and starts listening).
  6. Run until the process is signalled or the server returns.
  7. Shutdown, in the reverse of start-up.

A command (sync, openapi, migrate) stops after step 3: no boot, no routes, no server.

public interface Module {
String id();
default void register(AppBuilder app) throws Exception {}
default void boot(App app) throws Exception {}
default void started(App app) throws Exception {}
default void shutdown(App app) throws Exception {}
}

The id matches [a-z][a-z0-9-]* and must be unique. core is taken by the framework’s own module, which is added for you.

Hook Use it to Do not
register(AppBuilder) declare settings, provide services, claim configuration components, contribute migrations and definitions, claim commands build services, read config values, start threads
boot(App) read config, look up services, add health checks, register routes and background loops (loops start only after every started hook has run) provide new services
started(App) work that needs every module booted provide new services
shutdown(App) stop what you started

App.builder().module(a).module(b)...start() does this, in order:

  1. Calls every module’s register, in the order listed.
  2. Loads and validates configuration. Any problem fails here.
  3. Builds every provided service, eagerly. A provider asks for what it needs and that is built first.
  4. Calls every module’s boot, in order.
  5. Calls every module’s started, in order, after every boot finished. If any boot failed, no started runs.
  6. Returns the running App.

Failures are thrown from start() as StartupException, collected so one start reports every problem: a duplicate module id, two providers for one type, a lookup of a type nobody provides, a dependency cycle, any config error, an unknown driver, an exception from a provider or hook. Services already built are closed before it is thrown; StartupException.problems() lists them.

A module provides a service by type during register. The lambda is a Provider<T> (T create(Lookup lookup) throws Exception); Lookup offers get(Class), contributions(Class) and moduleId().

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()));
  • One provider per type. A second provide for a type fails start-up, naming both modules.
  • Providers run once, at start-up, in dependency order. A provider that asks for a type nobody provides fails start-up and names the asking module.
  • The framework provides Config, InstantSource, Ids, MonotonicClock, Health and EnvironmentVariables, plus Metrics and Background; a module cannot provide these. Ids.generate("ord") gives ord_ plus 13 characters. Use the injected InstantSource, not Instant.now(), so tests can fix the clock.
  • A service that is AutoCloseable is closed at shutdown.

After start-up, App is a typed map: app.get(Locks.class) throws IllegalArgumentException if absent, app.find(ContextResolver.class) returns an Optional. App also has config(), health(), moduleIds(), buildOrder() and shutdownDrain().

A module can hand a value to another module that collects them. This is how migrations work:

MigrationSet.contribute(app, OrdersModule.class, "db/migration/orders");

The class passed is used only for its class loader: it says which jar holds the SQL directory. Call it from register, because the contributing module’s id is taken from the module being registered. The raw form is app.contribute(Class<T>, T). The FlowCatalyst module’s Definitions.in(app) uses the same mechanism.

Method Meaning
module(Module) add a module; order matters (register, boot, started, migrations)
configDirectory(Path) where application.yaml lives; default config under the working directory
environment(Map<String,String>) the environment to read instead of System.getenv(); tests use this
instantSource(InstantSource) the wall clock
monotonicClock(MonotonicClock) the clock used by locks and timeouts
shutdownHook(boolean) close from a JVM shutdown hook; default off
override(Class<T>, T) replace a provided service; only when APP_ENV is test, otherwise start-up fails

A builder starts once; reusing it throws IllegalStateException.

static final class MailModule implements Module {
static final Setting<String> HOST =
Setting.string("mail.host").asRequired().describedAs("SMTP host.");
static final Setting<Secret> PASSWORD = Setting.secret("mail.password");
@Override
public String id() { return "mail"; }
@Override
public void register(AppBuilder app) {
app.declare(HOST);
app.declare(PASSWORD);
app.provide(
Mailer.class,
lookup -> {
Config config = lookup.get(Config.class);
return new Mailer(config.get(HOST), config.find(PASSWORD).orElse(Secret.of("")));
});
}
@Override
public void boot(App app) {
app.health().add("mail", () -> {
if (app.get(Mailer.class).host.isEmpty()) {
throw new IllegalStateException("no host");
}
});
}
}

Shutdown is idempotent and runs in a fixed order: not ready first, then the background loops stop, then each module’s shutdown work runs in reverse order, then built services are closed in reverse build order. A failure in one step is logged and does not stop the rest. Each step gets app.shutdown.drain (default 10s). A step still running after that is logged as an overrun, interrupted (Java) or abandoned (Go), and shutdown moves on without waiting, so write shutdown work that stops promptly.

App.close() is idempotent and AutoCloseable, so use try-with-resources in tests. builder.shutdownHook(true) also closes the app from a JVM shutdown hook; the default is off so tests leave no hooks behind. The steps run on virtual threads.

The database capability provides one pooled connection per configured instance, each with a database:<name> health check. Instances, pools and migrate are configuration (Configuration); see Database and Redis for the keys.

Migrations are plain SQL files, forward only, named V<version>__<description>.sql with a positive integer version (for example V0001__create_orders.sql). Each module contributes at most one set (a module id plus a location), and your application contributes its own the same way. Sets are applied to the default database instance, in module registration order and by version within a set, only when that instance’s migrate is true (the default). Each file runs in its own transaction together with its row in fw_schema_history, under a PostgreSQL advisory lock so instances starting together apply each file once. A changed checksum of an applied file, a missing applied file or a skipped lower version fails start-up.

Registration order is migration order: list the module whose tables you depend on (the outbox module, for example) before your own.

A check returns normally for up and fails for down; the message becomes the reason. All checks run in parallel, each limited by app.health.timeout (default 2s), and report Up, Down(reason) or TimedOut. With the HTTP server, /health/ready serves the report (HTTP).

app.health().add("mail", () -> {
if (app.get(Mailer.class).host.isEmpty()) {
throw new IllegalStateException("no host");
}
});
// a dependency you can serve requests without
app.health().add("flowcatalyst", client::verifyCredentials, Criticality.INFORMATIONAL);

app.health().check() returns a HealthReport: isUp() is true when every check is up, isReady() when every critical one is, criticality(name) says how a check ran.

A check is critical (the default) or informational. A critical check that is not up makes the application not ready; an informational one is reported but never decides readiness. Configuration overrides a module’s choice by name:

app:
health:
critical: [flowcatalyst] # the platform decides readiness again
informational: ["database:reporting"]

A name in both lists fails start-up. A name that matches no check is logged at WARN once start-up finishes, not refused, because some checks exist only in some deployments. The core claims the app component, so a misspelt key under it (app.helth.critical) fails start-up as unknown.

A module can claim a command name, which is how java -jar app.jar sync or app sync works. Command names match [a-z][a-z0-9-]*; two claims for one name fail start-up. A command runs after configuration and building and before boot, so it has no routes, no health checks and no server. Anything not claimed starts the application normally; an unknown argument is not an error.

app.command(
new Command() {
@Override public String name() { return "mail-test"; }
@Override public int run(App app, List<String> args, PrintStream out) {
out.println("host " + app.get(Mailer.class).host);
return 0;
}
});

AppBuilder.launch(String... args) returns Launch.Ran(exitCode) when a command ran (the application is closed first) or Launch.Started(app):

switch (App.builder().module(/* ... */).launch(args)) {
case Launch.Ran ran -> System.exit(ran.exitCode());
case Launch.Started started -> { } // running; the server threads keep the JVM alive
}

Anything thrown out of a command, an Error included, is logged and launch returns Launch.Ran(1) after closing the application, so non-daemon threads end and the JVM exits. An Error from a provider, boot or started closes the services built so far and propagates.

Declaration-phase commands need only what modules declared, not configuration or services. Writing the OpenAPI document is the first (app openapi, see Typed operations and OpenAPI). They run after declaration and stop there: no configuration file is read, no provider runs, nothing connects, so they work in a build without a database. In Java a module claims one with the app.command(DeclarationCommand) overload (its run(Declarations, args, out) gets a read-only view with moduleIds(), settings() and contributions(Type.class)); in Go with Declarer.DeclarationCommand.

Things an application can have many of are code: lock stores, secret stores, HTTP clients and rate limiters are named in a builder with a factory that names the driver, for example LocksModule.builder().store("main", DatabaseLockStores.database()). No configuration key chooses a driver (Configuration).

Connections are named instances in configuration. Database and Redis build every instance under <section>.instances. A key that an instance factory did not read fails start-up as unknown, so a typo cannot pass silently; with exactly one instance default may be omitted, with several it must name one; a capability with no configured instances is valid.

An InstanceFactory<T> receives the instance name, its InstanceConfig section, a Lookup and the instances built so far, and reads its keys through typed getters (string, integer, bool, duration, secret, findString, section). Instances.build(Database.class, "database", lookup, factory) returns a registry with get(name), defaultInstance(), names() and all(). The shipped registries (Locks, Databases, RedisConnections) have package-private constructors; a capability of your own writes a registry around Instances.

The specification is the Core contract. Configuration is covered next in Configuration.