AWS Builder Center
Building Resilient Cloud Workflows: Implementing Real-Time Rate Limiting with AWS Lambda and Amazon DynamoDB

Building Resilient Cloud Workflows: Implementing Real-Time Rate Limiting with AWS Lambda and Amazon DynamoDB

Learn how to protect serverless architectures against traffic spikes and denial-of-service attempts by implementing an atomic, sliding-window rate limiter using AWS Lambda and Amazon DynamoDB.

In distributed, serverless applications, managing incoming request velocity is critical for ensuring resource availability, preventing runaway execution costs, and protecting downstream dependencies. While Amazon API Gateway provides built-in token-bucket throttling, many workloads require dynamic, tenant-aware, or identity-specific rate limits enforced closer to the business logic.
This guide explores how to design and implement a distributed, low-latency rate limiter leveraging AWS Lambda and Amazon DynamoDB with atomic counters.

Architecture Overview

The rate-limiting pipeline sits inline with the request flow:
  1. Request Ingestion: Incoming API requests hit API Gateway and trigger an authorizer or an edge-routing Lambda function.
  1. Identifier Extraction: The function identifies the client using an API key, authenticated user ID, or client IP.
  1. Atomic Evaluation: Lambda queries DynamoDB to check current usage within the current rolling window.
  1. Execution Decision:
  • If the counter is within the threshold, DynamoDB atomically increments the usage count and the request proceeds.
  • If the counter exceeds the threshold, the function immediately returns an HTTP 429 (Too Many Requests).
[ Client ]
│
▼
[ Amazon API Gateway ]
│
▼
[ Evaluator Lambda ] ──(Atomic Update / Check)──► [ Amazon DynamoDB ]
│ │
├─► Allowed: Forward to Core Service └─► TTL auto-purges expired windows
└─► Denied: Return HTTP 429

Step 1: Designing the DynamoDB Table

To handle rapid, high-concurrency requests with automatic cleanup:
  • Partition Key ( PK ): String formatted as  USER#<ClientID>#WINDOW#<TimestampBucket>  (e.g., bucketed by minute).
  • Attribute ( request_count ): Number representing requests processed in this bucket.
  • TTL Attribute ( expires_at ): Epoch timestamp set to auto-expire records after 1–2 hours to prevent storage bloat.
Table Configuration (AWS CLI)
Bash
aws dynamodb create-table \
--table-name ClientRateLimits \
--attribute-definitions AttributeName=PK,AttributeType=S \
--key-schema AttributeName=PK,KeyType=HASH \
--billing-mode PAY_PER_REQUEST
Enable Time to Live (TTL):
Bash
aws dynamodb update-time-to-live \
--table-name ClientRateLimits \
--time-to-live-specification "Enabled=true, AttributeName=expires_at"

Step 2: Implementation Logic in AWS Lambda

To avoid race conditions under heavy concurrent load, use DynamoDB's  UpdateItem  with conditional expressions rather than a separate read-then-write operation.
Example (Node.js / AWS SDK v3)
JavaScript
import { DynamoDBClient, UpdateItemCommand } from "@aws-sdk/client-dynamodb";

const client = new DynamoDBClient({});
const RATE_LIMIT_TABLE = process.env.RATE_LIMIT_TABLE;
const MAX_REQUESTS_PER_MINUTE = 60;

export const handler = async (event) => {
const clientId = event.requestContext?.authorizer?.claims?.sub || event.requestContext?.identity?.sourceIp || "anonymous";
// Create a 1-minute time bucket (in epoch seconds)
const now = Math.floor(Date.now() / 1000);
const currentBucket = Math.floor(now / 60) * 60;
const pk = `USER#${clientId}#WINDOW#${currentBucket}`;
const ttl = currentBucket + 3600; // retain record for 1 hour

try {
const response = await client.send(new UpdateItemCommand({
TableName: RATE_LIMIT_TABLE,
Key: {
PK: { S: pk }
},
UpdateExpression: "ADD #count :inc SET #ttl = if_not_exists(#ttl, :ttl)",
ExpressionAttributeNames: {
"#count": "request_count",
"#ttl": "expires_at"
},
ExpressionAttributeValues: {
":inc": { N: "1" },
":ttl": { N: ttl.toString() },
":limit": { N: MAX_REQUESTS_PER_MINUTE.toString() }
},
ConditionExpression: "attribute_not_exists(#count) OR #count < :limit",
ReturnValues: "UPDATED_NEW"
}));

return {
statusCode: 200,
body: JSON.stringify({ message: "Request accepted", currentCount: response.Attributes.request_count.N })
};

} catch (error) {
if (error.name === "ConditionalCheckFailedException") {
return {
statusCode: 429,
headers: {
"Retry-After": (currentBucket + 60 - now).toString()
},
body: JSON.stringify({ error: "Too Many Requests", message: "Rate limit exceeded. Please retry later." })
};
}

console.error("DynamoDB error:", error);
return {
statusCode: 500,
body: JSON.stringify({ error: "Internal Server Error" })
};
}
};

Best Practices & Production Considerations

  • DynamoDB Accelerator (DAX) vs. In-Memory Caching: If microsecond latency is required, consider pairing this with an in-memory Redis cluster (Amazon ElastiCache) or Lambda execution context memory caching for frequent hits.
  • Graceful Degradation: Always set up fallback logic (e.g., soft fail-open) so that an unexpected DynamoDB outage does not completely block legitimate application traffic.
  • Monitoring & Alerts: Publish custom metrics to Amazon CloudWatch whenever a  429  is generated to detect coordinated scrapers or DDoS patterns in real time.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article