分散レート制限
RedisのカウンターとアトミックなLuaスクリプトを使い、固定ウィンドウ、スライディングウィンドウ、トークンバケットの各アルゴリズムで多数のアプリインスタンス間のリクエスト制限を調整します。
「分散レート制限」はCoddyKit上の無料Redis Caching & Messaging (Pub/Sub, Streams)レッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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 60The 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 cWhy 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 nowToken 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 1716900000Refill 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: 1716900060Resilience 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.
よくある質問
「分散レート制限」レッスンは無料ですか?
はい。「分散レート制限」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Redis Caching & Messaging (Pub/Sub, Streams)コースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Redis Caching & Messaging (Pub/Sub, Streams)コースには全4レッスンが含まれています。
「分散レート制限」で何を学びますか?
RedisのカウンターとアトミックなLuaスクリプトを使い、固定ウィンドウ、スライディングウィンドウ、トークンバケットの各アルゴリズムで多数のアプリインスタンス間のリクエスト制限を調整します。 ブラウザで直接実行するハンズオンコードでRedis Caching & Messaging (Pub/Sub, Streams)を演習し、24時間対応の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フィードバックを取得できます。ローカル設定は不要です。