Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(throttler): fail fast and shut down cleanly when the Redis backend is offline (#932)
Yudhi Armyndharise24bbcfb71f6
diff --git a/src/app.module.ts b/src/app.module.tsindex e98a73207..5c3f94c5d 100644--- a/src/app.module.ts+++ b/src/app.module.ts@@ -5,8 +5,8 @@ import * as fs from 'fs';import * as path from 'path';import { TypeOrmModule } from '@nestjs/typeorm';import { ThrottlerModule } from '@nestjs/throttler';-import Redis from 'ioredis';import { RedisThrottlerStorage } from './common/throttler/redis-throttler.storage';+import { createThrottlerRedisClient } from './common/throttler/throttler-redis.client';import configuration from './config/configuration';import { validateEnv } from './config/env.validation';import { SessionModule } from './modules/session/session.module';@@ -241,19 +241,12 @@ if (dashboardServingEnabled && dashboardBuildPresent) {limit: configService.get<number>('api.rateLimit.longLimit', 1000),},];- // Fail-open on Redis error (see RedisThrottlerStorage), so a Redis outage never blocks the API.+ // Fail-open on Redis error (see RedisThrottlerStorage), so a Redis outage never blocks the+ // API. The client is built fail-fast (see throttler-redis.client.ts) so that fail-open+ // engages immediately instead of after a queue/timeout stall per request.const redisStorage =process.env.REDIS_ENABLED === 'true'- ? new RedisThrottlerStorage(- new Redis({- host: configService.get<string>('redis.host', 'localhost'),- port: configService.get<number>('redis.port', 6379),- username: configService.get<string>('redis.username'),- password: configService.get<string>('redis.password'),- connectTimeout: configService.get<number>('redis.connectTimeoutMs', 5000),- maxRetriesPerRequest: 3,- }),- )+ ? new RedisThrottlerStorage(createThrottlerRedisClient(configService)): undefined;return { throttlers, ...(redisStorage ? { storage: redisStorage } : {}) };},diff --git a/src/common/throttler/redis-throttler.storage.lifecycle.spec.ts b/src/common/throttler/redis-throttler.storage.lifecycle.spec.tsnew file mode 100644index 000000000..12a38a23f--- /dev/null+++ b/src/common/throttler/redis-throttler.storage.lifecycle.spec.ts@@ -0,0 +1,32 @@+import { Test } from '@nestjs/testing';+import { ThrottlerStorage } from '@nestjs/throttler';+import { RedisThrottlerStorage } from './redis-throttler.storage';+import type { Redis } from 'ioredis';++describe('RedisThrottlerStorage lifecycle wiring', () => {+ it('Nest invokes onModuleDestroy on the storage instance registered via a factory provider', async () => {+ const redis = {+ eval: jest.fn(),+ on: jest.fn(),+ quit: jest.fn().mockResolvedValue('OK'),+ disconnect: jest.fn(),+ };+ const storage = new RedisThrottlerStorage(redis as unknown as Redis);++ // Mirror @nestjs/throttler's ThrottlerStorageProvider: a useFactory returning options.storage.+ const moduleRef = await Test.createTestingModule({+ providers: [+ { provide: 'THROTTLER_OPTIONS', useValue: { storage } },+ {+ provide: ThrottlerStorage,+ useFactory: (options: { storage: RedisThrottlerStorage }) => options.storage,+ inject: ['THROTTLER_OPTIONS'],+ },+ ],+ }).compile();++ await moduleRef.close();+ expect(redis.quit).toHaveBeenCalledTimes(1);+ expect(redis.disconnect).toHaveBeenCalledTimes(1);+ });+});diff --git a/src/common/throttler/redis-throttler.storage.spec.ts b/src/common/throttler/redis-throttler.storage.spec.tsindex ab6ad8bb5..5ab7972fd 100644--- a/src/common/throttler/redis-throttler.storage.spec.ts+++ b/src/common/throttler/redis-throttler.storage.spec.ts@@ -1,10 +1,13 @@-import { RedisThrottlerStorage } from './redis-throttler.storage';+import { RedisThrottlerStorage, THROTTLER_REDIS_QUIT_TIMEOUT_MS } from './redis-throttler.storage';import type { Redis } from 'ioredis';-type MockRedis = { eval: jest.Mock };+type MockRedis = { eval: jest.Mock; on: jest.Mock; quit: jest.Mock; disconnect: jest.Mock };const makeRedis = (opts: { hits: number; ttlMs: number }): MockRedis => ({eval: jest.fn().mockResolvedValue([opts.hits, opts.ttlMs]),+ on: jest.fn(),+ quit: jest.fn().mockResolvedValue('OK'),+ disconnect: jest.fn(),});describe('RedisThrottlerStorage', () => {@@ -52,4 +55,60 @@ describe('RedisThrottlerStorage', () => {const rec = await new RedisThrottlerStorage(redis as unknown as Redis).increment('k', 1000, 10, 60000, 'short');expect(rec).toEqual({ totalHits: 0, timeToExpire: 0, isBlocked: false, timeToBlockExpire: 0 });});++ it('fails open FAST when the client rejects while disconnected (no queue/timeout stall)', async () => {+ const redis = makeRedis({ hits: 1, ttlMs: 1000 });+ // The exact rejection ioredis produces with enableOfflineQueue:false — issued commands must not+ // wait for reconnect; the request is decided on the fail-open path immediately.+ redis.eval.mockRejectedValue(new Error("Stream isn't writeable and enableOfflineQueue options is false"));+ const storage = new RedisThrottlerStorage(redis as unknown as Redis);+ const result = await Promise.race([+ storage.increment('k', 1000, 10, 60000, 'short'),+ new Promise<'slow'>(resolve => setTimeout(() => resolve('slow'), 100)),+ ]);+ expect(result).toEqual({ totalHits: 0, timeToExpire: 0, isBlocked: false, timeToBlockExpire: 0 });+ });++ it('attaches an error listener so connection failures surface as structured logs, never unhandled events', () => {+ const redis = makeRedis({ hits: 1, ttlMs: 1000 });+ new RedisThrottlerStorage(redis as unknown as Redis);+ expect(redis.on).toHaveBeenCalledWith('error', expect.any(Function));+ const calls = redis.on.mock.calls as Array<[string, (error: Error) => void]>;+ const errorCall = calls.find(([event]) => event === 'error');+ expect(errorCall).toBeDefined();+ const listener = errorCall![1];+ expect(() => listener(new Error('ECONNREFUSED'))).not.toThrow();+ });++ it('onModuleDestroy drains the client with quit() and always disconnects the socket', async () => {+ const redis = makeRedis({ hits: 1, ttlMs: 1000 });+ await new RedisThrottlerStorage(redis as unknown as Redis).onModuleDestroy();+ expect(redis.quit).toHaveBeenCalledTimes(1);+ expect(redis.disconnect).toHaveBeenCalledTimes(1);+ });++ it('onModuleDestroy still disconnects when quit() rejects (client already offline)', async () => {+ const redis = makeRedis({ hits: 1, ttlMs: 1000 });+ // With enableOfflineQueue:false a quit() issued mid-outage rejects instantly WITHOUT closing the+ // socket — teardown must not propagate that rejection nor skip the disconnect.+ redis.quit.mockRejectedValue(new Error("Stream isn't writeable and enableOfflineQueue options is false"));+ const storage = new RedisThrottlerStorage(redis as unknown as Redis);+ await expect(storage.onModuleDestroy()).resolves.toBeUndefined();+ expect(redis.disconnect).toHaveBeenCalledTimes(1);+ });++ it('onModuleDestroy does not hang when quit() never settles (deadline, then force disconnect)', async () => {+ jest.useFakeTimers();+ try {+ const redis = makeRedis({ hits: 1, ttlMs: 1000 });+ redis.quit.mockReturnValue(new Promise(() => undefined)); // half-open socket: QUIT never answered+ const storage = new RedisThrottlerStorage(redis as unknown as Redis);+ const destroy = storage.onModuleDestroy();+ await jest.advanceTimersByTimeAsync(THROTTLER_REDIS_QUIT_TIMEOUT_MS);+ await destroy;+ expect(redis.disconnect).toHaveBeenCalledTimes(1);+ } finally {+ jest.useRealTimers();+ }+ });});diff --git a/src/common/throttler/redis-throttler.storage.ts b/src/common/throttler/redis-throttler.storage.tsindex eec6072a8..6776296de 100644--- a/src/common/throttler/redis-throttler.storage.ts+++ b/src/common/throttler/redis-throttler.storage.ts@@ -1,8 +1,11 @@-import { Injectable } from '@nestjs/common';+import { Injectable, OnModuleDestroy } from '@nestjs/common';import type { Redis } from 'ioredis';import { ThrottlerStorage } from '@nestjs/throttler';import { createLogger } from '../services/logger.service';+/** Max time to await a graceful `redis.quit()` on shutdown before force-disconnecting (see onModuleDestroy). */+export const THROTTLER_REDIS_QUIT_TIMEOUT_MS = 2000;+/** The 4-field record @nestjs/throttler's guard reads (not re-exported from the package root). */interface ThrottlerRecord {totalHits: number;@@ -37,12 +40,47 @@ return {hits, ttl}* conventions are SECONDS — so the values here are ceil(ms / 1000), matching the default in-memory* storage. Fail-OPEN on Redis error: rate limiting is a secondary control, and fail-closed would* self-DoS the gateway (every request 500s on the storage call).+ *+ * This class owns the client lifecycle: it is registered as the `ThrottlerStorage` provider by+ * @nestjs/throttler (its ThrottlerStorageProvider returns the configured instance), so Nest invokes+ * onModuleDestroy on it at shutdown.*/@Injectable()-export class RedisThrottlerStorage implements ThrottlerStorage {+export class RedisThrottlerStorage implements ThrottlerStorage, OnModuleDestroy {private readonly logger = createLogger('RedisThrottlerStorage');- constructor(private readonly redis: Redis) {}+ constructor(private readonly redis: Redis) {+ // An ioredis client with no 'error' listener reports every connection failure via an unstructured+ // console dump; log it through the structured logger instead. Never rethrow — the client keeps+ // reconnecting in the background and increment() already fails open per request.+ this.redis.on('error', (error: Error) => {+ this.logger.warn('Throttler Redis client error', { error: error.message });+ });+ }++ async onModuleDestroy(): Promise<void> {+ const redis = this.redis;++ // Bound the teardown: redis.quit() waits for the QUIT reply, which never arrives on a half-open /+ // partitioned socket — leaving app.close() blocked until the orchestrator SIGKILLs the process.+ // Race a graceful QUIT (drain, not a hard cut) against a short deadline so shutdown proceeds.+ let timer: NodeJS.Timeout | undefined;+ const deadline = new Promise<void>(resolve => {+ timer = setTimeout(resolve, THROTTLER_REDIS_QUIT_TIMEOUT_MS);+ timer.unref();+ });++ try {+ await Promise.race([redis.quit().catch(() => undefined), deadline]);+ } finally {+ if (timer) clearTimeout(timer);+ // Always release the socket. With enableOfflineQueue:false and the client mid-reconnect, quit()+ // rejects instantly WITHOUT closing it — so ioredis's reconnect timer would outlive teardown.+ // disconnect() is idempotent, so calling it after a clean quit is harmless; this guarantees no+ // live handle survives onModuleDestroy regardless of connection state.+ redis.disconnect();+ }+ }async increment(key: string,diff --git a/src/common/throttler/throttler-redis.client.spec.ts b/src/common/throttler/throttler-redis.client.spec.tsnew file mode 100644index 000000000..9565e7956--- /dev/null+++ b/src/common/throttler/throttler-redis.client.spec.ts@@ -0,0 +1,68 @@+import { ConfigService } from '@nestjs/config';+import {+ buildThrottlerRedisOptions,+ createThrottlerRedisClient,+ THROTTLER_REDIS_COMMAND_TIMEOUT_MS,+} from './throttler-redis.client';++const makeConfig = (values: Record<string, unknown>): ConfigService =>+ ({+ get: jest.fn((key: string, fallback?: unknown) => values[key] ?? fallback),+ }) as unknown as ConfigService;++describe('buildThrottlerRedisOptions', () => {+ it('maps the redis.* config keys onto the client', () => {+ const options = buildThrottlerRedisOptions(+ makeConfig({+ 'redis.host': 'redis.internal',+ 'redis.port': 6380,+ 'redis.username': 'throttler',+ 'redis.password': 'secret',+ 'redis.connectTimeoutMs': 3000,+ }),+ );+ expect(options).toMatchObject({+ host: 'redis.internal',+ port: 6380,+ username: 'throttler',+ password: 'secret',+ connectTimeout: 3000,+ });+ });++ it('falls back to localhost defaults', () => {+ const options = buildThrottlerRedisOptions(makeConfig({}));+ expect(options).toMatchObject({ host: 'localhost', port: 6379, connectTimeout: 5000 });+ });++ it('fails fast instead of queueing or replaying commands across an outage', () => {+ const options = buildThrottlerRedisOptions(makeConfig({}));+ // Commands issued while disconnected reject immediately so the storage's fail-open path+ // engages per request — no offline-queue stall, no post-recovery replay of queued evals.+ expect(options.enableOfflineQueue).toBe(false);+ // An eval in flight when the socket dies is never resent: the INCR is not idempotent, so a+ // resend could double-count or land in a fresh window.+ expect(options.autoResendUnfulfilledCommands).toBe(false);+ // Every command is deadline-bounded, so a dropped in-flight call cannot hang the request.+ expect(options.commandTimeout).toBe(THROTTLER_REDIS_COMMAND_TIMEOUT_MS);+ // No queue-based retry flushing — per-command latency is bounded by commandTimeout alone.+ expect(options.maxRetriesPerRequest).toBeNull();+ });+});++describe('createThrottlerRedisClient', () => {+ it('passes the fail-fast options through to the ioredis constructor', () => {+ const client = createThrottlerRedisClient(makeConfig({ 'redis.host': '127.0.0.1' }));+ try {+ expect(client.options.enableOfflineQueue).toBe(false);+ expect(client.options.autoResendUnfulfilledCommands).toBe(false);+ expect(client.options.commandTimeout).toBe(THROTTLER_REDIS_COMMAND_TIMEOUT_MS);+ expect(client.options.maxRetriesPerRequest).toBeNull();+ expect(client.options.host).toBe('127.0.0.1');+ } finally {+ // Stop the eager connect/reconnect loop so the test leaves no live handle behind.+ client.on('error', () => undefined);+ client.disconnect();+ }+ });+});diff --git a/src/common/throttler/throttler-redis.client.ts b/src/common/throttler/throttler-redis.client.tsnew file mode 100644index 000000000..3989502f9--- /dev/null+++ b/src/common/throttler/throttler-redis.client.ts@@ -0,0 +1,46 @@+import { ConfigService } from '@nestjs/config';+import Redis, { RedisOptions } from 'ioredis';++/**+ * Upper bound for one throttler command. The storage fails OPEN on command error, so a bounded+ * rejection is how a slow/partitioned Redis degrades to "allow" instead of stalling the request.+ * It also settles commands ioredis drops on reconnect (autoResendUnfulfilledCommands: false below),+ * which would otherwise never resolve.+ */+export const THROTTLER_REDIS_COMMAND_TIMEOUT_MS = 2000;++/**+ * Client options for the throttler's Redis backend, tuned so the fail-open posture of+ * RedisThrottlerStorage engages IMMEDIATELY instead of after a stall:+ *+ * - enableOfflineQueue: false — a command issued while disconnected rejects at once+ * ("Stream isn't writeable...") rather than sitting in the offline queue until reconnect.+ * The default (queue + flush on recovery) both stalls every request for seconds and replays+ * the non-idempotent INCR evals late, corrupting the fixed-window counts.+ * - autoResendUnfulfilledCommands: false — an eval in flight when the socket dies is NOT resent+ * after reconnect: a resent INCR can double-count (if it already ran server-side) or land in a+ * fresh window. Dropping it is safe because commandTimeout settles the awaiting caller.+ * - commandTimeout — per-command deadline covering the two cases above (dropped in-flight+ * commands never settle on their own) plus a live-but-slow Redis.+ * - maxRetriesPerRequest: null — disables ioredis's periodic pending-queue flush; with the+ * offline queue disabled there is nothing to flush, and per-command latency is bounded by+ * commandTimeout instead of a retry counter.+ */+export function buildThrottlerRedisOptions(configService: ConfigService): RedisOptions {+ return {+ host: configService.get<string>('redis.host', 'localhost'),+ port: configService.get<number>('redis.port', 6379),+ username: configService.get<string>('redis.username'),+ password: configService.get<string>('redis.password'),+ connectTimeout: configService.get<number>('redis.connectTimeoutMs', 5000),+ enableOfflineQueue: false,+ autoResendUnfulfilledCommands: false,+ commandTimeout: THROTTLER_REDIS_COMMAND_TIMEOUT_MS,+ maxRetriesPerRequest: null,+ };+}++/** Dedicated client for throttler hit-count storage — separate from cache/queue clients. */+export function createThrottlerRedisClient(configService: ConfigService): Redis {+ return new Redis(buildThrottlerRedisOptions(configService));+}