速率限制与节流
学习速率限制如何保护系统免受滥用和过载,包括令牌桶与滑动窗口算法。
速率限制与节流 是 CoddyKit 上的免费 System Design Basics for Backend Developers 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 System Design Basics for Backend Developers 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 System Design Basics for Backend Developers 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Why Rate Limit?
Rate limiting caps how many requests a client can make in a time window. It protects a system from abuse, accidental floods, and runaway clients.
- Stops brute-force and scraping attacks
- Ensures fair sharing among clients
- Protects backends from overload
Rate Limiting vs Throttling
The terms overlap but differ slightly: rate limiting rejects requests over a hard cap, while throttling often slows or queues excess requests rather than rejecting them outright.
Fixed Window Counter
The simplest scheme counts requests in fixed time windows, e.g. 100 per minute. It is easy but has an edge problem: a client can send 100 at the end of one window and 100 at the start of the next — 200 in a few seconds.
limit = 100
window = '12:00:00-12:00:59'
count = 0
# reset count to 0 each new windowSliding Window
A sliding window smooths the edge problem by weighting the previous window or tracking timestamps over a rolling interval. It gives a more accurate, fairer limit at the cost of more bookkeeping.
Token Bucket
The token bucket is the most popular algorithm. Tokens refill at a steady rate up to a capacity. Each request consumes a token; if the bucket is empty, the request is rejected. This allows short bursts while bounding the average rate.
import time
class Bucket:
def __init__(self, cap, rate):
self.cap = cap
self.rate = rate
self.tokens = cap
self.last = time.time()
def allow(self):
now = time.time()
self.tokens = min(self.cap, self.tokens + (now - self.last) * self.rate)
self.last = now
if self.tokens >= 1:
self.tokens -= 1
return True
return False
b = Bucket(5, 1)
print([b.allow() for _ in range(7)])Leaky Bucket
The leaky bucket processes requests at a fixed rate, queuing bursts and 'leaking' them out steadily. It smooths traffic into a constant outflow — good when the downstream needs a steady, predictable load.
Choosing the Limit Key
Decide what to limit on:
- Per API key or user — fair per-account limits
- Per IP — defends against anonymous abuse
- Per endpoint — protects expensive operations
Often you combine several keys.
Communicating Limits
Tell clients their status with standard headers and the right status code, so well-behaved clients can back off.
HTTP/1.1 429 Too Many Requests
Retry-After: 30
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1735689600Distributed Rate Limiting
With many app servers, an in-memory counter per server is inconsistent. Use a shared store like Redis with atomic increments (or Lua scripts) so the limit is enforced globally across the fleet.
INCR rl:user:42
EXPIRE rl:user:42 60
# reject when value > limitRate Limiting and DDoS
Rate limiting complements DDoS protection. Application-layer limits stop a single abusive client, while edge and network defenses absorb large volumetric floods before they reach your servers. Defense in depth uses both.
Designing Good Limits
Set limits from real usage data, allow reasonable bursts, expose clear headers, and return 429 with Retry-After. Consider tiered limits — higher caps for paid plans, stricter ones for unauthenticated traffic.
Quick Check
Test your understanding of rate limiting.
Recap
You learned to protect systems with rate limiting:
- Fixed window, sliding window, token bucket, and leaky bucket
- Choose limit keys: per user, per IP, per endpoint
- Return 429 with Retry-After and rate-limit headers
- Use a shared store like Redis for distributed enforcement
用 AI 导师学习 System Design Basics for Backend Developers — 免费
在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。
- 课程
- 12
- 课程
- 48
常见问题解答
「速率限制与节流」课时是免费的吗?
是的 — 「速率限制与节流」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 System Design Basics for Backend Developers 课程的其余内容,请升级到 CoddyKit PRO。 System Design Basics for Backend Developers 课程共包含 4 节课。
「速率限制与节流」这节课中我会学到什么?
学习速率限制如何保护系统免受滥用和过载,包括令牌桶与滑动窗口算法。 你通过在浏览器中直接运行的动手代码来练习 System Design Basics for Backend Developers,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 System Design Basics for Backend Developers 需要有经验吗?
无需任何先前经验。CoddyKit 上的 System Design Basics for Backend Developers 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「速率限制与节流」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 System Design Basics for Backend Developers 课中编写并运行代码吗?
能。每节 System Design Basics for Backend Developers 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 身份认证与授权
- 数据加密与隐私
- DDoS 防护与防火墙
- 速率限制与节流