How to add scaling policy to RDS DatabaseCluster with CDK?

Viewed 727

I've deployed an AWS CDK RDS DatabaseCluster with the following code:

 const cluster = new rds.DatabaseCluster(this, "Cluster", {
  engine: rds.DatabaseClusterEngine.AURORA_POSTGRESQL,
  instanceProps: {
    instanceType: ec2.InstanceType.of(
      ec2.InstanceClass.BURSTABLE3,
      ec2.InstanceSize.MEDIUM
    ),
    vpcSubnets: {
      subnetType: ec2.SubnetType.PUBLIC,
    },
    vpc,
  },
  parameterGroup: rds.ParameterGroup.fromParameterGroupName(
    this,
    "ParameterGroup",
    "default.aurora-postgresql11"
  ),
  storageEncrypted: true,
  storageEncryptionKey: customKey,
  credentials: rds.Credentials.fromGeneratedSecret("dbAdmin"),
});

After the cluster is deployed I can easily add an auto scaling policy via the web console (click the cluster and then in the top right go to "Actions" -> add replica auto scaling).

I can find no way to do this with the CDK. The only thing about scaling I can find is this https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-rds.ServerlessScalingOptions.html

But it's unclear to me how to implement this or if this is even the right one.

Has anybody done this with the CDK or can someone give me a hint on how to achieve this?

1 Answers

You need to use the @aws-cdk/aws-applicationautoscaling module.

The general way to use this is to:

  1. Create a scaling target. What you want to scale and the boundaries for scaling.
  2. Create a scaling metric against the scaling target. How you want to scale.

For your use-case, to have read replica scaling, this will work:

    import { PredefinedMetric, ScalableTarget, ServiceNamespace } from '@aws-cdk/aws-applicationautoscaling';

    const readCapacity = new ScalableTarget(
      this,
      'rdsScaling',
      {
        serviceNamespace: ServiceNamespace.RDS,
        minCapacity: 1,
        maxCapacity: 4,
        resourceId: 'cluster:'+cluster.clusterIdentifier,
        scalableDimension: 'rds:cluster:ReadReplicaCount',
      }
    );

    readCapacity.scaleToTrackMetric(
      'rdsScalingTracking',
      {
        targetValue: 50,
        predefinedMetric: PredefinedMetric.RDS_READER_AVERAGE_CPU_UTILIZATION,
      }
    );

Resource ID is specific to the service you are scaling. For RDS the documentation states "cluster:clusterId".

Related