# 限流

限流是一种流量控制技术，用于限制客户端在既定时间段内可向服务发起的请求数量；超过限制时，返回错误或延迟服务。它保护 API 和 Web 应用免受滥用、拒绝服务流量和资源耗尽的影响，并在客户端之间强制公平共享容量。<sup>[1](https://www.rfc-editor.org/info/rfc6585/)</sup><sup> • </sup><sup>[2](https://docs.netlify.com/manage/security/secure-access-to-sites/rate-limiting/)</sup>

| 关键事实 | 详情 |
|---|---|
| HTTP 信号 | 429 请求过多状态码表示客户端在给定时间内发送了过多请求；响应可包含 Retry-After 头部，以秒为单位给出等待时间。<sup>[1](https://www.rfc-editor.org/info/rfc6585/)</sup> |
| 核心模型 | 令牌桶和漏桶通过 R = B/t 将突发大小 B、速率 R 和时间间隔 t 关联起来；二者都用于帧中继、ATM、集成服务和区分服务中的速率控制。<sup>[3](https://www.rfc-editor.org/info/rfc3290/)</sup> |
| 常见算法 | 固定窗口计数器、滑动窗口日志、滑动窗口计数器、令牌桶和漏桶是五种广泛实现的技术。<sup>[4](https://redis.io/docs/latest/develop/use-cases/rate-limiter/nodejs/)</sup> |
| 固定窗口的弱点 | 客户端可以在一个窗口末尾发送上限数量的请求，并在下一个窗口开头再发送上限数量的请求，从而在窗口边界处使吞吐量翻倍。<sup>[4](https://redis.io/docs/latest/develop/use-cases/rate-limiter/nodejs/)</sup> |
| 标准化 | IETF HTTPAPI 工作组的草案定义了 RateLimit 和 RateLimit-Policy 头部字段，使服务器可以公布配额策略，客户端可以避免被限流。<sup>[5](https://datatracker.ietf.org/doc/draft-ietf-httpapi-ratelimit-headers/)</sup> |
| 分布式执行 | 基于 Redis 的限流器使用带 EVAL 的 Lua 脚本，使读取—决策—更新循环保持原子性，因此并发请求无法重复使用令牌或丢失计数器更新。<sup>[6](https://redis.io/docs/latest/develop/use-cases/rate-limiter/)</sup> |

## 为什么服务要限制请求速率

限流有若干不同目的。它在内置默认防护的基础上进一步缓解分布式拒绝服务（DDoS）攻击，保护数据库、内容管理系统和 AI 推理提供方等后端服务，使其免受会触及自身限制或产生过高成本的流量尖峰冲击，防止过度抓取和机器人流量，并在访问者之间强制公平使用 API。<sup>[2](https://docs.netlify.com/manage/security/secure-access-to-sites/rate-limiting/)</sup> 云提供商将其定位为纵深防御体系中的一层：Netlify 在 DDoS 防护、防火墙流量规则和 Web 应用防火墙（WAF）规则之后应用限流，<sup>[2](https://docs.netlify.com/manage/security/secure-access-to-sites/rate-limiting/)</sup> 而 [Cloudflare](https://www.edgepedia.org/zh/cloudflare) 将按 IP 或按 API 密钥的请求限制与模式验证和双向 TLS 客户端认证配合使用，以保护 API。<sup>[7](https://developers.cloudflare.com/use-cases/apis/protect-apis/)</sup>

认证与限流相互作用。根据 AWS 的 DDoS 韧性指南，缺少认证的 API 端点面临更大的应用层 DDoS 攻击风险，因为攻击者无需有效凭据即可创建请求；该指南建议对每个 REST API 方法设置标准或突发速率限制，以保护后端免受过多流量冲击。<sup>[8](https://docs.aws.amazon.com/whitepapers/latest/aws-best-practices-ddos-resiliency/protecting-api-endpoints-bp4.html)</sup>

## 算法

**令牌桶和漏桶。** 这些是经典模型，RFC 3290 将其形式化描述为既定突发大小 B、速率 R 和时间间隔 t 之间的理论关系，即 R = B/t。<sup>[3](https://www.rfc-editor.org/info/rfc3290/)</sup> 令牌桶以稳定速率补充令牌，并在有令牌可用时允许请求通过，因此可接受最高达桶容量的突发；漏桶则塑造输出速率，无论输入多么突发，都强制形成更均匀的请求节奏。<sup>[9](https://redis.io/blog/api-throttling-algorithms-patterns/)</sup> nginx Web 服务器的 limit_req 模块实现漏桶方法：rate=1r/s 且 burst=5 的配置允许平均每秒不超过 1 个请求，突发不超过 5 个请求，超过突发大小的过多请求会以错误终止。<sup>[10](https://nginx.org/en/docs/http/ngx_http_limit_req_module.html)</sup>

**基于窗口的计数器。** 固定窗口计数器使用每个窗口一个键，在离散且不重叠的区间内统计请求；它是最简单的算法，但允许在边界处出现两倍突发，因为客户端可以在窗口关闭前耗尽限额，并在下一个窗口开启后立即再次耗尽限额。<sup>[4](https://redis.io/docs/latest/develop/use-cases/rate-limiter/nodejs/)</sup> 滑动窗口日志在有序集合中记录每个请求的精确时间戳，提供无边界突发的真正滚动窗口，但其内存随请求量成比例增长，因此不适合高流量、高基数限流。<sup>[4](https://redis.io/docs/latest/develop/use-cases/rate-limiter/nodejs/)</sup> 滑动窗口计数器对两个固定窗口计数器的计数值取加权平均，以近似真正滑动窗口，在保持与固定窗口相同的低内存占用的同时提供接近精确的准确性。<sup>[4](https://redis.io/docs/latest/develop/use-cases/rate-limiter/nodejs/)</sup> Redis 教程的总结性指导是：对大多数 API 而言，滑动窗口计数器在准确性、简单性和低内存使用之间提供了最佳平衡，而令牌桶适合突发流量，漏桶适合严格执行禁止突发的限制。<sup>[11](https://redis.io/tutorials/howtos/ratelimiting/)</sup>

## HTTP 信令

限流的 HTTP 标准是 RFC 6585（2012 年 4 月），它定义了 429 请求过多状态码：它表示用户在给定时间内发送了过多请求，响应应包含解释该状况的细节，并可包含 Retry-After 头部，指示在发起新请求前应等待多久。<sup>[1](https://www.rfc-editor.org/info/rfc6585/)</sup> 该规范有意不限定计数方法：服务器可以按资源、跨整个服务器或在一组服务器之间统计请求，并可通过认证凭据或有状态 cookie 识别用户。<sup>[1](https://www.rfc-editor.org/info/rfc6585/)</sup> 带有 429 状态码的响应不得由缓存存储。<sup>[1](https://www.rfc-editor.org/info/rfc6585/)</sup> RFC 6585 还记录了一项安全考虑：当服务器受到攻击时，对每个请求都返回 429 会消耗资源，因此不要求服务器使用该状态码，服务器可以改为直接丢弃连接。<sup>[12](https://www.rfc-editor.org/rfc/rfc6585.html)</sup>

**配额公布。** IETF HTTPAPI 工作组的一份 Internet-Draft 定义了 RateLimit 和 RateLimit-Policy 头部字段，使服务器可以公布其配额策略和当前服务限制，以便客户端避免被限流。<sup>[5](https://datatracker.ietf.org/doc/draft-ietf-httpapi-ratelimit-headers/)</sup> 该草案规定，客户端不得假设未来响应会包含相同的 RateLimit 字段或任何此类字段；格式错误的 RateLimit 字段必须忽略；当响应同时包含 RateLimit 和 Retry-After 时，以 Retry-After 的值为准。<sup>[5](https://datatracker.ietf.org/doc/draft-ietf-httpapi-ratelimit-headers/)</sup> 在标准化之前，X-RateLimit-Limit、X-RateLimit-Remaining 和 X-RateLimit-Reset 等广泛使用但非标准的头部大量出现，并伴有已记录的互操作性问题：据观察，X-RateLimit-Reset 会根据实现携带剩余秒数、剩余毫秒数、Unix 时间戳或格式化日期时间。<sup>[5](https://datatracker.ietf.org/doc/draft-ietf-httpapi-ratelimit-headers/)</sup>

## 分布式限流

单服务器限流器将计数器保存在本地内存中，但在负载均衡器之后，本地按进程的计数器会失效：同一客户端通过命中不同实例绕过限制，因此限流器需要一个足够快、能位于请求路径上的集中式存储。<sup>[6](https://redis.io/docs/latest/develop/use-cases/rate-limiter/)</sup> Redis 是常见选择；其文档将限流器描述为共享存储，每个服务实例在每次请求时都会查询它，并在亚毫秒级时间内返回允许或拒绝决定，计数器按限流维度划分，例如用户、IP 地址、API 密钥、租户或模型。<sup>[6](https://redis.io/docs/latest/develop/use-cases/rate-limiter/)</sup> 原子性在这一层很重要：没有原子性，两个并发请求可能各自读到低于阈值的计数，并都被允许通过，因此生产实现通过 EVAL 将检查并更新逻辑作为单个 Lua 脚本运行。<sup>[6](https://redis.io/docs/latest/develop/use-cases/rate-limiter/)</sup> Redis 8.8 增加了专用 INCREX 命令，这是一种窗口计数器限流器，结合了递增、边界和过期操作。<sup>[13](https://redis.io/docs/latest/develop/whats-new/8-8/)</sup>

在地理分布式站点之间执行单一全局限制本身就是一个研究问题。分布式限流的研究指出了准确性、响应性以及限流器之间的通信成本之间的核心权衡；准确性指系统将聚合需求约束到全局限制的程度。<sup>[14](https://www.cs.princeton.edu/courses/archive/fall12/cos561/papers/drl-sigcomm07.pdf)</sup>

## 实践中的执行

商业和开源网关将限流作为可配置的策略层提供。Apigee 区分 SpikeArrest 策略和配额策略：SpikeArrest 策略限制 API 代理处理的请求，以防止拒绝服务攻击或有缺陷的客户端应用造成突发流量；配额策略维护分布式计数器，按可识别实体（如应用、开发者或 API 密钥）统计请求，旨在执行业务合同和服务级别协议，而非运营流量管理。<sup>[15](https://docs.cloud.google.com/apigee/docs/api-platform/develop/rate-limiting)</sup> Google Cloud Armor 在负载均衡器处应用限流，以防止来自不可信客户端的 DDoS 攻击，并在服务网格中执行按客户端的服务器端限制。<sup>[16](https://docs.cloud.google.com/armor/docs/rate-limiting-overview)</sup> Cloudflare 的限流产品定义细粒度阈值，并自动阻止或记录超过阈值的客户端，用例包括登录端点保护和基于会话的 API 防御。<sup>[17](https://www.cloudflare.com/products/rate-limiting/)</sup> 规则可以纳入后端状态：Cloudflare WAF 限流规则可以仅在响应状态码为 401 或 403 时递增计数器，因此失败的认证尝试会计入限制，而成功的尝试不会。<sup>[18](https://51e47fea.previews.developers.cloudflare.com/waf/rate-limiting-rules/best-practices/)</sup>

## 实测行为与近期发现

一项针对生产 API 网关的系统性测量研究测试了它们是否在任意连续时间区间内执行限制，作者将这一性质称为区间无关的速率约束。NGINX（使用其漏桶 limit_req）和 APISIX 在构造上满足该性质，Traefik 通过架构设计满足该性质，但 Kong 在其默认固定窗口计数器下不满足：客户端以固定间隔发送请求，会累积来自两个连续窗口的通过量，并在不进行任何头部操纵的情况下，相对于加固配置达到 1.78 倍超额请求倍数。<sup>[19](https://www.sciencedirect.com/science/article/pii/S0167404826002634)</sup>

固定阈值也难以适应变化的负载。一项 2025 年关于微服务限流的研究使用深度强化学习，并在 [Kubernetes](https://www.edgepedia.org/zh/kubernetes) 集群中评估，报告称在高负载场景下，与传统固定阈值策略相比，吞吐量提高 23.7%，99 分位延迟降低 31.4%，并指出令牌桶和滑动窗口等广泛采用的算法难以适应动态流量模式。<sup>[20](https://arxiv.org/abs/2511.03279)</sup>

## References

1. [RFC 6585: Additional HTTP Status Codes, RFC Editor](https://www.rfc-editor.org/info/rfc6585/)
2. [Rate limiting, Netlify Docs](https://docs.netlify.com/manage/security/secure-access-to-sites/rate-limiting/)
3. [RFC 3290: An Informal Management Model for Diffserv Routers, RFC Editor](https://www.rfc-editor.org/info/rfc3290/)
4. [Token bucket rate limiter with Redis and Node.js, Redis Docs](https://redis.io/docs/latest/develop/use-cases/rate-limiter/nodejs/)
5. [draft-ietf-httpapi-ratelimit-headers: RateLimit header fields for HTTP, IETF Datatracker](https://datatracker.ietf.org/doc/draft-ietf-httpapi-ratelimit-headers/)
6. [Redis rate limiter, Redis Docs](https://redis.io/docs/latest/develop/use-cases/rate-limiter/)
7. [Protect your APIs, Cloudflare Developers](https://developers.cloudflare.com/use-cases/apis/protect-apis/)
8. [Protecting API endpoints (BP4), AWS Best Practices for DDoS Resiliency](https://docs.aws.amazon.com/whitepapers/latest/aws-best-practices-ddos-resiliency/protecting-api-endpoints-bp4.html)
9. [API Throttling: Algorithms, Patterns & Mistakes, Redis Blog](https://redis.io/blog/api-throttling-algorithms-patterns/)
10. [Module ngx_http_limit_req_module, nginx documentation](https://nginx.org/en/docs/http/ngx_http_limit_req_module.html)
11. [Build 5 Rate Limiters with Redis: Algorithm Comparison Guide, Redis Tutorials](https://redis.io/tutorials/howtos/ratelimiting/)
12. [RFC 6585 (full text), RFC Editor](https://www.rfc-editor.org/rfc/rfc6585.html)
13. [Redis 8.8 release notes, Redis Docs](https://redis.io/docs/latest/develop/whats-new/8-8/)
14. [Cloud Control with Distributed Rate Limiting, SIGCOMM 2007](https://www.cs.princeton.edu/courses/archive/fall12/cos561/papers/drl-sigcomm07.pdf)
15. [Rate-limiting, Apigee, Google Cloud Documentation](https://docs.cloud.google.com/apigee/docs/api-platform/develop/rate-limiting)
16. [Rate limiting overview, Google Cloud Armor](https://docs.cloud.google.com/armor/docs/rate-limiting-overview)
17. [Cloudflare Rate Limiting, product page](https://www.cloudflare.com/products/rate-limiting/)
18. [Rate limiting best practices, Cloudflare WAF docs](https://51e47fea.previews.developers.cloudflare.com/waf/rate-limiting-rules/best-practices/)
19. [Rate-limit security in production API gateways, Computers & Security (ScienceDirect)](https://www.sciencedirect.com/science/article/pii/S0167404826002634)
20. [Multi-Objective Adaptive Rate Limiting in Microservices Using Deep Reinforcement Learning, arXiv](https://arxiv.org/abs/2511.03279)

---
*Initially written Oct 15, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 网络与安全 › Networking fundamentals and architecture

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/rate-limiting

English original: https://www.edgepedia.org/rate-limiting
