feat: add haproxy load balancer, api replicas and graceful shutdown

This commit is contained in:
2026-11-01 14:50:16 +03:00
parent cdcff89d25
commit e9bc51288b
8 changed files with 103 additions and 8 deletions
+4
View File
@@ -1,6 +1,7 @@
import { Controller, Get } from '@nestjs/common';
import { ApiError } from '../common/filters/api-error';
import { PrismaService } from '../db/prisma.service';
import { isDraining } from './shutdown';
@Controller('health')
export class HealthController {
@@ -13,6 +14,9 @@ export class HealthController {
@Get('ready')
async ready(): Promise<{ status: 'ok' }> {
if (isDraining()) {
throw new ApiError('unavailable', 'shutting down');
}
try {
await this.prisma.$queryRaw`SELECT 1`;
} catch {
+26
View File
@@ -0,0 +1,26 @@
import { INestApplication, Logger } from '@nestjs/common';
let draining = false;
export function isDraining(): boolean {
return draining;
}
export function enableGracefulShutdown(app: INestApplication): void {
const delayMs = Number(process.env.SHUTDOWN_DELAY_MS ?? 3000);
const shutdown = (signal: string): void => {
if (draining) {
return;
}
draining = true;
Logger.log(`${signal}: readiness → 503, closing in ${delayMs} ms`, 'Shutdown');
setTimeout(() => {
app.close().then(
() => process.exit(0),
() => process.exit(1),
);
}, delayMs);
};
process.once('SIGTERM', () => shutdown('SIGTERM'));
process.once('SIGINT', () => shutdown('SIGINT'));
}
+2 -1
View File
@@ -7,6 +7,7 @@ import {
import { AppModule } from './app.module';
import { configureApp } from './configure-app';
import { setupSwagger } from './docs/swagger';
import { enableGracefulShutdown } from './health/shutdown';
async function bootstrap(): Promise<void> {
const app = await NestFactory.create<NestFastifyApplication>(
@@ -19,7 +20,7 @@ async function bootstrap(): Promise<void> {
configureApp(app);
setupSwagger(app);
app.enableShutdownHooks();
enableGracefulShutdown(app);
const host = process.env.APP_HOST ?? '0.0.0.0';
const port = Number(process.env.APP_PORT ?? 8080);