API 요청 제한 및 조절
요청 제한이 API를 악용, 무차별 대입, 서비스 거부 공격으로부터 보호하는 방식과 토큰 버킷 및 슬라이딩 윈도 전략을 구현하는 방법을 익혀 보세요.
API 요청 제한 및 조절은(는) CoddyKit의 무료 Secure Coding & OWASP Top 10 for Backend 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Secure Coding & OWASP Top 10 for Backend 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Secure Coding & OWASP Top 10 for Backend 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Why Rate Limiting?
Rate limiting caps how many requests a client can make in a time window. It protects APIs from brute-force attacks, scraping, accidental loops, and denial-of-service.
It is a key control listed under API security best practices.
Throttling vs Limiting
Rate limiting rejects requests over a hard cap; throttling slows them down (queuing or delaying) instead of rejecting outright. Both manage load and abuse, often used together.
What to Limit On
Choose a key to count requests against:
- API key or user ID for authenticated traffic
- IP address for anonymous traffic
- Endpoint sensitivity (stricter limits on login)
Combining keys gives finer control and resists simple bypasses.
Fixed Window
The simplest approach counts requests in a fixed time window, resetting the counter each period. It is easy but allows bursts at window edges (twice the limit across a boundary).
import time
window = {}
LIMIT = 5
PERIOD = 60
def allow(key):
now = int(time.time() // PERIOD)
count = window.get((key, now), 0)
if count >= LIMIT:
return False
window[(key, now)] = count + 1
return TrueToken Bucket
The token bucket refills tokens at a steady rate up to a capacity. Each request consumes a token; an empty bucket means the request is rejected. It allows controlled bursts while enforcing an average rate.
import time
class TokenBucket:
def __init__(self, rate, capacity):
self.rate = rate
self.capacity = capacity
self.tokens = capacity
self.last = time.time()
def allow(self):
now = time.time()
self.tokens = min(self.capacity, self.tokens + (now - self.last) * self.rate)
self.last = now
if self.tokens >= 1:
self.tokens -= 1
return True
return FalseSliding Window
The sliding window tracks timestamps of recent requests and counts only those within the last N seconds. It avoids the burst problem of fixed windows at the cost of more bookkeeping.
Distributed Rate Limiting
With multiple servers, counters must be shared. A central store like Redis holds the counters so limits apply across the whole cluster, not per instance. Use atomic operations to avoid race conditions.
Communicating Limits
Tell clients about their limits with response headers so well-behaved clients can back off.
headers = {
'X-RateLimit-Limit': '100',
'X-RateLimit-Remaining': '42',
'X-RateLimit-Reset': '1717000000',
'Retry-After': '30',
}
for k, v in headers.items():
print(k + ': ' + v)Status Codes
Return 429 Too Many Requests when a client exceeds the limit, ideally with a Retry-After header. This is the standard signal clients and SDKs expect.
Protecting Sensitive Endpoints
Apply stricter limits to high-risk endpoints like login, password reset, and OTP verification. Tight limits here directly blunt brute-force and credential-stuffing attacks.
- Login: a few attempts per minute
- Password reset: a few per hour
- General reads: generous limits
Avoiding Pitfalls
Watch for bypasses: rotating IPs, missing limits on some routes, and limits that reset on server restart. Place rate limiting at the gateway or middleware layer so every route is covered consistently.
Quick Check
Test your understanding of rate limiting.
Recap
You learned why APIs need rate limiting, how to choose a limiting key, and the trade-offs of fixed-window, token-bucket, and sliding-window strategies. You also saw distributed limiting with Redis, the 429 response, and stricter limits for sensitive endpoints.
자주 묻는 질문
“API 요청 제한 및 조절” 강의는 무료인가요?
네 — “API 요청 제한 및 조절” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Secure Coding & OWASP Top 10 for Backend 강의 전체를 잠금 해제할 수 있습니다. Secure Coding & OWASP Top 10 for Backend 강의에는 총 4개의 강의가 포함되어 있습니다.
“API 요청 제한 및 조절”에서 뭘 배우나요?
요청 제한이 API를 악용, 무차별 대입, 서비스 거부 공격으로부터 보호하는 방식과 토큰 버킷 및 슬라이딩 윈도 전략을 구현하는 방법을 익혀 보세요. 브라우저에서 직접 실행하는 실습 코드로 Secure Coding & OWASP Top 10 for Backend을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Secure Coding & OWASP Top 10 for Backend을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Secure Coding & OWASP Top 10 for Backend은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.
“API 요청 제한 및 조절” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Secure Coding & OWASP Top 10 for Backend 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Secure Coding & OWASP Top 10 for Backend 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 안전한 RESTful API 설계
- GraphQL API 보안
- SSRF 공격 방지
- API 요청 제한 및 조절