typescriptamazon-web-servicescachingaws-api-gatewayaws-cdk

How to specify cache keys on AWS API Gateway using TS CDK?


I am managing my AWS infra with AWS CDK for TypeScript, specifically aws-cdk-lib@2.182.0. My goal is to enable API Gateway caching for an endpoint like GET subpath/{customerId}/path using customerId as the cache key. Effectively, on AWS console, it should look like this after deployment: enter image description here

But this is what I am getting currently: enter image description here

This my API gateway deployOptions:

deployOptions: {
  stageName: props.stageName,
  metricsEnabled: true,
  cachingEnabled: true,
  cacheClusterEnabled: true,
  cacheClusterSize: '0.5',
  cacheTtl: Duration.seconds(3600),
  cacheDataEncrypted: true,
},

Note: This is a REST API from API Gateway V1
And my method configuration:

methods.addMethod('GET', new LambdaIntegration(lambda), {
      authorizer: requestAuthorizer,
      requestValidator: requestParamValidator,
      requestParameters: {
        'method.request.path.customerId': true,
      },
      methodResponses: [
        {
          statusCode: '200',
        },
        {
          statusCode: '404',
        },
        {
          statusCode: '401',
        },
      ],
    });

I tried adding the cacheKeyParameters parameter like this:

methods.addMethod('GET', new LambdaIntegration(lambda), {
      authorizer: requestAuthorizer,
      requestValidator: requestParamValidator,
      cacheKeyParameters: ['method.request.path.customerId'],
      requestParameters: {
        'method.request.path.customerId': true,
      },
      methodResponses: [
        {
          statusCode: '200',
        },
        {
          statusCode: '404',
        },
        {
          statusCode: '401',
        },
      ],
    });

or inside methodOptions in my deployOptions that I showed, but I get this compile error:
Object literal may only specify known properties, and cacheKeyParameters does not exist in type MethodOptions
Even if I ignore this with @ts-ignore, it does not work and the result is still: enter image description here

I also tried:

myMethod.addPropertyOverride('CacheKeyParameters', [
  'method.request.path.customerId',
]);

or

myMethod.addPropertyOverride('cacheKeyParameters', [
  'method.request.path.customerId',
]);

But then the deployment failed with:
[#: extraneous key [CacheKeyParameters] is not permitted]
or
[#: extraneous key [cacheKeyParameters] is not permitted]

That makes sense since the CDK documentation for MethodOptions does not have cacheKeyParameters or any cache-related parameter. But then, how would I do that?

Not even ChatGPT o1 could help me with this one XD


Solution

  • Cache key parameters exist on API Gateway's integration object and not method object shown here and here