Redisによる分散レート制限
Redis、アトミック操作、Luaスクリプトを使って複数のゲートウェイやサービスインスタンス間でレート制限の状態を共有し、競合状態を回避する方法を学びます。
「Redisによる分散レート制限」はCoddyKit上の無料API Rate Limiting & Scalability Patternsレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはAPI Rate Limiting & Scalability Patterns学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 API Rate Limiting & Scalability Patternsコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
The Multi-Instance Problem
When you run several gateway replicas, each one keeping its own in-memory counter means a client gets N x limit total — once per instance.
To enforce one global limit, every instance must read and update shared state.
Why Redis
Redis is the de facto choice for distributed rate limiting because it offers:
- Sub-millisecond in-memory reads and writes
- Atomic commands like
INCR - Built-in expiry for automatic window resets
- Lua scripting for multi-step atomic logic
A Naive Counter
The simplest fixed-window counter uses INCR plus EXPIRE:
The first request in a window creates the key and sets a TTL; later requests just increment.
INCR rate:user:42
-- if reply == 1 (first hit):
EXPIRE rate:user:42 60The Race Condition
Running INCR then EXPIRE as two separate calls has a bug: if the process crashes between them, the key has no TTL and the limit never resets.
The fix is to make the check-and-increment atomic.
Atomicity with Lua
Redis runs a Lua script as a single atomic unit. We can check the count, increment, and set expiry without interruption.
local c = redis.call('INCR', KEYS[1])
if c == 1 then
redis.call('EXPIRE', KEYS[1], ARGV[2])
end
if c > tonumber(ARGV[1]) then
return 0
end
return 1Calling the Script
From the gateway you invoke the script with EVAL, passing the key, the limit, and the window size.
A return of 1 means allow; 0 means reject with 429 Too Many Requests.
allowed = redis.eval(script, keys=['rate:user:42'], args=[100, 60])
if allowed == 0:
return Response(status=429)Sliding Window with Sorted Sets
For smoother limiting, store request timestamps in a sorted set. Remove old entries, count what remains, then add the new one.
ZREMRANGEBYSCORE rate:user:42 0 (now-window)
ZCARD rate:user:42
ZADD rate:user:42 now nowReturning Rate Limit Headers
Good gateways tell clients where they stand using standard headers:
X-RateLimit-LimitX-RateLimit-RemainingRetry-Afteron a429
The Lua script can return remaining count alongside the allow flag.
Handling Redis Failures
What if Redis is unreachable? Two strategies:
- Fail open — allow traffic; favors availability
- Fail closed — reject traffic; favors protection
Most APIs fail open with a local fallback limiter to avoid a full outage.
Reducing Latency
Every limit check is a network hop. Cut overhead by:
- Co-locating Redis near the gateway
- Using connection pooling
- Batching counters with a short local cache for very hot keys
Keying by Identity
The rate limit key defines what you are limiting. Common choices:
rate:ip:1.2.3.4for anonymous trafficrate:user:42for authenticated usersrate:apikey:abcfor API clients
Pick the most specific identity available so one abuser cannot exhaust a shared bucket.
Quick Check
Test your grasp of distributed limiting.
Recap
You learned to share rate limit state across instances:
- A shared Redis store gives one global limit
- Lua scripts make check-and-increment atomic
- Sorted sets enable sliding windows
- Decide fail open vs. closed for Redis outages
よくある質問
「Redisによる分散レート制限」レッスンは無料ですか?
はい。「Redisによる分散レート制限」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、API Rate Limiting & Scalability Patternsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 API Rate Limiting & Scalability Patternsコースには全4レッスンが含まれています。
「Redisによる分散レート制限」で何を学びますか?
Redis、アトミック操作、Luaスクリプトを使って複数のゲートウェイやサービスインスタンス間でレート制限の状態を共有し、競合状態を回避する方法を学びます。 ブラウザで直接実行するハンズオンコードで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フィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- API Gateway連携パターン
- グローバルレート制限とサービス単位のレート制限
- 動的なレート制限の設定
- Redisによる分散レート制限