Sub topic 15
Throttling and protecting your backend
This chapter assumes you can deploy the SAM template from the earlier chapters and call it with curl. It covers how API Gateway limits request rates, how to set limits per route, how Lambda concurrency limits fit in, and how clients should react to rejections.
Why throttle at all
An HTTP API will accept traffic faster than most backends can handle it. A buggy client loop, a scraper, or a traffic spike can exhaust your Lambda concurrency, overload a database behind the function, or run up your bill. Throttling puts a ceiling on request rate at the edge, before the request reaches your code.
Limits apply in layers. Each layer protects something different.
How API Gateway throttles
API Gateway uses a token bucket algorithm. Think of a bucket that holds tokens.
- Each request removes one token.
- The bucket refills at the rate limit, in requests per second.
- The bucket can hold at most the burst limit number of tokens.
A burst limit lets a short spike through without rejecting requests. After the bucket empties, only the steady refill rate gets through. A request that finds the bucket empty is rejected with 429 Too Many Requests. Your Lambda function is never invoked for it, so you are not billed for that invocation.
There are two levels of limits for an HTTP API:
| Level | Who sets it | Scope |
|---|---|---|
| Account-level quota | AWS, per Region | All APIs in your account in that Region |
| Stage and route limits | You | One stage, or one route within it |
The account-level quota has a default steady rate and burst that you can ask AWS to raise. Check the current numbers in the Service Quotas console, because they change over time and differ by Region. Your own limits can only lower the effective limit for a route. They cannot raise it above the account quota.
Configuring limits in SAM
Set a default for every route on a stage, then override specific routes. In SAM, use DefaultRouteSettings and RouteSettings on the AWS::Serverless::HttpApi resource. The keys in RouteSettings are route keys exactly as they appear in the event, such as POST /items.
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless::Application
Resources: {}That fragment is only a skeleton. The working version below replaces it. It reuses the earlier items API and adds limits.
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
ItemsApi:
Type: AWS::Serverless::HttpApi
Properties:
DefaultRouteSettings:
ThrottlingBurstLimit: 100
ThrottlingRateLimit: 50
RouteSettings:
"POST /items":
ThrottlingBurstLimit: 20
ThrottlingRateLimit: 5
ItemsFunction:
Type: AWS::Serverless::Function
Properties:
Runtime: python3.13
Handler: app.handler
CodeUri: src/
MemorySize: 256
Timeout: 10
ReservedConcurrentExecutions: 10
Events:
GetItem:
Type: HttpApi
Properties:
ApiId: !Ref ItemsApi
Path: /items/{id}
Method: GET
CreateItem:
Type: HttpApi
Properties:
ApiId: !Ref ItemsApi
Path: /items
Method: POSTHere every route allows 50 requests per second with a burst of 100. The write route POST /items is stricter: 5 per second with a burst of 20. Writes usually cost more downstream, so they deserve a tighter limit than reads.
Lambda concurrency as a second guard
API Gateway limits requests per second. Lambda limits how many invocations run at the same time. These are different measures. A slow function can pile up concurrent executions even at a modest request rate. As a rough guide, concurrency is about requests per second multiplied by average duration in seconds.
ReservedConcurrentExecutions does two things for one function:
- It guarantees that function that many concurrent executions, taken from your account's shared pool.
- It caps the function at that number, so it cannot overwhelm a downstream resource that supports only a few connections.
When the cap is reached, Lambda rejects further invocations. API Gateway then returns an error to the client, typically a 5xx response rather than a 429. A 5xx during a traffic spike therefore does not always mean your code crashed. Check the function's Throttles metric in CloudWatch to tell the two apart.
What HTTP APIs do not offer
REST APIs have usage plans and API keys, which let you give each customer their own quota. HTTP APIs do not have them. If you need per-client quotas, you have these options:
- Use a Lambda authorizer to identify the caller, then enforce a quota in your own code, for example with counters in DynamoDB.
- Put AWS WAF in front of a REST API, or CloudFront in front of your API, and use rate-based rules to block abusive IP addresses.
- Choose a REST API when usage plans are a hard requirement. See the earlier chapter on choosing between the two.
The built-in route limits are shared by all callers of a route. One noisy client can use up the whole bucket and cause 429 responses for everyone else.
Testing the limits
Send a burst of parallel requests and count the status codes. Replace the placeholder URL with your ApiUrl output.
API_URL="https://abc123.execute-api.us-east-1.amazonaws.com"
seq 1 300 | xargs -P 50 -I{} \
curl -s -o /dev/null -w "%{http_code}\n" -X POST "$API_URL/items" \
-H 'content-type: application/json' -d '{"name": "widget"}' \
| sort | uniq -cWith the POST /items limits above, you should see mostly 201 and some 429. The exact split varies, because the bucket refills while the test runs and throttling is applied on a best-effort basis. Do not rely on the numbers being exact. Treat limits as protection, not as precise counters.
Making clients behave
A 429 is a signal to slow down. Clients should retry with exponential backoff and random jitter, so that many clients do not retry at the same instant.
import random
import time
import urllib.error
import urllib.request
def call_with_backoff(url, attempts=5, base=0.2, cap=5.0):
for attempt in range(attempts):
try:
with urllib.request.urlopen(url) as response:
return response.status, response.read()
except urllib.error.HTTPError as err:
if err.code not in (429, 500, 502, 503, 504):
return err.code, err.read()
if attempt == attempts - 1:
return err.code, err.read()
delay = min(cap, base * (2 ** attempt))
time.sleep(random.uniform(0, delay))
raise RuntimeError("unreachable")
if __name__ == "__main__":
status, body = call_with_backoff(
"https://abc123.execute-api.us-east-1.amazonaws.com/items/42"
)
print(status, body)Only retry requests that are safe to repeat. A GET is safe. A POST that creates a record may create it twice unless your handler accepts an idempotency key.
Watching for throttling
Two sources tell you throttling is happening:
- The API's
4xxmetric in CloudWatch rises. Access logs, covered in the previous chapter, show the status code per request, so you can filter for 429. - The Lambda
ThrottlesandConcurrentExecutionsmetrics show function-level limits.
Set a CloudWatch alarm on throttles so you learn about sustained rejections before customers report them.
Common mistakes
- Setting the burst lower than the rate. Keep burst at or above the rate, or short spikes are rejected needlessly.
- Assuming a route limit is per client. It is shared by all callers.
- Setting reserved concurrency to
0. This blocks all invocations of the function. - Reading every 5xx as a code bug without checking Lambda throttles.
- Treating throttling as security. It limits load, but it does not authenticate anyone. Use authorizers for access control.
Exercise
Your function writes to a database that allows only 20 simultaneous connections. Clients report intermittent 5xx errors during traffic spikes, and your logs show no exceptions. Which two settings would you use to protect the database, and where would you look to confirm throttling is the cause?
Show answer
Set ReservedConcurrentExecutions on the function to 20 or less so it cannot open more connections than the database allows, and set lower ThrottlingRateLimit and ThrottlingBurstLimit values on the busy routes so fewer requests arrive at once. To confirm the cause, check the Lambda Throttles metric in CloudWatch, and check the API's access logs for the status codes returned to clients.
Exercise
A route is configured with a rate limit of 10 and a burst limit of 50. Roughly how does a client see this limit if it sends 200 requests in one second?
Show answer
The bucket holds up to 50 tokens, so about the first 50 requests (plus a few refilled tokens) succeed immediately. The remaining requests find the bucket empty and receive 429 Too Many Requests, because tokens refill at only 10 per second.