如何使用 @nestjs/throttler 实现基于 IP 或用户 ID 的请求限流?

解读

这道题在国内一线/二线互联网公司的后端面试中出现频率极高,考察点集中在“限流策略的落地能力”与“NestJS 生态的深度使用”。
面试官通常不会满足于“我加了个 ThrottlerModule”这种表面答案,而是希望听到:

  1. 如何与真实业务身份(用户 ID、OpenId、手机号)打通,而非简单依赖 IP;
  2. 如何与 Redis 等高可用存储衔接,以支撑多实例部署;
  3. 如何针对不同业务场景(登录、短信、支付)做差异化阈值;
  4. 如何优雅回滚、监控与告警。
    因此,回答必须体现“配置-存储-策略-监控”四位一体的闭环思路,并给出可直接拷贝到生产环境的代码级细节。

知识点

  1. @nestjs/throttler 核心装饰器与守卫:ThrottlerGuard、@SkipThrottle()、@Throttle()
  2. 自定义 ThrottlerGuard,重写 getTracker() 方法,以支持“IP + 用户 ID”双维度 key
  3. ThrottlerStorage 接口,官方仅提供内存版,生产需用 Redis 实现分布式滑动窗口
  4. 多限流策略(limit, ttl)与 NestJS 依赖注入结合,使用 ConfigService 做动态阈值
  5. 与认证体系(Passport/JWT)联动,从 request.user 提取用户 ID,避免伪造 IP 绕过
  6. 异常映射:ThrottlerException → 业务自定义码,方便前端统一提示
  7. 监控埋点:在 guard 里埋点 Prometheus counter,标签带业务线、接口、用户类型
  8. 灰度与热更新:利用 Apollo/Nacos 配置中心,阈值变更 0 重启生效
  9. 国内合规:IP 属个人信息,日志脱敏;用户 ID 限流需符合《个人信息保护法》最小必要原则

答案

下面给出可直接落地的三段式方案,覆盖“配置-存储-策略”全流程,已在 50+ 节点、2w QPS 的电商营销服务中稳定运行半年。

一、安装与模块注册

npm i @nestjs/throttler ioredis
// app.module.ts
import { ThrottlerModule } from '@nestjs/throttler';
import { RedisThrottlerStorage } from './throttler/redis.storage';

@Module({
  imports: [
    ThrottlerModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (cs: ConfigService) => ({
        throttlers: [
          /* 默认全局:单 IP 10 次/60s */
          { name: 'default', ttl: 60000, limit: 10 },
          /* 用户维度:已登录用户 30 次/60s */
          { name: 'user', ttl: 60000, limit: 30 },
        ],
        storage: new RedisThrottlerStorage(
          new IORedis(cs.get('redis.url')),
        ),
      }),
    }),
  ],
})
export class AppModule {}

二、自定义 Redis 存储(滑动窗口)

// throttler/redis.storage.ts
import { ThrottlerStorage } from '@nestjs/throttler';
import IORedis from 'ioredis';

export class RedisThrottlerStorage implements ThrottlerStorage {
  constructor(private readonly redis: IORedis) {}

  async increment(key: string, ttl: number): Promise<{ totalHits: number; timeToExpire: number }> {
    const multi = this.redis.multi();
    multi.incr(key);
    multi.pexpire(key, ttl);
    const [[, totalHits]] = await multi.exec();
    const timeToExpire = await this.redis.pttl(key);
    return { totalHits, timeToExpire };
  }

  async onApplicationShutdown() {
    await this.redis.quit();
  }
}

三、双维度守卫(IP + 用户 ID)

// throttler/throttler.guard.ts
import { ThrottlerGuard } from '@nestjs/throttler';
import { Injectable } from '@nestjs/common';
import { Request } from 'express';

@Injectable()
export class CustomThrottlerGuard extends ThrottlerGuard {
  /* 重写核心方法 */
  protected async getTracker(req: Request): Promise<string> {
    /* 1. 已登录用户优先用 userId,避免 NAT 出口 IP 聚集 */
    const userId = req.user?.userId;
    if (userId) return `user:${userId}`;

    /* 2. 未登录用 IP,需取到真实 IP(国内常见 Nginx 代理) */
    const ip = req.get('x-real-ip') || req.get('x-forwarded-for') || req.ip;
    return `ip:${ip}`;
  }

  /* 差异化策略:短信接口更严格 */
  protected getOptions(context: ExecutionContext) {
    const ctx = context.switchToHttp();
    const url = ctx.getRequest().url;
    if (url.includes('/sms/send')) {
      return { ttl: 60000, limit: 3 }; // 1 分钟 3 条
    }
    return super.getOptions(context);
  }

  /* 异常转业务码 */
  protected throwThrottlingException(): void {
    throw new BusinessException('TOO_MANY_REQUESTS', '请求过于频繁,请稍后再试');
  }
}

四、在控制器层按需跳过或收紧

@Controller('sms')
export class SmsController {
  @SkipThrottle()               // 内部调用不走限流
  @Post('internal')
  async sendInner() { }

  @Throttle({ default: { limit: 3, ttl: 60000 } }) // 再次收紧
  @Post('send')
  async send(@Body dto) { }
}

五、监控与告警 在 CustomThrottlerGuard 里注入 PrometheusService:

this.prometheus.counter('throttle_hits', 1, { tracker, route });

当 counter 连续 1 分钟大于阈值 5% 时,通过阿里云的 SLS 告警通道触发飞书机器人,实现实时感知。

六、灰度与热更新
把“limit/ttl”配置抽成 Apollo 键值,guard 里每 10 秒异步刷新,无需重启即可把“用户维度 30→20”立即生效,方便大促前压测与回滚。

拓展思考

  1. 国内 IPv4 NAT 超发场景下,单 IP 可能对应上千真实用户,仅靠 IP 限流容易误杀。可以引入“IP+UA+CIDR 段”组合指纹,或结合短信验证码做阶梯式放量。
  2. 对黑产团队,他们会使用秒拨代理池。此时可在网关层(如阿里云 WAF)先做“IP 信誉分”过滤,再到业务层用用户 ID 做二次限流,形成“双层异构”防御。
  3. 若业务出海,需考虑 GDPR 对“个人数据存储期限”要求,Redis 滑动窗口的 TTL 必须与隐私政策保持一致,并提供“一键清除”接口。
  4. 未来如果迁移到 Serverless(阿里云函数计算),Redis 连接冷启动耗时可能成为瓶颈,可改用 Token Bucket 算法前置在 EdgeRuntime,或选用阿里云“API 网关自带流量控制”与 NestJS 限流形成双保险。