Application Lifecycle
A Miia app moves through three phases: init, active, and shutdown. Knowing what happens in each lets you wire the onInit / onReady / onShutdown / onDestroy lifecycle hooks correctly and reason about graceful shutdown under signals like SIGTERM.
Init phase
Triggered by app.listen(port, ...) (or app.init() directly for embedded scenarios like app.fetch in serverless). Sequence:
- Module graph - every module passed to
register()is loaded: providers are registered, controllers constructed and their routes written to the route table. Skipped if an earlierapp.get()already did it. container.constructAll()- constructs every singleton provider, global guards fromapp.useGuard()included. Module boundary violations found here and in step 1 are thrown as one report, before anyonInit().container.initAll()- runs each singleton'sonInit()(if defined). Async, awaited in dependency order (dependencies first, otherwise registration order).compilePipelines()- bakes global middleware + global and per-route guard/middleware chains into finalMiddlewarefunctions, using the guard instances built in step 2. Runs once per app.container.bootstrapAll()- runs every singleton'sonReady()hook. By this point all providers are fully initialised, so handlers likeMessageBus.onReadycan safely callDiscoveryServiceand wire@Onsubscriptions.
Once init() returns, the app is ready to accept requests via app.fetch.
@Injectable()
class DbConnection {
async onInit() {
await this.connect()
}
}
The module graph is processed once
register() only records modules. The graph is processed once, on the first init(), app.get() or fetch() - so the order of separate register() calls does not matter. What a provider may inject depends on imports and exports, not on order (see Boundaries): violations are collected while the graph is processed and the singletons are constructed, and reported together before the first onInit().
Configuration freezes at two points, and a late call throws an Error instead of being silently ignored:
| Call | Throws after |
|---|---|
register(), provide() | the module graph is processed (first init(), app.get() or fetch()) |
use(), useGuard(), addRoute() | init() has started (listen() calls it) |
This is why app.get(ConfigService) right after register() works, and why middleware, guards and manual routes can still be added after it:
const app = new Miia().register(AppModule)
const config = app.get(ConfigService) // processes the module graph
app.useGuard(RateLimitGuard)
app.use(cors({ origin: config.get('CORS_ORIGIN') }))
app.addRoute('GET', '/', (ctx) => {
ctx.res.redirect('/static')
})
await app.listen(config.get('PORT'))
If the graph fails to process (a duplicate provider, a route conflict), the error is kept: every later init() / app.get() rethrows the same error. So is a boundary report - from init(), or from an app.get() before it - and requests get it too.
After init() completes, listen() computes the body size ceiling - the maximum of the maxBodySize option and all @BodyLimit values across registered routes - and passes it to the runtime: Bun.serve({ maxRequestBodySize }) on Bun, a counting stream wrapper for chunked bodies on Deno, and ListenInfo.maxBodySize for server adapters (@miiajs/node-server, @miiajs/uws-server). See Body size limits.
Active phase
While the app is running:
- HTTP requests routed through
app.fetch→compose()middleware pipeline → controller handler. @Onhandlers receive messages via the configuredMessageTransport(when using@miiajs/messaging).- Request-scoped DI providers are created on the first
ctx.resolve()in a request and kept on that request's context, so concurrent requests never share an instance; once the response is built, they getonDestroy(). requestscope vssingletonvstransient- see Providers.
Shutdown phase
By default, when app.listen() is called, Miia registers handlers for SIGTERM, SIGINT, and SIGHUP. On any of those signals, the app:
- Logs
[App] Received <signal>, shutting down gracefully... - Awaits
app.destroy()which:- Calls
closeServer()(stops accepting new requests) - Waits for the
onDestroy()of requests that finished before shutdown started - a request still running, or one that finishes after that, is not waited for - Runs every singleton's
onShutdown()- stop taking new work and wait for the work in flight (e.g. in-flight handler drain, consumer unsubscribe) - Then runs every singleton's
onDestroy()- release resources (e.g. database disconnect, broker cleanup) - Logs
[App] Shutdown complete
- Calls
process.exit(0)(or1ifdestroy()throws)
Both hook phases run in reverse dependency order - a provider's hooks before those of the providers it injects - and every onShutdown() finishes before the first onDestroy() starts. A provider draining work in onShutdown() can still use the connection it injects; the connection closes in onDestroy():
@Injectable()
class DbConnection {
async onDestroy() {
await this.disconnect()
}
}
@Injectable()
class ReportWorker {
private db = inject(DbConnection)
async onShutdown() {
this.stopPolling()
await this.currentJob // may still query this.db
}
}
A failing step does not stop the rest: a closeServer() that throws does not skip the hooks, and a hook that throws does not skip the others. destroy() logs each failure with its source (DbConnection.onDestroy() failed during shutdown) and throws after everything has run - the error itself for a single failure, an AggregateError for several. Under a signal handler the process then exits with code 1. Calling destroy() yourself, you get both the log lines and the thrown error.
A destroy() called while another is still running returns the same shutdown: the hooks run once, and both calls resolve, or reject with the same error. Once it has settled, the next destroy() runs again.
Concurrent signals are guarded: only the first one initiates shutdown. Pressing Ctrl+C twice means the second SIGINT goes to the OS default action (kill the process) - this is conventional Unix behaviour, not a bug.
Triggers in real deployments
- K8s / Docker stop sends SIGTERM, then SIGKILL after
terminationGracePeriodSeconds(30s default). Fits Miia's flow -destroy()runs within the grace period. - systemd stop also SIGTERM, similar timing.
- Ctrl+C in a terminal sends SIGINT.
- Closing the terminal sends SIGHUP (Unix-only).
Configuring shutdown hooks
The shutdownHooks option in MiiaOptions controls registration:
new Miia() // default - SIGTERM + SIGINT + SIGHUP
new Miia({ shutdownHooks: false }) // opt out completely
new Miia({ shutdownHooks: ['SIGTERM'] }) // custom signal subset
When to opt out:
- Serverless - if you only use
app.fetchfor AWS Lambda / Vercel / Cloudflare Workers, skipapp.listen()entirely. Handlers are not registered (registration happens inlisten(), not constructor). - Multi-Miia processes - rare, but possible (e.g. public API + admin worker in one process). See below.
- Custom bootstrap - you have your own
process.on('SIGTERM')orchestration and want full control overdestroy()timing.
Behavioural details
process.exit(0)cancels non-awaited timers and any remaining open handles afterdestroy()returns. Acceptable trade-off for deterministic exit. If you have long-running background jobs, await them in your ownonShutdown().- User signal handlers co-exist with Miia's. If you have your own
process.on('SIGTERM', ...)listener, it still fires alongside Miia's. PassshutdownHooks: falseif you want exclusive control. - Windows: SIGHUP is not supported. Miia silently filters it out from the default array on
process.platform === 'win32'. SIGTERM and SIGINT remain active. TestAppdoes not calllisten()- it goes throughinit()directly. So no signal handlers are registered in tests, by construction.
Multi-Miia in one process
Node delivers each signal to every registered listener. If two Miia instances both have shutdownHooks: true, both start their own destroy() concurrently on SIGTERM. The first instance to reach process.exit(0) terminates the process; the other's cleanup may be interrupted mid-flight.
Pattern for two-app processes:
const primary = new Miia().register(PublicAppModule)
const admin = new Miia({ shutdownHooks: false }).register(AdminAppModule)
await Promise.all([primary.listen(8080), admin.listen(9090)])
// Primary owns shutdown signals. When SIGTERM fires, Miia destroys primary
// automatically. We register an extra hook to tear down admin first.
process.on('SIGTERM', async () => {
await admin.destroy()
// primary.destroy() runs from Miia's own handler immediately after.
})
Alternative: both opt out, register your own coordinator.
Embedded app.fetch (serverless)
For environments where the runtime owns the request loop (Cloudflare Workers, Vercel Edge), do not call app.listen():
const app = new Miia({ shutdownHooks: false })
.register(AppModule)
await app.init() // explicit - normally called by listen()
export default { fetch: app.fetch } // platform handler
Keep the explicit await app.init() on cold start. Without it the first request processes the module graph and runs the hooks, so a graph error (a duplicate provider, a route conflict) surfaces as a failed request instead of a failed start.
Cloudflare Workers is the exception when start-up does I/O. The top of a module runs in the global scope, where timers, network I/O and random values are not allowed, so a top-level await app.init() stops the Worker from starting if a constructor or a hook does any of them (Disallowed operation called within global scope). Leave init() out in that case: the first request runs it, and requests that arrive meanwhile wait for it.
An I/O object opened that way belongs to the first request. The next request that touches it fails with Cannot perform I/O on behalf of a different request, so a singleton cannot keep a TCP connection on Workers: open it in a request-scoped provider. A binding (env.KV) or a fetch() per call is fine in a singleton.
onDestroy() of a request-scoped provider runs after the response, and on Workers async work that outlives the response is dropped unless it goes through waitUntil() from cloudflare:workers.
AWS Lambda calls its handler with an event, not a Request, so it needs an adapter that turns the event into a Request and the Response back into the result Lambda expects. MiiaJS does not ship one.
shutdownHooks: false is recommended here - the platform manages signals itself, and serverless handlers are short-lived. If you skip the option, no harm done either: signal handlers are only registered in listen(), not in init().