AWS API Gateway Rate Limiting — Usage Plans, Throttling, and Burst Control
In this tutorial, you will learn about AWS API Gateway Rate Limiting. We cover key concepts, practical examples, and best practices to help you master this topic.
AWS API Gateway provides rate limiting through usage plans that define throttle and burst limits per API key, enabling tiered access control for Serverless and REST APIs deployed on AWS.
What You'll Learn
- How AWS API Gateway rate limiting works with usage plans
- How to configure throttle and burst limits
- How to associate API keys with usage plans for tiered access
Why It Matters
AWS API Gateway handles serverless APIs at scale. Without rate limiting, a single client can trigger Lambda invocations that exhaust your concurrency limits and generate excessive costs. Usage plans protect both your API and your AWS bill.
Real-World Use
DodaTech's serverless API runs on API Gateway + Lambda. Three usage plans are configured: Free (10 req/s, burst 20), Pro (100 req/s, burst 50), and Enterprise (1000 req/s, burst 200). API keys are assigned to the appropriate plan, and clients exceeding limits receive 429 responses with throttling headers.
flowchart LR
A["API Request\n+ Key"] --> B["API Gateway"]
B --> C{"Usage Plan\ncheck"}
C -->|"Within throttle"| D["Lambda\nFunction"]
C -->|"Exceeded"| E["429 Too Many\nRequests"]
D --> F["Response"]
style B fill:#dbeafe,stroke:#2563eb
style C fill:#fef3c7,stroke:#d97706
style E fill:#fecaca,stroke:#dc2626
Creating Usage Plans
import boto3
client = boto3.client('apigateway')
# Create a usage plan with throttle and quota
usage_plan = client.create_usage_plan(
name='pro-plan',
description='Pro tier: 100 req/s, 50000 req/day',
apiStages=[{
'apiId': 'your-api-id',
'stage': 'prod'
}],
throttle={
'burstLimit': 50,
'rateLimit': 100.0
},
quota={
'limit': 50000,
'period': 'DAY',
'offset': 0
}
)
print(f"Usage plan created: {usage_plan['id']}")
Associating API Keys
# Create an API key
api_key = client.create_api_key(
name='partner-pro-key',
description='Pro tier key for Partner ABC',
enabled=True,
stageKeys=[{
'restApiId': 'your-api-id',
'stageName': 'prod'
}]
)
# Associate key with usage plan
client.create_usage_plan_key(
usagePlanId=usage_plan['id'],
keyId=api_key['id'],
keyType='API_KEY'
)
print(f"API Key: {api_key['value']}")
print(f"Associated with plan: {usage_plan['id']}")
Lambda Authorizer with Rate Limiting
import json
def lambda_handler(event, context):
# Extract API key from request
api_key = event['headers'].get('x-api-key', '')
# Look up usage plan for key (from DynamoDB)
plan = get_usage_plan(api_key)
# Generate IAM policy with rate limit context
policy = {
'principalId': api_key,
'policyDocument': {
'Version': '2012-10-17',
'Statement': [{
'Action': 'execute-api:Invoke',
'Effect': 'Allow',
'Resource': event['methodArn']
}]
},
'context': {
'rateLimit': str(plan['rateLimit']),
'burstLimit': str(plan['burstLimit']),
'tier': plan['tier']
}
}
return policy
Common Mistakes
1. Not Setting Per-Method Throttles
API Gateway allows per-method throttles. Auth endpoints should have lower limits than data endpoints even within the same usage plan.
2. Ignoring Burst Limits
Burst allows short traffic spikes. Set burst 2-5x the rate limit to handle legitimate traffic patterns.
3. Not Enabling API Keys
Without API key requirement, usage plans are not enforced. Enable API key requirement on your API methods.
4. Forgetting to Deploy After Changes
Usage plan changes may require redeploying the API stage. Always deploy after modifying throttles.
5. Not Monitoring Throttle Events
CloudWatch metrics track throttle count and rate. Set up dashboards and alarms for throttle events.
Practice Questions
- What AWS resource defines rate limits for API keys?
- What is the difference between rateLimit and burstLimit?
- How do you associate an API key with a usage plan?
- What happens when a request exceeds the throttling limit?
- How do you set up per-API-key rate limits?
Answers
- Usage Plan. 2. rateLimit is the sustained requests per second; burstLimit is the short-term maximum. 3. Call create_usage_plan_key with the plan ID and key ID. 4. API Gateway returns a 429 Too Many Requests response. 5. Create separate API keys for each client and assign them to different usage plans.
Challenge
Build a CloudFormation template that creates three usage plans (free, pro, enterprise) with appropriate throttle and burst limits, creates API keys for test partners, associates keys with the correct plans, and configures CloudWatch alarms for throttle events.
FAQ
Mini Project
Create a complete AWS API Gateway rate limiting setup with: three usage plans (Free/Pro/Enterprise), API key generation and plan association, a Lambda authorizer for key validation, CloudWatch dashboards for throttle monitoring, and a management script for creating and rotating API keys.
What's Next
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro