0Pricing
Redis Caching & Messaging (Pub/Sub, Streams) · 课时

分布式限流

使用 Redis 计数器和原子 Lua 脚本,在多个应用实例之间协调请求限制,实现固定窗口、滑动窗口和令牌桶算法

分布式限流 是 CoddyKit 上的免费 Redis Caching & Messaging (Pub/Sub, Streams) 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Redis Caching & Messaging (Pub/Sub, Streams) 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Redis Caching & Messaging (Pub/Sub, Streams) 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Local Limits Do Not Scale

An in-memory rate limiter only counts requests on one server. With many app instances behind a load balancer, you need a shared view of usage. Redis, being central and atomic, is the natural coordination point.

Fixed Window Counter

The simplest algorithm: a counter per time window. INCR the key; set a TTL equal to the window on first increment. Reject when the count exceeds the limit.

INCR rl:user:42:1716900000
EXPIRE rl:user:42:1716900000 60

The Race Condition

Doing INCR then EXPIRE as two commands risks a key without a TTL if the client dies in between. An atomic Lua script fixes this by running both as one operation.

local c = redis.call('INCR', KEYS[1])
if c == 1 then redis.call('EXPIRE', KEYS[1], ARGV[1]) end
return c

Why Atomicity Matters

Across many instances, concurrent requests could otherwise read and write counters in interleaved order. Lua scripts run atomically on the server, so the entire check-and-increment happens with no interleaving.

Fixed Window Burst Problem

Fixed windows allow bursts at the boundary: a client can send a full window's worth at the end of one window and again at the start of the next, doubling the effective rate.

Sliding Window Log

A sorted set of request timestamps gives a precise sliding window. Drop old entries, count what remains, and add the new request, all in one script.

ZREMRANGEBYSCORE rl:user:42 0 (now-window)
ZCARD rl:user:42
ZADD rl:user:42 now now

Token Bucket

The token bucket allows controlled bursts. Tokens refill at a fixed rate up to a cap; each request consumes one. Store tokens and last-refill time in a hash and update atomically with Lua.

HSET rl:tb:user:42 tokens 10 ts 1716900000

Refill Logic

On each request, compute elapsed time, add elapsed * rate tokens (capped at the bucket size), then allow the request if at least one token remains. The Lua script keeps this consistent across instances.

Choosing an Algorithm

Fixed window: cheapest, allows boundary bursts. Sliding log: precise but more memory. Token bucket: smooth with controlled bursts, great for APIs.

Returning Useful Headers

Tell clients about their limits: return remaining requests and reset time so well-behaved clients can self-throttle.

# X-RateLimit-Remaining: 7
# X-RateLimit-Reset: 1716900060

Resilience Note

Decide a fallback if Redis is unreachable: fail open (allow traffic) for availability, or fail closed (deny) for protection. The right choice depends on whether the limit guards cost or correctness.

Quick Check

Test your understanding of distributed rate limiting.

Recap

You built distributed rate limiting on Redis: fixed-window counters, atomic Lua to avoid TTL leaks and races, sliding-window logs with sorted sets, and token buckets for smooth bursts. Centralizing the counters makes limits consistent across all app instances; choose your fail-open vs fail-closed fallback deliberately.

常见问题解答

「分布式限流」课时是免费的吗?

是的 — 「分布式限流」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Redis Caching & Messaging (Pub/Sub, Streams) 课程的其余内容,请升级到 CoddyKit PRO。 Redis Caching & Messaging (Pub/Sub, Streams) 课程共包含 4 节课。

「分布式限流」这节课中我会学到什么?

使用 Redis 计数器和原子 Lua 脚本,在多个应用实例之间协调请求限制,实现固定窗口、滑动窗口和令牌桶算法 你通过在浏览器中直接运行的动手代码来练习 Redis Caching & Messaging (Pub/Sub, Streams),全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Redis Caching & Messaging (Pub/Sub, Streams) 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Redis Caching & Messaging (Pub/Sub, Streams) 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「分布式限流」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Redis Caching & Messaging (Pub/Sub, Streams) 课中编写并运行代码吗?

能。每节 Redis Caching & Messaging (Pub/Sub, Streams) 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 使用 Redis 实现分布式锁
  2. 领导者选举模式
  3. 将 Redis 用作协调服务
  4. 分布式限流
← 返回 Redis Caching & Messaging (Pub/Sub, Streams)