Redis를 활용한 분산 요청 제한
Redis, 원자적 연산, Lua 스크립트를 사용해 여러 게이트웨이와 서비스 인스턴스 사이에서 요청 제한 상태를 공유하고 경쟁 조건을 방지하는 방법을 익혀 보세요.
Redis를 활용한 분산 요청 제한은(는) CoddyKit의 무료 API Rate Limiting & Scalability Patterns 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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/7 AI 튜터), CoddyKit PRO로 업그레이드하면 API Rate Limiting & Scalability Patterns 강의 전체를 잠금 해제할 수 있습니다. API Rate Limiting & Scalability Patterns 강의에는 총 4개의 강의가 포함되어 있습니다.
“Redis를 활용한 분산 요청 제한”에서 뭘 배우나요?
Redis, 원자적 연산, Lua 스크립트를 사용해 여러 게이트웨이와 서비스 인스턴스 사이에서 요청 제한 상태를 공유하고 경쟁 조건을 방지하는 방법을 익혀 보세요. 브라우저에서 직접 실행하는 실습 코드로 API Rate Limiting & Scalability Patterns을(를) 배우며, 24/7 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 게이트웨이 통합 패턴
- 전역 속도 제한과 서비스별 속도 제한
- 동적 속도 제한 구성
- Redis를 활용한 분산 요청 제한