How to Cache in AWS API Gateway for Faster Responses
To cache in
AWS API Gateway, enable caching on a stage and configure a cache key to store responses. This reduces backend calls by returning cached data for repeated requests based on specified parameters.Syntax
Enable caching by setting cacheClusterEnabled to true in the stage settings. Define cacheKeyParameters in method request to specify which request parts form the cache key. Set cacheTtlInSeconds to control how long responses stay cached.
json
{
"stageName": "prod",
"cacheClusterEnabled": true,
"cacheClusterSize": "0.5",
"methodSettings": {
"*/*": {
"cachingEnabled": true,
"cacheTtlInSeconds": 300,
"cacheDataEncrypted": true,
"cacheKeyParameters": [
"method.request.querystring.param1",
"method.request.header.Authorization"
]
}
}
}Example
This example shows how to enable caching on the prod stage with a 5-minute TTL. It caches responses based on a query string parameter and an authorization header, encrypting cached data for security.
json
{
"restApiId": "a1b2c3d4",
"stageName": "prod",
"cacheClusterEnabled": true,
"cacheClusterSize": "0.5",
"methodSettings": {
"GET /items": {
"cachingEnabled": true,
"cacheTtlInSeconds": 300,
"cacheDataEncrypted": true,
"cacheKeyParameters": [
"method.request.querystring.category",
"method.request.header.Authorization"
]
}
}
}Output
Caching enabled on stage 'prod' for GET /items with 300 seconds TTL.
Common Pitfalls
- Not enabling caching on the stage disables all cache settings.
- Forgetting to specify
cacheKeyParameterscauses all requests to share the same cache, leading to incorrect responses. - Setting a very long TTL can serve stale data.
- Not encrypting sensitive cached data risks security.
json
{
"stageName": "prod",
"cacheClusterEnabled": false,
"methodSettings": {
"GET /items": {
"cachingEnabled": true,
"cacheTtlInSeconds": 600
}
}
}
{
"stageName": "prod",
"cacheClusterEnabled": true,
"cacheClusterSize": "0.5",
"methodSettings": {
"GET /items": {
"cachingEnabled": true,
"cacheTtlInSeconds": 600,
"cacheKeyParameters": ["method.request.querystring.category"],
"cacheDataEncrypted": true
}
}
}Quick Reference
- cacheClusterEnabled: Enables caching on the stage (true/false).
- cacheClusterSize: Size of cache cluster (e.g., 0.5, 1.6, 6.1).
- cachingEnabled: Enables caching per method.
- cacheTtlInSeconds: Time to live for cached responses.
- cacheKeyParameters: Request parts used to create cache keys.
- cacheDataEncrypted: Encrypt cached data for security.
Key Takeaways
Enable caching on the API Gateway stage by setting cacheClusterEnabled to true.
Specify cacheKeyParameters to control which request parts form the cache key.
Set cacheTtlInSeconds to define how long responses stay cached.
Encrypt cached data if it contains sensitive information.
Avoid long TTLs to prevent serving stale data.