0Pricing
API Rate Limiting & Scalability Patterns · レッスン

Redisのソート済みセットによるスライディングウィンドウ

Redisのソート済みセット、アトミック操作、古いエントリの自動期限切れを使って、正確な分散スライディングウィンドウ方式のレートリミッターを実装します。

「Redisのソート済みセットによるスライディングウィンドウ」はCoddyKit上の無料API Rate Limiting & Scalability Patternsレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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のソート済みセットによるスライディングウィンドウ」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、API Rate Limiting & Scalability Patternsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 API Rate Limiting & Scalability Patternsコースには全4レッスンが含まれています。

「Redisのソート済みセットによるスライディングウィンドウ」で何を学びますか?

Redisのソート済みセット、アトミック操作、古いエントリの自動期限切れを使って、正確な分散スライディングウィンドウ方式のレートリミッターを実装します。 ブラウザで直接実行するハンズオンコードでAPI Rate Limiting & Scalability Patternsを演習し、24時間対応の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に戻る