Database Module
Path: apps/backend/src/database/
Type: Global infrastructure module (no endpoints)
Purpose
Provides a singleton Kysely<DB> instance to the entire backend via the DATABASE injection token. This is the only entry point for database access — every repository in the system depends on it.
Architecture
database/
├── database.module.ts # @Global() NestJS module with graceful shutdown
└── infrastructure/
└── database.providers.ts # DATABASE token, KyselyDatabase type, factory provider
How It Works
databaseProvideris a NestJS factory provider that readsDATABASE_URLfromConfigService- It calls
getDatabaseInstance()frompackages/backend/database/which creates apg.Pool+Kysely<DB>instance - The instance is cached by connection string to prevent duplicate pools
DatabaseModuleis@Global()— imported once inAppModule, available everywhere- On shutdown,
onModuleDestroy()callsdb.destroy()to drain the connection pool
Injection Pattern
import { DATABASE, type KyselyDatabase } from "@/database/infrastructure/database.providers";
@Injectable()
export class MyRepository {
constructor(@Inject(DATABASE) private readonly database: KyselyDatabase) {}
}
Connection Pool Configuration
Pool behavior is controlled via environment variables:
| Variable | Default | Description |
|---|---|---|
DB_POOL_MAX | 3 | Max connections per instance |
DB_POOL_MIN | 0 | Min idle connections |
DB_POOL_IDLE_TIMEOUT | 300000 | Idle timeout (ms) |
DB_POOL_CONNECTION_TIMEOUT | 10000 | Acquire timeout (ms) |
DB_POOL_KEEP_ALIVE_DELAY | 5000 | Keep-alive ping interval (ms) |
DB_STATEMENT_TIMEOUT | — | Query timeout (ms) |
DB_POOL_MONITORING | — | Enable pool health logging in production |
See connection-pool-management.md for capacity planning across environments.
Design Decisions
@Global()to avoid importingDatabaseModulein every feature module (115+ modules)- Connection string cache as defensive programming against duplicate pool creation in edge cases
- Graceful shutdown via
OnModuleDestroyto properly drain connections on restart/deploy - No domain/application layers — this is pure infrastructure, not a feature module