Service Providers

Katal utilizes a modular, Laravel-grade Service Provider architecture to organize subsystem initialization, container bindings, and lifecycle management.


1. Overview

Service providers decouple your application's bootstrap logic into self-contained modules. Each provider implements three lifecycle methods: - register(): Bind services, singletons, and configuration into the IoC container. Runs synchronously or asynchronously during app.boot(). - boot(): Boot routes, subscribe to event listeners, or start background polling. Runs after all service providers have executed register(). - shutdown(): Teardown database connections, close sockets, and flush caches on graceful process termination.


2. Built-in Core Service Providers

Katal's internal subsystems are themselves structured as standard service providers, ensuring the Application class remains a pure orchestrator:

Service Provider Lifecycle Phase Responsibility
ConfigServiceProvider Phase 0 Parses cascading .env files, loads config/*.ts, .json, connects global config() facade.
RoutingServiceProvider Phase 1 Configures the dual-tier router ($O(1)$ static table + Radix Trie).
EventServiceProvider Phase 1 Binds the in-process EventBus pub/sub engine.
CacheServiceProvider Phase 1 Configures the cache store and single-flight stampede mutex.
RateLimitServiceProvider Phase 1 Binds atomic sliding-window rate limiters.
QueueServiceProvider Phase 1 Initializes in-memory or Redis Streams queue drivers.
HealthServiceProvider Phase 1 Binds health, readiness, and liveness check registries.
OpenApiServiceProvider Phase 1 Generates OpenAPI 3.1 specifications and mounts Scalar explorer.

3. Creating a Custom Service Provider

import { ServiceProvider } from "katal";

export class DatabaseServiceProvider extends ServiceProvider {
    // 1. Container bindings
    override register(): void {
        this.app.singleton("db", () => {
            return new DatabaseClient({
                host: this.app.getConfig("database.connections.mysql.host"),
                port: this.app.getConfig("database.connections.mysql.port"),
            });
        });
    }

    // 2. Boot phase
    override async boot(): Promise<void> {
        const db = this.app.resolve<DatabaseClient>("db");
        await db.connect();
    }

    // 3. Graceful shutdown
    override async shutdown(): Promise<void> {
        const db = this.app.resolve<DatabaseClient>("db");
        await db.disconnect();
    }
}

4. Registering Providers

Register providers during application setup:

import { Application } from "katal";
import { DatabaseServiceProvider } from "./providers/DatabaseServiceProvider";

const app = new Application({ port: 3000 });

// Register individual provider
app.registerProvider(new DatabaseServiceProvider(app));

// Or register multiple providers simultaneously
app.registerProviders([
    new DatabaseServiceProvider(app),
    new StripeServiceProvider(app),
]);

5. Reverse LIFO Teardown Guarantee

When app.stop() is invoked (or when the process intercepts SIGTERM / SIGINT), Katal executes provider shutdown() hooks in reverse LIFO (Last-In, First-Out) order:

sequenceDiagram
    participant App as Application.stop()
    participant P3 as CustomQueueServiceProvider
    participant P2 as DatabaseServiceProvider
    participant P1 as ConfigServiceProvider

    Note over App: Shutdown commences in reverse order
    App->>P3: 1. shutdown() (stop queue workers)
    App->>P2: 2. shutdown() (close DB connections)
    App->>P1: 3. shutdown() (release config resources)

This ensures that downstream consumers (such as workers and routes) finish processing requests before upstream foundations (such as databases and configuration) are severed.


See Also