Sub topic 15
Throttling and protecting your backend
This chapter assumes you can deploy an HTTP API with SAM, as covered in the earlier chapters. It also assumes you know what a route and a stage are. Here you will limit how fast clients can call the API, so a traffic spike or a buggy client cannot overwhelm your Lambda function or the services behind it.
How throttling works
API Gateway throttles with a token bucket. The bucket refills at a steady rate (requests per second). Its size is the burst, the number of requests that can arrive at once. A request takes one token. If the bucket is empty, API Gateway rejects the request with 429 Too Many Requests and never calls your function.
Limits apply at several levels, and the lowest applicable one wins:
| Level | Scope | Who sets it |
|---|---|---|
| Account, per Region | All APIs in the account | AWS (default 10,000 requests per second, burst 5,000; can be raised) |
| Stage default | Every route in a stage | You |
| Route override | One route in a stage | You |
Check the current quotas in the API Gateway documentation, because AWS can change them.
Configuring limits in SAM
Set stage defaults and per-route overrides on the AWS::Serverless::HttpApi resource with DefaultRouteSettings and RouteSettings. The route key must match the route exactly.
Resources:
ItemsApi:
Type: AWS::Serverless::HttpApi
Properties:
DefaultRouteSettings:
ThrottlingRateLimit: 50
ThrottlingBurstLimit: 100
RouteSettings:
"POST /items":
ThrottlingRateLimit: 5
ThrottlingBurstLimit: 10Here every route allows 50 requests per second with bursts up to 100. Writes to POST /items are held to 5 per second, because they are the expensive operation.
Handling 429 in clients
A throttled response is not an error in your code. Clients should retry with exponential backoff and random jitter, and they should honor a Retry-After header if one is present. Retrying immediately makes the overload worse.
import random
import time
import requests
def get_with_backoff(url, attempts=5):
for attempt in range(attempts):
response = requests.get(url, timeout=10)
if response.status_code != 429:
return response
time.sleep(min(2 ** attempt, 30) + random.random())
return responseProtecting the backend
API Gateway throttling does not protect everything. Combine it with these controls:
- Reserved concurrency caps how many copies of a function run at once. It also guarantees that capacity to the function. Set it below the limit of any database or downstream service. Invocations over the cap return a throttle error, which API Gateway reports as a 5xx response.
- Timeouts on the function and on every outbound call stop slow dependencies from tying up concurrency.
- Authorizers keep anonymous callers away from your quota.
ItemsFunction:
Type: AWS::Serverless::Function
Properties:
ReservedConcurrentExecutions: 20Verifying the limit
Send a burst of requests and count the status codes. With the POST /items limit above, most requests in a fast loop should return 429.
for i in $(seq 1 40); do
curl -s -o /dev/null -w "%{http_code}\n" -X POST "$API_URL/items" \
-H 'content-type: application/json' -d '{"name": "widget"}'
done | sort | uniq -cExercise
A route has a rate limit of 5 and a burst limit of 10. A client sends 30 requests in a fraction of a second. Roughly how many reach Lambda, and what do the others receive?
Show answer
About 10, the size of the burst bucket, reach Lambda, plus a few more as tokens refill. The rest receive 429 Too Many Requests from API Gateway, and your function is never invoked for them.
Exercise
Why set reserved concurrency on a function that writes to a small database, even when API Gateway throttling is already configured?
Show answer
Throttling limits requests per second, not simultaneous executions. Slow requests can pile up and open many database connections at once. Reserved concurrency caps the number of running copies, which protects the database.