如何实现接口级别的速率限制并支持按用户分组?
解读
国内互联网面试中,速率限制(Rate Limit)是高频考点,尤其 ToC 业务面对羊毛党、爬虫、突发流量时,必须做到“接口级 + 用户维度”的精细化限流。Django 自带的安全中间件只解决全局暴力破解,无法区分接口、无法按用户分组,因此需要候选人给出“可落地、可扩展、可观测”的工程方案。面试官重点考察:
- 是否熟悉主流限流算法(令牌桶、滑动日志、固定窗口、漏桶)及适用场景;
- 能否利用 Django 中间件/装饰器/DRF throttle 体系做到“接口级”;
- 能否把“用户分组”抽象为动态可配置策略(VIP、普通、内部服务、IP 白名单等);
- 是否考虑分布式部署、Redis 热 key 和大 key 问题、降级与监控告警;
- 是否给出单元测试与压测思路。
知识点
- DRF 内置 Throttle 体系:AnonRateThrottle、UserRateThrottle、ScopedRateThrottle,配合 DEFAULT_THROTTLE_RATES 配置;
- 自定义 ScopedRateThrottle 子类,重写 get_cache_key() 把“用户分组”拼进 key,实现“同一接口不同组别不同阈值”;
- 令牌桶算法:Redis + Lua 脚本保证原子性,支持突发流量与匀速消费;
- 滑动日志:Redis ZSET 按毫秒时间戳存请求,ZREMRANGEBYSCORE 清理过期,ZCARD 计数;
- 中间件层拦截:django-ratelimit 装饰器(基于缓存计数器),支持 key=ip|user|header,可自定义 group_fn;
- 配置中心:Django 设置 + constance / django-admin 界面动态调整阈值,无需发版;
- 高并发优化:Redis 管道、本地缓存预热、异步回写、限流 key 带版本号防止热 key;
- 观测与告警:Prometheus + django-prometheus 暴露限流指标(rate_limit_hits_total{group,view}),Grafana 配置告警规则;
- 容灾降级:限流 Redis 不可用时 fallback 到“允许通过”或“全局兜底阈值”,防止雪崩;
- 测试:pytest-django 用 freeze_time 模拟时间滑动,locust 压测验证 95th 延迟与错误率。
答案
生产级方案采用“DRF + Redis + 令牌桶 + 动态配置”四段式,步骤如下:
-
定义用户分组
在 User 模型扩展rate_groupCharField,默认normal,后台可手动标记vip、internal、partner。登录后通过request.user.rate_group读取。 -
自定义 ScopedRateThrottle
class GroupedRateThrottle(ScopedRateThrottle): scope_attr = 'throttle_scope' # 从 constance 读取组别配额,形如 {"normal": "100/h", "vip": "1000/h"} GROUP_RATES = settings.RATELIMIT_GROUP_RATES def get_cache_key(self, request, view): if request.user.is_authenticated: group = request.user.rate_group else: group = 'anon' ident = f'{group}_{request.user.pk or self.get_ident(request)}' return self.cache_format % { 'scope': view.throttle_scope or view.__class__.__name__, 'ident': ident } def allow_request(self, request, view): # 动态覆盖 rate group = 'anon' if not request.user.is_authenticated else request.user.rate_group self.rate = self.GROUP_RATES.get(group, self.GROUP_RATES['normal']) return super().allow_request(request, view) -
令牌桶 Lua 脚本(原子性)
放在scripts/ratelimit_token_bucket.lua:local key = KEYS[1] local now = tonumber(ARGV[1]) local capacity = tonumber(ARGV[2]) local refill_rate = tonumber(ARGV[3]) local requested = tonumber(ARGV[4]) local bucket = redis.call('HMGET', key, 'tokens', 'last') local tokens = tonumber(bucket[1]) or capacity local last = tonumber(bucket[2]) or now local delta = math.max(0, now - last) tokens = math.min(capacity, tokens + delta * refill_rate) if tokens < requested then redis.call('HMSET', key, 'tokens', tokens, 'last', now) return 0 else redis.call('HMSET', key, 'tokens', tokens - requested, 'last', now) redis.call('EXPIRE', key, 3600) return 1 end -
在自定义 throttle 中调用
把allow_request里的计数逻辑换成redis.evalsha(sha, 1, key, now, capacity, refill_rate, 1),返回 False 即触发 429。 -
视图级声明
class OrderCreateAPI(CreateAPIView): throttle_scope = 'order_create' throttle_classes = [GroupedRateThrottle] -
动态配置
使用django-constance在 admin 后台维护RATELIMIT_GROUP_RATESJSON,修改后即刻生效;配合cache.delete_pattern('throttle_*')可立即清缓存。 -
观测告警
在allow_request返回 False 处埋点:from prometheus_client import Counter rate_limit_hits = Counter('rate_limit_hits_total', 'labelnames=['group', 'scope']) rate_limit_hits.labels(group=group, scope=scope).inc()Grafana 配置
rate(ratelimit_hits_total[5m]) > 0.2 * 配额即触发飞书告警。 -
容灾降级
Redis 异常捕获后返回 True,并在 Sentry 记录,避免用户无法下单;同时把“降级事件”推送到 Prometheus,方便运维巡检。 -
单元测试
@override_settings(RATELIMIT_GROUP_RATES={'normal': '3/m'}) def test_normal_user_blocked_after_3(self): user = UserFactory(rate_group='normal') self.client.force_authenticate(user) for i in range(3): resp = self.client.post('/api/order/') assert resp.status_code == 201 assert self.client.post('/api/order/').status_code == 429 -
压测验收
使用 locust 编写场景:VIP 用户 1000 并发持续 5 min,错误率 < 0.1%,P95 延迟 < 120 ms,Redis CPU < 30%,验证令牌桶精度。
拓展思考
- 如果业务需要“接口 + 用户 + 下游商户”三维限流,可把
throttle_scope设计为f'{view}.{merchant_id}',并在get_cache_key中拼接,实现更细粒度; - 针对大促突发流量,可引入“分层桶”:先走本地内存令牌桶(Cython 实现),再走 Redis 集群,降低网络 RTT;
- 若公司采用 Service Mesh,限流可下沉到 Istio Envoy,通过 Header
x-user-group做局部限流,Django 侧只需透传分组,减少后端复杂度; - 合规场景下需支持“用户申诉与人工加白”,可开发限流白名单表,优先级高于令牌桶,申诉流程走工单系统;
- 未来做“按付费额度弹性限流”,可把用户当月剩余额度同步到 Redis,令牌桶容量动态等于
remaining_quota,实现“用多少,限多少”的弹性能力。