Redis를 활용한 분산 속도 제한
여러 서비스 인스턴스에서 작동하는 견고하고 확장 가능한 분산 속도 제한기를 Redis로 구축하는 방법을 학습합니다.
Redis를 활용한 분산 속도 제한은(는) CoddyKit의 무료 API Rate Limiting & Scalability Patterns 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 API Rate Limiting & Scalability Patterns 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. API Rate Limiting & Scalability Patterns 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Scaling Beyond Single Server
In previous lessons, we learned about basic rate limiting. But what happens when your application grows and runs on multiple servers?
- In-memory limits: They only track requests on a single server.
- Multiple servers: Each server has its own counter, leading to inaccurate and ineffective limits.
- The problem: Users can bypass limits by hitting different servers.
We need a way for all servers to share the same rate limit state.
Introducing Redis for Shared State
To build a distributed rate limiter, we need a centralized, fast data store accessible by all our application instances. This is where Redis shines!
- What is Redis? An open-source, in-memory data structure store.
- Why Redis? It's extremely fast, supports various data types, and is designed for concurrent access.
- Key for Rate Limiting: Its atomic operations are perfect for incrementing counters reliably across multiple services.
Redis Commands for Counters
Redis provides simple yet powerful commands that are ideal for building rate limiters. The two main ones you'll use are INCR and EXPIRE.
INCR key: Atomically increments the number stored atkeyby one. If the key doesn't exist, it's set to 0 before incrementing.EXPIRE key seconds: Sets a timeout onkey. After the timeout, the key is automatically deleted. This is crucial for defining our rate limiting windows.
These commands ensure our counters are consistent even with many concurrent requests.
Implementing Fixed Window with Redis
Let's consider a Fixed Window Counter algorithm using Redis. Imagine we want to limit a user to 5 requests per 60 seconds.
- Define a key: A unique key for the user and the current time window, e.g.,
user:123:2023-10-27-10:00. - Increment Counter: When a request comes in, use
INCRon this key. - Set Expiry: For the first request in a new window, also use
EXPIREto set the key's timeout (e.g., 60 seconds). - Check Limit: Before incrementing, check if the current count for the key is less than the allowed limit.
Basic Redis Fixed Window Code
Here's a simple Python example for a fixed window rate limiter using Redis. This snippet shows the core logic without full error handling.
import redis
import time
def is_rate_limited(user_id, limit, window_seconds):
r = redis.Redis(host='localhost', port=6379, db=0)
current_minute = int(time.time() // window_seconds)
key = f"rate_limit:{user_id}:{current_minute}"
count = r.get(key)
if count is None:
r.setex(key, window_seconds, 0) # Initialize and set expiry
count = 0
else:
count = int(count)
if count < limit:
r.incr(key)
return False # Not rate limited
return True # Rate limited
if __name__ == "__main__":
user = "user_alice"
requests_limit = 5
time_window = 60 # seconds
print(f"Testing rate limiter for {user} ({requests_limit} reqs/{time_window}s)")
for i in range(1, 8):
if is_rate_limited(user, requests_limit, time_window):
print(f"Request {i}: Rate limited!")
else:
print(f"Request {i}: OK")
time.sleep(0.1) # Simulate some workAddressing Race Conditions
In the previous example, the `get`, `setex`, and `incr` operations are separate. This can lead to a race condition:
- Two requests might `GET` the key when it doesn't exist.
- Both might `SETEX` it, potentially overwriting each other's expiry.
- The `EXPIRE` might not be set for the *first* incremented value, causing the counter to persist indefinitely.
We need to perform these multiple Redis commands as a single, atomic operation.
Atomic Operations with Lua Scripts
Redis allows you to execute server-side Lua scripts. This is incredibly powerful for rate limiting because:
- Atomicity: A Lua script runs as a single, indivisible command. No other Redis commands can interrupt it.
- Efficiency: Reduces network round trips for complex operations.
We can write a Lua script to check the counter, increment it, and set its expiry all in one go.
Lua Script Example for Limiter
Here's a Lua script for an atomic fixed window counter. It takes the key, limit, and window duration as arguments.
local key = KEYS[1]
local limit = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local current_count = redis.call('INCR', key)
if current_count == 1 then
redis.call('EXPIRE', key, window)
end
if current_count > limit then
return 1 -- Rate limited
else
return 0 -- Not rate limited
endPython Calling Lua Script
Now, let's see how to integrate and execute this Lua script from our Python application. The EVAL command sends the script to Redis for atomic execution.
import redis
import time
def is_rate_limited_atomic(user_id, limit, window_seconds):
r = redis.Redis(host='localhost', port=6379, db=0)
current_minute = int(time.time() // window_seconds)
key = f"rate_limit_atomic:{user_id}:{current_minute}"
# The Lua script to execute
lua_script = """
local key = KEYS[1]
local limit = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local current_count = redis.call('INCR', key)
if current_count == 1 then
redis.call('EXPIRE', key, window)
end
if current_count > limit then
return 1 -- Rate limited
else
return 0 -- Not rate limited
end
"""
# Execute the Lua script atomically
# KEYS[1] is 'key'
# ARGV[1] is 'limit', ARGV[2] is 'window_seconds'
result = r.eval(lua_script, 1, key, limit, window_seconds)
return bool(result)
if __name__ == "__main__":
user = "user_bob"
requests_limit = 5
time_window = 60 # seconds
print(f"Testing atomic rate limiter for {user} ({requests_limit} reqs/{time_window}s)")
for i in range(1, 8):
if is_rate_limited_atomic(user, requests_limit, time_window):
print(f"Request {i}: Rate limited!")
else:
print(f"Request {i}: OK")
time.sleep(0.1) # Simulate some workDistributed Limiting Check
Which of the following are key benefits of using Redis for distributed rate limiting, especially when using Lua scripting?
Recap: Redis for Scale
Great job! You've learned how to build robust distributed rate limiters using Redis.
- Distributed Problem: In-memory limits fail with multiple application instances.
- Redis Solution: Provides a fast, centralized, and shared state for rate limit counters.
- Key Commands:
INCRandEXPIREare fundamental. - Atomicity with Lua: Crucial for preventing race conditions and ensuring correctness when multiple Redis commands are involved.
This approach is foundational for building scalable and resilient APIs.
자주 묻는 질문
“Redis를 활용한 분산 속도 제한” 강의는 무료인가요?
네 — “Redis를 활용한 분산 속도 제한” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 API Rate Limiting & Scalability Patterns 강의 전체를 잠금 해제할 수 있습니다. API Rate Limiting & Scalability Patterns 강의에는 총 4개의 강의가 포함되어 있습니다.
“Redis를 활용한 분산 속도 제한”에서 뭘 배우나요?
여러 서비스 인스턴스에서 작동하는 견고하고 확장 가능한 분산 속도 제한기를 Redis로 구축하는 방법을 학습합니다. 브라우저에서 직접 실행하는 실습 코드로 API Rate Limiting & Scalability Patterns을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
API Rate Limiting & Scalability Patterns을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 API Rate Limiting & Scalability Patterns은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“Redis를 활용한 분산 속도 제한” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 API Rate Limiting & Scalability Patterns 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 API Rate Limiting & Scalability Patterns 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 메모리 내 속도 제한기 설계
- Redis를 활용한 분산 속도 제한
- 속도 제한 초과 처리
- 요청 제한기 검증 및 모니터링