Skip to content

Instantly share code, notes, and snippets.

@leegilmorecode
Created December 31, 2021 13:49
Show Gist options
  • Save leegilmorecode/c4b39acdab19994641a789a7a8abdd6a to your computer and use it in GitHub Desktop.
Save leegilmorecode/c4b39acdab19994641a789a7a8abdd6a to your computer and use it in GitHub Desktop.
Example of API Gateway caching on AWS using the CDK
// create the rest API for accessing our lambdas
const api: apigw.RestApi = new apigw.RestApi(this, "blogs-api", {
description: "blogs api gateway",
deploy: true,
deployOptions: {
// this enables caching on our api gateway, with a ttl of five minutes (unless overridden per method)
cachingEnabled: true,
cacheClusterEnabled: true,
cacheDataEncrypted: true,
stageName: "prod",
dataTraceEnabled: true,
loggingLevel: apigw.MethodLoggingLevel.INFO,
cacheTtl: cdk.Duration.minutes(5),
throttlingBurstLimit: 100,
throttlingRateLimit: 100,
tracingEnabled: true,
metricsEnabled: true,
// Method deployment options for specific resources/methods. (override common options defined in `StageOptions#methodOptions`)
methodOptions: {
"/blogs/GET": {
throttlingRateLimit: 10,
throttlingBurstLimit: 10,
cacheDataEncrypted: true,
cachingEnabled: true,
cacheTtl: cdk.Duration.minutes(10),
loggingLevel: apigw.MethodLoggingLevel.INFO,
dataTraceEnabled: true,
metricsEnabled: true,
},
"/blogs/{id}/GET": {
throttlingRateLimit: 20,
throttlingBurstLimit: 20,
cachingEnabled: true,
cacheDataEncrypted: true,
cacheTtl: cdk.Duration.minutes(1),
loggingLevel: apigw.MethodLoggingLevel.INFO,
dataTraceEnabled: true,
metricsEnabled: true,
},
},
},
defaultCorsPreflightOptions: {
allowHeaders: ["Content-Type", "X-Amz-Date"],
allowMethods: ["GET"],
allowCredentials: true,
allowOrigins: apigw.Cors.ALL_ORIGINS, // we wouldn't do this in production
},
});
// add a /blogs resource
const blogs: apigw.Resource = api.root.addResource("blogs");
// integrate the lambda to the method - GET /blogs
blogs.addMethod(
"GET",
new apigw.LambdaIntegration(listBlogsHandler, {
proxy: true,
allowTestInvoke: true,
})
);
// integrate the lambda to the method - GET /blog/{id}
const blog: apigw.Resource = blogs.addResource("{id}");
blog.addMethod(
"GET",
new apigw.LambdaIntegration(getBlogHandler, {
proxy: true,
allowTestInvoke: true,
// ensure that our caching is done on the id path parameter
cacheKeyParameters: ["method.request.path.id"],
cacheNamespace: "blogId",
requestParameters: {
"integration.request.path.id": "method.request.path.id",
},
}),
{
requestParameters: {
"method.request.path.id": true,
},
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment