Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(throttler): optional Redis-backed rate-limit storage (REDIS_ENABLED) (#722)
Yudhi Armyndharis9fe4f673bb0c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2d39e0b88..d98affe24 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -112,6 +112,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0`common/utils` (it has no engine-specific logic), so the webhook module no longer imports across theengine boundary.+- **Optional Redis-backed rate-limit storage.** When `REDIS_ENABLED=true`, API rate-limit counters+ now persist to Redis (a new `RedisThrottlerStorage` implementing @nestjs/throttler v6's+ `ThrottlerStorage`), so limits aggregate across replicas behind a load balancer instead of being+ per-process. Default off (single-node deployments gain nothing and it adds a connection dependency).+ Fail-OPEN on Redis error — rate limiting is a secondary control, and fail-closed would self-DoS the+ API.+### Fixed- **Silent delivery failure for 1:1 Baileys sends to LID-migrated contacts (ack 463).** On thediff --git a/src/app.module.ts b/src/app.module.tsindex 43e794beb..18cdfa693 100644--- a/src/app.module.ts+++ b/src/app.module.ts@@ -5,6 +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 configuration from './config/configuration';import { validateEnv } from './config/env.validation';import { SessionModule } from './modules/session/session.module';@@ -211,12 +213,14 @@ if (dashboardServingEnabled && dashboardBuildPresent) {},}),- // Rate limiting+ // Rate limiting. When REDIS_ENABLED, the hit-count storage moves to Redis so limits aggregate+ // across replicas; otherwise the default in-memory (per-process) storage is used. Default off —+ // a single-node deployment gains nothing from Redis storage, and it adds a connection dep.ThrottlerModule.forRootAsync({imports: [ConfigModule],inject: [ConfigService],- useFactory: (configService: ConfigService) => ({- throttlers: [+ useFactory: (configService: ConfigService) => {+ const throttlers = [{name: 'short',ttl: configService.get<number>('api.rateLimit.shortTtl', 1000),@@ -232,8 +236,23 @@ if (dashboardServingEnabled && dashboardBuildPresent) {ttl: configService.get<number>('api.rateLimit.longTtl', 3600000),limit: configService.get<number>('api.rateLimit.longLimit', 1000),},- ],- }),+ ];+ // Fail-open on Redis error (see RedisThrottlerStorage), so a Redis outage never blocks the API.+ 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,+ }),+ )+ : undefined;+ return { throttlers, ...(redisStorage ? { storage: redisStorage } : {}) };+ },}),// Core modulesdiff --git a/src/common/throttler/redis-throttler.storage.spec.ts b/src/common/throttler/redis-throttler.storage.spec.tsnew file mode 100644index 000000000..79ae7b3f1--- /dev/null+++ b/src/common/throttler/redis-throttler.storage.spec.ts@@ -0,0 +1,47 @@+import { RedisThrottlerStorage } from './redis-throttler.storage';+import type { Redis } from 'ioredis';++type MockRedis = { incr: jest.Mock; pexpire: jest.Mock; pttl: jest.Mock };++const makeRedis = (opts: { hits: number; ttlMs: number }): MockRedis => ({+ incr: jest.fn().mockResolvedValue(opts.hits),+ pexpire: jest.fn().mockResolvedValue(1),+ pttl: jest.fn().mockResolvedValue(opts.ttlMs),+});++describe('RedisThrottlerStorage', () => {+ it('first hit (incr=1): sets the TTL once, reports totalHits + remaining time in seconds, not blocked', async () => {+ const redis = makeRedis({ hits: 1, ttlMs: 1500 });+ const rec = await new RedisThrottlerStorage(redis as unknown as Redis).increment(+ '1.2.3.4',+ 1000,+ 10,+ 60000,+ 'short',+ );+ expect(redis.incr).toHaveBeenCalledWith('openwa:throttle:short:1.2.3.4');+ expect(redis.pexpire).toHaveBeenCalledWith('openwa:throttle:short:1.2.3.4', 1000);+ expect(rec).toEqual({ totalHits: 1, timeToExpire: 2, isBlocked: false, timeToBlockExpire: 0 });+ });++ it('subsequent hit (incr>1) does NOT re-set the TTL (inherits the window from the first hit)', async () => {+ const redis = makeRedis({ hits: 3, ttlMs: 800 });+ await new RedisThrottlerStorage(redis as unknown as Redis).increment('k', 1000, 10, 60000, 'short');+ expect(redis.pexpire).not.toHaveBeenCalled();+ });++ it('over the limit (incr>limit) is blocked with blockDuration in seconds', async () => {+ const redis = makeRedis({ hits: 11, ttlMs: 500 });+ const rec = await new RedisThrottlerStorage(redis as unknown as Redis).increment('k', 1000, 10, 60000, 'short');+ expect(rec.isBlocked).toBe(true);+ expect(rec.totalHits).toBe(11);+ expect(rec.timeToBlockExpire).toBe(60); // 60000ms / 1000+ });++ it('fails OPEN on a Redis error (returns a non-blocking record so the limiter never self-DoSes)', async () => {+ const redis = makeRedis({ hits: 1, ttlMs: 1000 });+ redis.incr.mockRejectedValue(new Error('ECONNREFUSED'));+ 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 });+ });+});diff --git a/src/common/throttler/redis-throttler.storage.ts b/src/common/throttler/redis-throttler.storage.tsnew file mode 100644index 000000000..139330980--- /dev/null+++ b/src/common/throttler/redis-throttler.storage.ts@@ -0,0 +1,58 @@+import { Injectable } from '@nestjs/common';+import type { Redis } from 'ioredis';+import { ThrottlerStorage } from '@nestjs/throttler';+import { createLogger } from '../services/logger.service';++/** The 4-field record @nestjs/throttler's guard reads (not re-exported from the package root). */+interface ThrottlerRecord {+ totalHits: number;+ timeToExpire: number;+ isBlocked: boolean;+ timeToBlockExpire: number;+}++/**+ * Redis-backed ThrottlerStorage for @nestjs/throttler v6 — persists hit counts to Redis so rate+ * limits aggregate across replicas (behind a load balancer) instead of being per-process.+ *+ * The guard sets `Retry-After: timeToBlockExpire` and `RateLimit-Reset: timeToExpire` — both HTTP+ * 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).+ */+@Injectable()+export class RedisThrottlerStorage implements ThrottlerStorage {+ private readonly logger = createLogger('RedisThrottlerStorage');++ constructor(private readonly redis: Redis) {}++ async increment(+ key: string,+ ttl: number,+ limit: number,+ blockDuration: number,+ throttlerName: string,+ ): Promise<ThrottlerRecord> {+ const redisKey = `openwa:throttle:${throttlerName}:${key}`;+ try {+ const hits = await this.redis.incr(redisKey);+ if (hits === 1) {+ // First hit in the window sets the TTL; subsequent hits inherit it (fixed window from first hit).+ await this.redis.pexpire(redisKey, ttl);+ }+ const ttlMs = await this.redis.pttl(redisKey);+ const isBlocked = hits > limit;+ return {+ totalHits: hits,+ timeToExpire: Math.ceil(ttlMs / 1000),+ isBlocked,+ timeToBlockExpire: isBlocked ? Math.ceil(blockDuration / 1000) : 0,+ };+ } catch (error) {+ this.logger.warn('Redis throttler storage failed; failing OPEN (allowing)', {+ error: error instanceof Error ? error.message : String(error),+ });+ return { totalHits: 0, timeToExpire: 0, isBlocked: false, timeToBlockExpire: 0 };+ }+ }+}