如何实现接口级别的速率限制并支持按用户分组?

解读

国内互联网面试中,速率限制(Rate Limit)是高频考点,尤其 ToC 业务面对羊毛党、爬虫、突发流量时,必须做到“接口级 + 用户维度”的精细化限流。Django 自带的安全中间件只解决全局暴力破解,无法区分接口、无法按用户分组,因此需要候选人给出“可落地、可扩展、可观测”的工程方案。面试官重点考察:

  1. 是否熟悉主流限流算法(令牌桶、滑动日志、固定窗口、漏桶)及适用场景;
  2. 能否利用 Django 中间件/装饰器/DRF throttle 体系做到“接口级”;
  3. 能否把“用户分组”抽象为动态可配置策略(VIP、普通、内部服务、IP 白名单等);
  4. 是否考虑分布式部署、Redis 热 key 和大 key 问题、降级与监控告警;
  5. 是否给出单元测试与压测思路。

知识点

  1. DRF 内置 Throttle 体系:AnonRateThrottle、UserRateThrottle、ScopedRateThrottle,配合 DEFAULT_THROTTLE_RATES 配置;
  2. 自定义 ScopedRateThrottle 子类,重写 get_cache_key() 把“用户分组”拼进 key,实现“同一接口不同组别不同阈值”;
  3. 令牌桶算法:Redis + Lua 脚本保证原子性,支持突发流量与匀速消费;
  4. 滑动日志:Redis ZSET 按毫秒时间戳存请求,ZREMRANGEBYSCORE 清理过期,ZCARD 计数;
  5. 中间件层拦截:django-ratelimit 装饰器(基于缓存计数器),支持 key=ip|user|header,可自定义 group_fn;
  6. 配置中心:Django 设置 + constance / django-admin 界面动态调整阈值,无需发版;
  7. 高并发优化:Redis 管道、本地缓存预热、异步回写、限流 key 带版本号防止热 key;
  8. 观测与告警:Prometheus + django-prometheus 暴露限流指标(rate_limit_hits_total{group,view}),Grafana 配置告警规则;
  9. 容灾降级:限流 Redis 不可用时 fallback 到“允许通过”或“全局兜底阈值”,防止雪崩;
  10. 测试:pytest-django 用 freeze_time 模拟时间滑动,locust 压测验证 95th 延迟与错误率。

答案

生产级方案采用“DRF + Redis + 令牌桶 + 动态配置”四段式,步骤如下:

  1. 定义用户分组
    在 User 模型扩展 rate_group CharField,默认 normal,后台可手动标记 vip、internal、partner。登录后通过 request.user.rate_group 读取。

  2. 自定义 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)
    
  3. 令牌桶 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
    
  4. 在自定义 throttle 中调用
    把 allow_request 里的计数逻辑换成 redis.evalsha(sha, 1, key, now, capacity, refill_rate, 1),返回 False 即触发 429。

  5. 视图级声明

    class OrderCreateAPI(CreateAPIView):
        throttle_scope = 'order_create'
        throttle_classes = [GroupedRateThrottle]
    
  6. 动态配置
    使用 django-constance 在 admin 后台维护 RATELIMIT_GROUP_RATES JSON,修改后即刻生效;配合 cache.delete_pattern('throttle_*') 可立即清缓存。

  7. 观测告警
    在 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 * 配额 即触发飞书告警。

  8. 容灾降级
    Redis 异常捕获后返回 True,并在 Sentry 记录,避免用户无法下单;同时把“降级事件”推送到 Prometheus,方便运维巡检。

  9. 单元测试

    @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
    
  10. 压测验收
    使用 locust 编写场景:VIP 用户 1000 并发持续 5 min,错误率 < 0.1%,P95 延迟 < 120 ms,Redis CPU < 30%,验证令牌桶精度。

拓展思考

  1. 如果业务需要“接口 + 用户 + 下游商户”三维限流,可把 throttle_scope 设计为 f'{view}.{merchant_id}',并在 get_cache_key 中拼接,实现更细粒度;
  2. 针对大促突发流量,可引入“分层桶”:先走本地内存令牌桶(Cython 实现),再走 Redis 集群,降低网络 RTT;
  3. 若公司采用 Service Mesh,限流可下沉到 Istio Envoy,通过 Header x-user-group 做局部限流,Django 侧只需透传分组,减少后端复杂度;
  4. 合规场景下需支持“用户申诉与人工加白”,可开发限流白名单表,优先级高于令牌桶,申诉流程走工单系统;
  5. 未来做“按付费额度弹性限流”,可把用户当月剩余额度同步到 Redis,令牌桶容量动态等于 remaining_quota,实现“用多少,限多少”的弹性能力。