Serverless Throttling Pattern
Handle backpressure in serverless using SQS, token buckets, and Lambda concurrency limits to protect downstream services from burst traffic.
Overview
Here’s the production trap this pattern solves: Lambda scales on its own, but your RDS cluster, your payment gateway, and your partner’s API don’t. A marketing campaign goes live, a thousand concurrent invocations spin up in seconds, and the downstream service — sized for a hundred connections — falls over. Your functions are healthy; everything they call isn’t.
The throttling pattern inserts control points that keep the downstream load inside its real capacity. Three places to put them: a queue that buffers and paces traffic (SQS), a hard cap on how many function instances run at once (reserved concurrency), and a per-caller token budget that rejects excess requests (token bucket). They answer different questions — how fast do we drain the backlog?, how many of us run in parallel?, how often may this caller ask? — and real systems usually combine at least two.
This pattern is about protecting downstream capacity, not rejecting API requests. If what you need is per-client rate limiting on a public HTTP API, the Redis rate limiting recipe is the closer fit. And if the goal is ordering work rather than limiting it, that’s the priority queue pattern.
When to Use
Reach for throttling when the traffic shape and the downstream capacity don’t match:
- Lambda bursts overwhelm a database or API with fixed connection or rate limits
- A third-party API enforces a quota (requests/second) you must stay under
- Traffic spikes cause downstream timeouts or connection pool exhaustion
- Messages should be processed at a controlled pace, not as fast as possible
- Several Lambda functions compete for the same downstream resource
It’s the wrong tool when the downstream scales with you (DynamoDB on-demand, S3) — there, adding a queue just adds latency and cost for nothing.
Solution
Strategy 1: SQS with Controlled Batch Processing (Python)
The queue absorbs the burst; the consumer drains it at a pace the downstream survives. The levers are batch_size and max_batching_window: small batches plus a waiting window spread work over time instead of firing everything at once.
import boto3
import json
import time
sqs = boto3.client('sqs')
QUEUE_URL = "https://sqs.us-east-1.amazonaws.com/123456789012/order-queue"
def handler(event, context):
# Process messages in small batches with deliberate pacing
batch_size = 5
processed = 0
for record in event["Records"]:
message = json.loads(record["body"])
try:
process_order(message)
processed += 1
except Exception as e:
# Return message to queue for retry
raise e
return {"processed": processed}
def process_order(order: dict):
# Simulate downstream API call with rate limit awareness
api_client.post("/orders", json=order)
CDK: SQS with Visibility Timeout and Batch Size
from aws_cdk import (
Stack,
aws_sqs as sqs,
aws_lambda as lambda_,
aws_lambda_event_sources as events,
Duration,
)
from constructs import Construct
class ThrottledConsumerStack(Stack):
def __init__(self, scope: Construct, construct_id: str, **kwargs):
super().__init__(scope, construct_id, **kwargs)
# Queue with long visibility timeout to prevent concurrent processing
queue = sqs.Queue(self, "ThrottledQueue",
visibility_timeout=Duration.seconds(300),
receive_message_wait_time=Duration.seconds(20), # Long polling
)
# Dead-letter queue for failed messages
dlq = sqs.Queue(self, "DeadLetterQueue",
retention_period=Duration.days(14),
)
# Consumer Lambda with limited concurrency
consumer = lambda_.Function(self, "ThrottledConsumer",
runtime=lambda_.Runtime.PYTHON_3_12,
handler="handler.handler",
code=lambda_.Code.from_asset("lambda/consumer"),
timeout=Duration.seconds(60),
reserved_concurrent_executions=10, # Cap parallelism
)
# Small batch size to control throughput
consumer.add_event_source(events.SqsEventSource(
queue,
batch_size=5,
max_batching_window=Duration.seconds(30),
report_batch_item_failures=True,
))
# DLQ subscription
queue.add_to_dead_letter_queue(
max_receive_count=5,
dead_letter_queue=dlq,
)
Three details in that stack do most of the work. reserved_concurrent_executions=10 is the hard ceiling — AWS won’t run an eleventh instance no matter how deep the queue gets. report_batch_item_failures=True lets you retry only the messages that failed instead of the whole batch. And max_receive_count=5 on the DLQ stops a poison message from looping forever.
Strategy 2: Token Bucket Rate Limiter (TypeScript)
When the requirement is “caller X may make N requests per second”, queue pacing doesn’t help — you need an explicit budget. A DynamoDB row per caller holds the token count; each request spends tokens, and tokens refill at a fixed rate.
import { DynamoDBClient, UpdateItemCommand, GetItemCommand } from '@aws-sdk/client-dynamodb';
import { marshall, unmarshall } from '@aws-sdk/util-dynamodb';
const ddb = new DynamoDBClient({ region: 'us-east-1' });
class TokenBucket {
private tableName = 'rate_limits';
private capacity: number;
private refillRate: number; // tokens per second
constructor(capacity: number, refillRate: number) {
this.capacity = capacity;
this.refillRate = refillRate;
}
async allowRequest(bucketKey: string, tokens = 1): Promise<boolean> {
const now = Date.now();
// Get current bucket state
const getResponse = await ddb.send(new GetItemCommand({
TableName: this.tableName,
Key: marshall({ bucketKey }),
}));
let tokensAvailable = this.capacity;
let lastRefill = now;
if (getResponse.Item) {
const bucket = unmarshall(getResponse.Item);
tokensAvailable = parseFloat(bucket.tokens);
lastRefill = parseInt(bucket.lastRefill);
// Refill tokens based on elapsed time
const elapsedSeconds = (now - lastRefill) / 1000;
const refilled = elapsedSeconds * this.refillRate;
tokensAvailable = Math.min(this.capacity, tokensAvailable + refilled);
}
if (tokensAvailable < tokens) {
return false; // Rate limit exceeded
}
// Consume tokens
tokensAvailable -= tokens;
await ddb.send(new UpdateItemCommand({
TableName: this.tableName,
Key: marshall({ bucketKey }),
UpdateExpression: 'SET tokens = :t, lastRefill = :r',
ExpressionAttributeValues: marshall({
':t': tokensAvailable.toFixed(2),
':r': now.toString(),
}),
}));
return true;
}
}
// Usage in Lambda handler
const rateLimiter = new TokenBucket(100, 10); // 100 tokens, 10/sec refill
export const handler = async (event: any): Promise<{ statusCode: number }> => {
const apiKey = event.requestContext.identity.apiId;
const allowed = await rateLimiter.allowRequest(apiKey);
if (!allowed) {
return {
statusCode: 429,
body: JSON.stringify({ error: 'Rate limit exceeded' }),
};
}
// Process request
return { statusCode: 200 };
};
One thing to decide up front: what happens when DynamoDB is unreachable? This code fails closed — an exception means no allowRequest answer, and the handler returns an error. For most internal workloads that’s right. If the limiter protects a non-critical endpoint, wrap the call and fail open, because a rate limiter that takes down the API it protects is worse than no limiter.
Strategy 3: Reserved Concurrency + SQS (Python)
This is the pattern most teams actually ship: SQS buffers, reserved concurrency caps, and partial batch failure reporting retries only what broke.
import boto3
import json
import os
sqs = boto3.client('sqs')
QUEUE_URL = os.environ["QUEUE_URL"]
def handler(event, context):
failed_records = []
for record in event["Records"]:
try:
message = json.loads(record["body"])
process_with_rate_limit(message)
except Exception as e:
# Report individual failure for partial batch retry
failed_records.append({
"itemIdentifier": record["messageId"]
})
if failed_records:
return {
"batchItemFailures": failed_records
}
return {"batchItemFailures": []}
def process_with_rate_limit(message: dict):
# Check downstream capacity before processing
if not check_downstream_capacity():
raise Exception("Downstream capacity exceeded")
# Process with timeout
api_client.post("/process", json=message, timeout=10)
def check_downstream_capacity() -> bool:
# Query downstream health endpoint
response = api_client.get("/health")
return response.status_code == 200 and response.json()["capacity"] > 0
Explanation
Each strategy controls throughput at a different level, so the choice depends on what you’re protecting:
- SQS batch control — the queue is a shock absorber. Producers write at any rate; the consumer reads small batches (5-10 messages) on a batching window. Bursts become queue depth instead of downstream load. Costs almost nothing; adds latency equal to the queuing delay.
- Reserved concurrency — a hard ceiling on parallel instances.
reserved_concurrent_executions=10means the downstream sees at most 10 concurrent callers, guaranteed by the platform, not by your code. Free to configure; the trade-off is that excess invocations get throttled rather than slowed. - Token bucket — a budget per caller, enforced at request time. Precise (exactly N/sec per key) but the most expensive per call: every request costs a DynamoDB read plus a write, and the bucket itself becomes a dependency that can fail.
Sizing reserved concurrency. Start from the downstream limit, not from traffic. If the database pool allows 50 connections and each Lambda holds one, reserved concurrency is 50 — minus headroom for anything else that talks to that database (other functions, scheduled jobs, admin tooling). Getting this wrong in the conservative direction just means a deeper queue; getting it wrong in the other direction means an outage.
Failure modes to plan for. Queue depth grows faster than the consumer drains it → messages hit maxReceiveCount and land in the DLQ; alarm on ApproximateNumberOfMessagesVisible, not on consumer errors. A downstream 429 inside a batch → report the item in batchItemFailures and let SQS retry it with backoff; don’t rethrow the whole batch. The token bucket store is down → decide fail-open vs fail-closed per endpoint, because there’s no universal right answer.
The pieces from this pattern — the SQS consumer, the CDK stack, and the token bucket — are bundled as a runnable project in the companion repo.
Variants
| Approach | Control Level | Best For |
|---|---|---|
| SQS batch + batching window | Queue-level | Smoothing traffic bursts |
| Reserved concurrency | Execution-level | Capping parallel invocations |
| Token bucket (DynamoDB) | Request-level | Precise rate per API key |
| Leaky bucket | Request-level | Strict rate with no bursts |
| Circuit breaker | Downstream-level | Protecting failing services |
| Semaphore (in-function) | Instance-level | Limiting concurrent async calls |
Circuit breaker deserves a mention because it solves the adjacent problem: throttling protects a slow downstream, a circuit breaker protects a failing one. When the downstream starts returning 5xx, a breaker short-circuits calls until it recovers — combine it with throttling, don’t choose between them. When a pipeline needs several of these mechanisms chained together, the serverless function composition pattern shows how to wire them.
Best Practices
- Combine SQS with reserved concurrency — the queue smooths, the cap bounds. Together they give both backlog tolerance and a hard guarantee.
- Use partial batch failure reporting — return only failed message IDs in
batchItemFailures; SQS redelivers just those, not the whole batch. - Set visibility timeout to ~6x the Lambda timeout — prevents redelivery while a long invocation is still running.
- Watch the Throttles metric — frequent throttling means either the cap is too low or the downstream needs scaling; treat it as a signal, not noise.
- Use long polling —
receive_message_wait_time=20cuts empty receives and SQS API costs. - Alarm on queue depth, not errors —
ApproximateNumberOfMessagesVisibletrending up is the earliest warning that the consumer can’t keep pace.
For the producer side of this pattern — one event fanning out to many consumers — the serverless fanout pattern covers SNS/SQS topology. And when the shared resource is a relational database, serverless DB connection pooling is the complementary fix.
Common Mistakes
- No reserved concurrency — an uncapped function scales to thousands of instances and takes the database down with it. Cap any function that calls a fixed-capacity downstream.
- Batch size too large — 100-message batches amplify partial failures and long invocations; 5-10 is the right range for most workloads.
- Visibility timeout too short — SQS redelivers mid-processing and you get duplicates. Use ~6x the function timeout.
- Throttling Lambda while ignoring the downstream limit — if the API allows 50 req/s and you cap at 100 concurrent Lambdas each making 1 req/s, you’re still double the limit. Size from the downstream number.
- Crashing on a downstream 429 — retry the single message with backoff or report it in
batchItemFailures; don’t fail the batch. - Token bucket with no failure policy — decide fail-open vs fail-closed before the first outage finds out for you.
References
- AWS Lambda reserved concurrency — how the cap works and what happens to excess invocations.
- Using Lambda with Amazon SQS — batch size, batching window, and partial batch responses.
- API Gateway throttling and usage plans — rate and burst limits at the API level.
- Token bucket algorithm — the refill math behind per-caller budgets.
Frequently Asked Questions
What is the difference between throttling and rate limiting?
Throttling controls the rate of processing to protect downstream systems. Rate limiting rejects requests that exceed a defined rate. Throttling smooths traffic; rate limiting drops excess traffic. In serverless, SQS-based throttling smooths, and token bucket rate limiting drops.
How do I choose the right reserved concurrency value?
Start with the downstream service's connection pool size. If your database supports 50 connections and each Lambda uses 1 connection, set reserved concurrency to 50 minus headroom for other callers. Monitor downstream latency and adjust.
Can I use API Gateway throttling instead of Lambda throttling?
Yes. API Gateway usage plans enforce rate and burst limits at the API level, before Lambda is invoked. Use it for public HTTP APIs; use reserved concurrency for internal event-driven functions.
What happens when Lambda is throttled?
For synchronous invocations (API Gateway), the caller gets a 429. For asynchronous invocations (SNS, EventBridge), the event retries with backoff. For SQS triggers, the message stays in the queue and is retried on the next poll. Configure DLQs for all cases.
Related Resources
Serverless Fanout Pattern
Broadcast a single event to multiple independent consumers via SNS, EventBridge, or SQS so each consumer processes the event without coupling.
PatternServerless Function Composition Pattern
Chain serverless functions via Step Functions or orchestration layers to build multi-step workflows with retries, branching, and state management.
PatternPriority Queue Pattern: Schedule Tasks by Urgency
Use the Priority Queue pattern to process high-priority work first. See Python, Java, and JavaScript examples with heaps and Redis.
PatternServerless DB Connection Pooling Pattern
Manage database connections across serverless invocations by using external connection poolers, connection reuse, and lightweight clients to avoid connection exhaustion.
PatternServerless Warm Pool Pattern
Keep Lambda functions warm by sending periodic ping events to reduce cold start latency for latency-sensitive workloads.