0Pricing
API Rate Limiting & Scalability Patterns · 课时

使用 Redis 有序集合实现滑动窗口

使用 Redis 有序集合、原子操作和旧条目自动过期机制,实现准确的分布式滑动窗口限流器。

使用 Redis 有序集合实现滑动窗口 是 CoddyKit 上的免费 API Rate Limiting & Scalability Patterns 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 API Rate Limiting & Scalability Patterns 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 API Rate Limiting & Scalability Patterns 课程共包含 4 节课。

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

From Theory to Production

You understand the sliding window log and counter conceptually. Now build one that works across many servers using Redis sorted sets, the most common production technique for accurate distributed rate limiting.

Why Sorted Sets

A Redis sorted set (ZSET) stores members ranked by a numeric score. By using the request timestamp as the score, we get an ordered log of recent requests we can trim and count efficiently.

One Key Per Client

Each client gets a key like rl:user123. Every incoming request adds a member to that client's sorted set, scored by the current timestamp in milliseconds.

ZADD rl:user123 1700000000123 1700000000123

Trimming the Window

Before counting, remove entries older than the window. If the window is 60 seconds, delete everything with a score below now - 60000. This keeps only the requests inside the current sliding window.

ZREMRANGEBYSCORE rl:user123 0 (now-60000)

Counting Requests

After trimming, the cardinality of the set is the number of requests in the window. Compare it against the limit to allow or deny.

ZCARD rl:user123

Atomicity Matters

Doing trim, add, and count as separate commands creates a race condition under concurrency. Wrap them in a single Lua script so Redis executes them atomically per client.

The Lua Script

A Lua script run with EVAL performs all steps in one atomic operation, returning whether the request is allowed. No two requests can interleave mid-check.

redis.call('ZREMRANGEBYSCORE', KEYS[1], 0, ARGV[1])
local count = redis.call('ZCARD', KEYS[1])
if count < tonumber(ARGV[3]) then
  redis.call('ZADD', KEYS[1], ARGV[2], ARGV[2])
  return 1
end
return 0

Setting Expiry

Always set a TTL on the key (a bit longer than the window) so abandoned clients do not leak memory. Idle keys expire automatically.

EXPIRE rl:user123 120

Accuracy vs Memory

This approach is highly accurate because it tracks every request timestamp, but memory grows with request volume per window. For very high-traffic clients, the sliding window counter approximation uses far less memory.

Handling Many Nodes

Because all API nodes talk to the same Redis, the limit is enforced globally regardless of which node handles a request. Use a Redis cluster or replica setup for availability, mindful that replication lag can slightly relax limits.

Failure Modes

Decide what happens if Redis is unreachable: fail open (allow traffic, risk overload) or fail closed (block traffic, risk outage). Most public APIs fail open with a local fallback limiter.

Quick Check

Test your understanding of the Redis sliding window.

Recap

You built a distributed sliding window:

  • Store request timestamps in a Redis sorted set, one key per client.
  • Trim old entries with ZREMRANGEBYSCORE, count with ZCARD.
  • Wrap trim/count/add in a Lua script for atomicity.
  • Set a TTL to free memory, and decide fail-open vs fail-closed for Redis outages.

常见问题解答

「使用 Redis 有序集合实现滑动窗口」课时是免费的吗?

是的 — 「使用 Redis 有序集合实现滑动窗口」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 API Rate Limiting & Scalability Patterns 课程的其余内容,请升级到 CoddyKit PRO。 API Rate Limiting & Scalability Patterns 课程共包含 4 节课。

「使用 Redis 有序集合实现滑动窗口」这节课中我会学到什么?

使用 Redis 有序集合、原子操作和旧条目自动过期机制,实现准确的分布式滑动窗口限流器。 你通过在浏览器中直接运行的动手代码来练习 API Rate Limiting & Scalability Patterns,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 API Rate Limiting & Scalability Patterns 需要有经验吗?

无需任何先前经验。CoddyKit 上的 API Rate Limiting & Scalability Patterns 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「使用 Redis 有序集合实现滑动窗口」课时需要多长时间?

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

我能在这节 API Rate Limiting & Scalability Patterns 课中编写并运行代码吗?

能。每节 API Rate Limiting & Scalability Patterns 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 滑动窗口日志实现
  2. 滑动窗口计数器策略
  3. 算法比较与权衡
  4. 使用 Redis 有序集合实现滑动窗口
← 返回 API Rate Limiting & Scalability Patterns