如何在限流触发时返回友好的错误响应,并记录攻击行为?
解读
国内一线/二线互联网公司面试时,限流(Rate Limiting)不仅是“加几行 Redis 计数器”那么简单,而是会追问:
- 触发限流时,如何给前端返回符合国内监管要求的“标准错误”?
- 如何把疑似攻击行为沉淀为可审计、可告警、可溯源的日志?
- 代码层面如何与 NestJS 的 IoC、异常过滤器、拦截器、装饰器体系无缝结合,做到“业务代码零侵入”?
面试官想看到的是:你能在框架层面给出“工程化、可落地、可灰度、可回滚”的完整方案,而不是贴一段 express-rate-limit 的配置。
知识点
- NestJS 异常层:ExceptionFilter 优先级、继承 BaseExceptionFilter、HttpException 子类化。
- 装饰器 + 元数据:自定义
@RateLimit()装饰器,利用Reflector在运行时读取控制器元数据。 - 守卫(Guard)与拦截器(Interceptor)区别:限流判断放 Guard,日志落库放 Interceptor,职责单一。
- Redis + Lua 脚本:保证
INCR + EXPIRE原子性,防止并发竞态;KEY 格式满足“等保 2.0”溯源要求:{api}:{uid|ip}:{yyyyMMddHH}。 - 日志规范:必须打印
traceId(Snowflake)、uid(若已登录)、X-Real-IP、X-Forwarded-For、User-Agent、timestamp、apiPath、limitConfig,并写入 ELK 或阿里云 SLS,方便后续做威胁狩猎。 - 错误码:遵循国内“REST+业务码”双码模式,例如
429-10001=“请求过于频繁,请 60 秒后重试”,并返回Retry-After响应头。 - 配置热更新:使用
nest/config+ 阿波罗/Consul,支持按路由、按用户维度动态调整阈值。 - 测试策略:单元测试(Jest)+ 集成测试(SuperTest)+ Chaos 压测,确保在 5wQPS 下 Redis 延迟 p99 < 5ms。
答案
下面给出可直接落地的“三步走”代码骨架,全部用 TypeScript 编写,符合 NestJS 风格,可直接放入 monorepo 的 libs/rate-limit 目录。
步骤 1:定义领域异常
export class RateLimitException extends HttpException {
constructor(public readonly retryAfterSeconds: number) {
super(
{
code: 10001,
message: '请求过于频繁,请稍后重试',
retryAfter: retryAfterSeconds,
},
HttpStatus.TOO_MANY_REQUESTS,
);
}
}
步骤 2:自定义装饰器,支持类级别与方法级别混用
export const RATE_LIMIT_KEY = 'rate_limit';
export interface RateLimitOptions {
points: number; // 次数
duration: number; // 秒
blockDuration?: number; // 额外封禁秒数
keyPrefix: string; // 业务线
}
export const RateLimit = (options: RateLimitOptions) =>
applyDecorators(
SetMetadata(RATE_LIMIT_KEY, options),
);
步骤 3:Guard 中做原子判断,Interceptor 中做审计
@Injectable()
export class RateLimitGuard implements CanActivate {
constructor(
private readonly reflector: Reflector,
private readonly redis: RedisService, // 基于 ioredis
private readonly logger: RateLimitLogger, // 自定义 Logger,实现日志落盘
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const opts = this.reflector.get<RateLimitOptions>(
RATE_LIMIT_KEY,
context.getHandler(),
) || this.reflector.get<RateLimitOptions>(RATE_LIMIT_KEY, context.getClass());
if (!opts) return true; // 未装饰直接放行
const request = context.switchToHttp().getRequest();
const uid = request.user?.uid || '0';
const ip = request.ip;
const key = `rl:${opts.keyPrefix}:${uid === '0' ? ip : uid}:${dayjs().format('YYYYMMDDHH')}`;
const lua = `
local c = redis.call('incr', KEYS[1])
if c == 1 then
redis.call('expire', KEYS[1], ARGV[1])
end
return c
`;
const cur = await this.redis.client.eval(lua, 1, key, opts.duration);
if (cur > opts.points) {
const ttl = await this.redis.client.ttl(key);
// 记录攻击日志
this.logger.warn({
traceId: request.headers['x-trace-id'],
uid,
ip,
userAgent: request.headers['user-agent'],
api: request.route?.path,
limitConfig: opts,
current: cur,
});
throw new RateLimitException(ttl > 0 ? ttl : 60);
}
return true;
}
}
步骤 4:全局异常过滤器统一包装
@Catch(RateLimitException)
export class RateLimitFilter extends BaseExceptionFilter {
catch(exception: RateLimitException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
response.header('Retry-After', String(exception.retryAfterSeconds));
response.status(exception.getStatus()).json(exception.getResponse());
}
}
步骤 5:在 main.ts 注册
app.useGlobalGuards(new RateLimitGuard(app.get(Reflector), app.get(RedisService), app.get(RateLimitLogger)));
app.useGlobalFilters(new RateLimitFilter());
通过以上 5 步,限流触发时:
- 前端收到
429+code=10001+message+retryAfter,可直接用于 Toast 提示; - 攻击日志以 JSON 形式实时写入 Kafka -> Flink -> SLS,支持后续做 IP 画像、账号风控;
- 业务代码只需在 Controller 上加一行
@RateLimit({ points: 20, duration: 60, keyPrefix: 'order' }),零侵入。
拓展思考
- 多维度限流:同一接口需要“按 IP 20 次/分 + 按 UID 100 次/分”双轨限速,如何在一个 Guard 里优雅地支持“或/与”策略?
- 分布式一致性:当网关层(Nginx+Lua)也做一层限流时,怎样保证“网关阈值 ≥ 业务阈值”,避免误杀?
- 惩罚升级:连续触发 3 次限流后自动升级封禁时长(1min→5min→30min),如何设计状态机并与风控系统联动?
- 压测与容量评估:双 11 峰值 30wQPS,Redis 集群需要多少分片、何种规格(16G/32G)才能保持 p99 < 5ms?如何写 JMeter 脚本验证?
- 合规审计:等保 2.0 要求“敏感接口日志保存 6 个月以上”,如何低成本地实现冷热分层(SSD->OSS->ODPS)并支持秒级检索?
把上述思考点准备成“故事化”回答,既展示深度,又能把面试节奏带入自己熟悉的技术主场,可显著拉高面试官的技术评分。