alata.
Architecture Concepts

Service Providers

Bootstrap every part of your application through providers and their lifecycle hooks.

Service providers are the units of bootstrapping in Alata. Each provider binds its services into the container, then participates in the shared boot lifecycle — the framework's database engines, cache, queue broker, and health endpoints are all wired this way, and your own services should be too.

Anatomy of a provider

A provider subclasses ServiceProvider and overrides only the hooks it needs.

app/providers/http_client_provider.py
import httpx

from alata.support.service_provider import ServiceProvider


class HttpClientProvider(ServiceProvider):
    def register(self) -> None:
        self._client = httpx.AsyncClient(timeout=10.0)
        self.app.instance("http_client", self._client)

    async def async_boot(self) -> None:
        if self._client.is_closed:
            self._client = httpx.AsyncClient(timeout=10.0)
            self.app.instance("http_client", self._client)

    async def shutdown(self) -> None:
        client = getattr(self, "_client", None)
        if client is not None and not client.is_closed:
            await client.aclose()

Every provider is constructed with the application kernel, available as self.app — which is also the container, so self.app.singleton(...), self.app.make(...), and friends all work directly. An optional second constructor argument lands on self.config.

The lifecycle hooks

The application lifecycle calls the hooks in a fixed order across all providers: every provider registers before any provider boots.

register()

The binding phase. Put services into the container — and nothing else.

def register(self) -> None:
    self.app.singleton("mailer", lambda: Mailer())

Three rules keep registration predictable:

  1. Do not resolve other services. Other providers may not have registered yet, and the container enforces this — self.app.make() raises RuntimeError during this phase. The only exception is pre-built instance bindings, notably the Phase-0 "config" and "settings", which are always safe to read:

    def register(self) -> None:
        connections = self.app.make("config").get("redis.connections", {})
  2. Create objects eagerly if boot() or async_boot() depends on them. A lazy factory has not run by the time boot() executes, so provider state it would have set does not exist yet.

  3. Factory closures must be pure — they must not write back to self:

    # Wrong — lazy factory with side effects on self
    self.app.singleton("x", self._create_x)   # sets self._x inside
    
    # Correct — eager, pure
    obj = self._create_x()
    self.app.singleton("x", lambda: obj)

boot()

Runs after all providers have registered, so every container binding is available via self.app.make(). Wire event listeners, include routers, configure resolved services:

def boot(self) -> None:
    dispatcher = self.app.make("events")
    dispatcher.listen(OrderShipped, SendShipmentNotification)

boot() is synchronous — async work belongs in the next hook.

async_boot()

Runs inside the FastAPI lifespan at server startup, so an event loop is guaranteed. Use it for opening async connection pools, awaiting one-time setup calls, or any I/O-bound initialization that cannot be done synchronously.

async def async_boot(self) -> None:
    await self.app.make("search_index").connect()

Objects you initialize in async_boot() must already exist — create them in register(). And since async_boot() only runs when the lifespan starts, code paths that never start a server (a one-off console command, for instance) will not have run it.

boot_http(app)

Runs only when an HTTP kernel is attached, and receives the FastAPI application instance. Mount routes, add middleware, or hook startup events:

def boot_http(self, app) -> None:
    from alata.http import APIRouter

    router = APIRouter(tags=["reports"])

    @router.get("/reports/summary")
    async def summary():
        return {"status": "ok"}

    app.include_router(router)

This is exactly how the framework's health provider mounts /health without any code in your project. Console commands and queue workers never trigger this phase.

shutdown()

Async graceful teardown, called from the lifespan on server shutdown — in reverse registration order, so services close after everything that depends on them. Close connections, flush buffers, release resources:

async def shutdown(self) -> None:
    client = getattr(self, "_client", None)
    if client is not None and not client.is_closed:
        await client.aclose()

For resources your provider owns, make cleanup safe after incomplete startup or repeated shutdown. Prepare them again in async_boot() if the application starts another lifespan, as in the HTTP client example above.

commands()

Providers are also how console commands reach the ./alata CLI. The primary path under the application kernel is self.app.add_commands([...]) in register() — the framework's own database provider registers the migrate family this way:

def register(self) -> None:
    self.app.add_commands([SyncCatalogCommand, PruneReportsCommand])

Providers can additionally expose a commands() hook returning a list of commands; the console kernel discovers and registers these when assembling the command set:

def commands(self) -> list:
    return [SyncCatalogCommand, PruneReportsCommand]

Registering your provider

Providers are declared in two places in a scaffolded project.

bootstrap/providers.py holds the ordered lists the kernel loads:

bootstrap/providers.py
FRAMEWORK_PROVIDERS = [
    RedisProvider,
    EventProvider,
    QueueProvider,
    CacheProvider,
    HealthProvider,
    StorageProvider,
]

PROVIDERS = [
    # Add your application providers here:
    "app.providers.http_client_provider",
]

Entries can be provider classes or module-path strings; a string module is imported and its Provider class instantiated. Order matters — lists execute top to bottom, and PROVIDERS runs after the framework tier, so your providers can resolve framework services in their boot().

bootstrap/application.py then passes everything to the kernel:

