如何配置不同路由的限流策略(如登录接口每分钟 5 次,普通接口每分钟 100 次)?
解读
国内一线/二线互联网公司在面试 NestJS 后端岗位时,限流(Rate Limiting)几乎是“必答题”。
面试官想确认三件事:
- 你是否知道 NestJS 官方生态里就有
@nestjs/throttler,而不是自己写 Redis 计数器; - 能否把“业务维度”与“框架维度”解耦——登录、注册、短信验证码等敏感接口必须单独限速,而 CURD 接口走通用桶;
- 是否具备“灰度/多租户/集群”意识,例如:
- 用 Redis 而不是单机 Map,否则 K8s 多 Pod 会击穿限流;
- 支持 IP、用户 ID、甚至手机号三维键;
- 能回答“令牌桶”与“固定窗口”在超高并发下的差异。
答不到“Redis+自定义装饰器+动态模块”这一层,通常会被追问“那你单机挂了怎么办”。
知识点
-
@nestjs/throttler核心类- ThrottlerModule.forRootAsync() 提供全局默认限流;
- ThrottlerGuard 是守卫,默认按 IP 做 key;
- @Throttle() 装饰器可覆盖默认限流;
- ThrottlerException 过滤器可统一返回 429 业务码(国内习惯用 200+自定义错误码,也可改)。
-
自定义 ThrottlerGuard 的 key 生成策略
- 登录接口:key =
login:${ip}:${username},防止同一用户名被暴力破解; - 普通接口:key =
api:${ip}即可; - 若公司已有统一网关,需与网关约定“X-Real-IP”头,防止取到 Node 内网 IP。
- 登录接口:key =
-
多维度限流配置
- 默认策略:ttl=60s,limit=100;
- 登录策略:ttl=60s,limit=5;
- 短信策略:ttl=60s,limit=1;
通过@Throttle(limit, ttl)局部覆盖,或自定义@LoginThrottle()装饰器,保持代码语义化。
-
集群持久化
- 使用
throttler-storage-redis包,把计数落到 Redis; - Redis 需开启
maxmemory-policy allkeys-lru,防止 key 过多; - 若公司用腾讯云/阿里云 Redis 5.0,建议把 ttl 设为 70s,留 10s 漂移防止时钟回拨。
- 使用
-
测试与压测
- 单元测试:用
@nestjs/testing构造模块,把 Redis 换成ioredis-mock,验证 5 次后抛 429; - 压测:阿里 PTS 或 JMeter,100 线程 0s 启动,观察 RT 是否陡增、QPS 是否被严格截断在 100。
- 单元测试:用
答案
- 安装依赖
pnpm add @nestjs/throttler ioredis throttler-storage-redis
- 创建动态模块
throttle.module.ts
import { Module } from '@nestjs/common';
import { ThrottlerModule } from '@nestjs/throttler';
import { Redis } from 'ioredis';
import { ThrottlerStorageRedisService } from 'throttler-storage-redis';
@Module({
imports: [
ThrottlerModule.forRootAsync({
useFactory: () => ({
throttlers: [
{ name: 'default', ttl: 60000, limit: 100 }, // 普通接口
{ name: 'login', ttl: 60000, limit: 5 }, // 登录接口
],
storage: new ThrottlerStorageRedisService(new Redis({
host: process.env.REDIS_HOST || '127.0.0.1',
port: Number(process.env.REDIS_PORT) || 6379,
password: process.env.REDIS_PASSWORD,
db: 1,
})),
}),
}),
],
})
export class CustomThrottleModule {}
- 自定义守卫
app.throttler.guard.ts
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { ThrottlerGuard } from '@nestjs/throttler';
import { Reflector } from '@nestjs/core';
@Injectable()
export class AppThrottlerGuard extends ThrottlerGuard {
constructor(options: any, reflector: Reflector) {
super(options, reflector);
}
protected async getTracker(req: Record<string, any>): Promise<string> {
// 优先取用户 ID,未登录取 IP
return req.user?.userId ? `uid:${req.user.userId}` : `ip:${req.ip}`;
}
protected getErrorMessage(): string {
return '请求过于频繁,请稍后再试'; // 中文友好提示
}
}
- 创建自定义装饰器
login-throttle.decorator.ts
import { SetMetadata } from '@nestjs/common';
import { Throttle } from '@nestjs/throttler';
export const LOGIN_THROTTLE_KEY = 'loginThrottle';
export const LoginThrottle = () => {
// 5 次/分钟,使用上面定义的 login 桶
return applyDecorators(
SetMetadata(LOGIN_THROTTLE_KEY, true),
Throttle(5, 60),
);
};
- 在
AuthController使用
@Controller('auth')
export class AuthController {
@Post('login')
@LoginThrottle()
async login(@Body() dto: LoginDto) {
return this.authService.login(dto);
}
}
- 全局启用守卫
main.ts
app.useGlobalGuards(new AppThrottlerGuard(app.get(Reflector)));
- 统一异常返回(可选)
@Catch(ThrottlerException)
export class ThrottleFilter implements ExceptionFilter {
catch(exception: ThrottlerException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse();
response.status(200).json({
code: 429,
message: '请求过于频繁,请稍后再试',
});
}
}
至此,登录接口 5 次/分钟,其余接口 100 次/分钟,集群多 Pod 共享 Redis 计数,符合国内互联网生产标准。
拓展思考
-
多租户 SaaS 场景:
把getTracker改造成tenant:${tenantId}:uid:${userId},防止 A 租户的大客户把 B 租户入口打挂。 -
动态限流:
把限流参数放到配置中心(阿里 Nacos、腾讯 Polaris),利用ThrottlerModule.forRootAsync的useFactory实时刷新,无需重启 Pod。 -
令牌桶算法:
官方默认固定窗口,突发流量会把 100 次瞬间打光;可引入rate-limiter-flexible的 TokenBucket,允许 1000 并发但平均速率 100/s,面试时主动提及会加分。 -
网关双层限流:
国内主流架构是“网关层(OpenResty+lua-resty-limit-req)+业务层(NestJS)”,回答时要强调“网关做粗限流、业务做精限流”,体现全链路思维。 -
审计与告警:
在AppThrottlerGuard里注入 Logger,当触发 429 时写 ELK,同时发送企业微信机器人告警,方便安全团队第一时间封禁 IP 或手机号。