bootstrap/application.py
app = Application(
    base_path=Path(__file__).parent.parent,
    providers=[
        DatabaseProvider,
        CommandProvider,
        *FRAMEWORK_PROVIDERS,
        *PROVIDERS,
        FastapiProvider,
    ],
)

Dropping a *_provider.py file into app/providers/ does not auto-load it. The kernel scans that directory at boot and logs a warning for any provider file not declared in bootstrap/providers.py, but it will not run it — registration is always explicit.

Scaffolding with make:provider

The console can generate and register a provider in one step:

./alata make:provider Payment

This creates app/providers/payment_provider.py from a stub and appends "app.providers.payment_provider" to the PROVIDERS list in bootstrap/providers.py. If the file or the entry already exists, the command tells you and leaves things alone.

Deferred providers

Boot should be cheap: register() binds closures, and nothing connects until something resolves the binding. A console command then touches only what it uses — db:seed resolves the database and nothing else, so an outage elsewhere cannot block it.

For an expensive client (an SDK that does I/O on import, a connection pool, a large model), make that laziness structural. A deferred provider is not instantiated at boot; it loads the first time one of its bindings is resolved:

app/providers/search_client_provider.py
class Provider(ServiceProvider):
    defer = True
    provides = ["search_client"]

    def register(self) -> None:
        self.app.singleton("search_client", self._build_client)

The first container.make("search_client") runs register() (under the same Phase-1 rules as boot) then boot(), then resolves. Loading happens once, is safe under concurrent first resolves, and the loaded provider joins the normal shutdown() order.

The load is synchronous and holds the container's resolve lock, so keep it cheap — or, in a serving process, warm it before readiness from an eager provider's async_boot(): await asyncio.to_thread(container.make, "search_client"). Otherwise the first request that needs the client stalls that worker's event loop for every concurrent request.

What a deferred provider may not do

Deferral is for expensive optional clients, not for infrastructure the whole process needs. A deferred provider may not:

RestrictionWhy
Register console commands./alata list runs before anything resolves — the commands would be invisible
Subscribe event listenersA provider that never loads never subscribes
Override async_boot() or boot_http()Those phases have already passed at lazy-load time
Declare defer = True with empty providesNothing could ever trigger the load

Each raises at boot, naming the provider — except listener subscription, which nothing can detect statically; that one is a convention you own.

Async services and deferral

Deferred load is synchronous, and that covers almost every async client: redis.asyncio.Redis(...), create_async_engine(...), httpx.AsyncClient(...) all construct without a loop and connect on first await.

The rare service whose startup itself is a coroutine initializes on first await instead. alata.support.async_startup.AsyncStartup packages the race-free version:

from alata.support.async_startup import AsyncStartup


class SearchClient(AsyncStartup):
    async def _startup(self) -> None:
        await self._pool.connect()

    async def query(self, text: str):
        await self._ensure_started()   # runs _startup() exactly once
        ...

Deferral trades boot-time failure for first-use failure: a misconfigured client surfaces on the first request that resolves it. Point the readiness probe at an endpoint that resolves the bindings your deployment depends on.

Built-in providers

The class-based kernel boots configuration and logging for every application without them being listed anywhere; a scaffolded project wires DatabaseProvider explicitly in bootstrap/application.py, ahead of everything else. The rest ship in the scaffold's FRAMEWORK_PROVIDERS list, so you can reorder or remove them (carefully — order is significant, e.g. cache wraps the redis clients).

ProviderImportWhat it binds / does
Logalata.providers.log_providerBinds the "log" manager (with LogManager type-mapped for @inject) and configures the root logger; always loads first.
Databasealata.providers.database_providerConfigures database connections, binds "engine" and "migrator", and registers database commands.
Redisalata.providers.redis_providerBinds "redis.<name>" and "redis.<name>.async" clients for each configured connection.
Eventsalata.providers.event_providerBinds the "events" dispatcher singleton for event → listener mappings.
Queuealata.providers.queue_providerBinds the "queue.broker" singleton — the broker workers and task definitions resolve.
Cachealata.providers.cache_providerBinds "cache" (redis-backed store, falling back to a null store when Redis is unavailable) and "cache.null".
Healthalata.providers.health_providerNo bindings; mounts /health, /health/db, and /health/metrics during HTTP boot.
Storagealata.providers.storage_providerBinds "storage" with the local-file and S3 drivers configured under filesystem.disks.
FastAPIalata.http (FastapiProvider)Builds the FastAPI kernel with the async lifecycle wired into its lifespan, attaches it to the application, and registers the maintenance-mode up/down commands.

The scaffolded project extends FastapiProvider in app/providers/fastapi_provider.py to layer on middleware (CORS, gzip, trusted hosts, request logging, maintenance mode) and include your API routes — a good example of subclassing a framework provider rather than replacing it.

Hook order at a glance

HookSync/asyncWhenRuns for
register()syncKernel construction, Phase 1Every entry point
boot()syncKernel construction, after all registrationsEvery entry point
boot_http(app)syncKernel construction, HTTP kernel attachedHTTP only
async_boot()asyncLifespan startupHTTP server (and anything driving the lifespan)
shutdown()asyncLifespan teardown, reverse orderHTTP server (and anything driving the lifespan)
commands()syncConsole kernel buildCLI

For the full picture of when each phase fires — including the mermaid boot-sequence diagram — see the application lifecycle.

On this page