DynamoDB is a key-value NoSQL, serverless, fully managed database service provided by AWS. This blog will teach you how to create DynamoDB table using AWS CDK. We will also learn different configuration options when creating a DynamoDB table using CDK.

Creating a DyanmoDB table using CDK

Let us look into code that creates a simple DynamoDB table.

import { Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb';

export class AwsDynamodbStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    new dynamodb.Table(this, "SimpleDynamoDB", {
      partitionKey: {
        name: "id",
        type: dynamodb.AttributeType.STRING
      },
    })
  }
}

When creating a DynamoDB table using CDK, the only required parameter is the partition key. We need to pass the name and type of partition key.

When we deploy this code, it creates a DynamoDB table. We can see that on the AWS console as well.

DynamoDB created after deploying stack
DynamoDB was created after deploying a stack.

By default, CDK creates a DynamoDB table with a PROVISIONED billing model with 5 RCUs and WCUs. We can change how many RCUs and WCUs should be allocated for our table. We can also configure autoscaling for our table.

Configuring AutoScaling for DynamoDB table using CDK

When configuring autoscaling, we can decide the maximum capacity for the table and the conditions on which this capacity should be changed.

Let us go through the below code that configures AutoScaling for the DynamoDB table.

import { Stack, StackProps } from 'aws-cdk-lib';
import * as appScaling from 'aws-cdk-lib/aws-applicationautoscaling';
import { Construct } from 'constructs';
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb';

export class AwsDynamodbStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    const dynamoDBTable = new dynamodb.Table(this, "SimpleDynamoDB", {
      partitionKey: {
        name: "id",
        type: dynamodb.AttributeType.STRING
      },
    });

    const readScaling = dynamoDBTable.autoScaleReadCapacity({ minCapacity: 1, maxCapacity: 10 })

    readScaling.scaleOnUtilization({
      targetUtilizationPercent: 65
    })

    const writeScaling = dynamoDBTable.autoScaleWriteCapacity({ minCapacity: 1, maxCapacity: 10 })

    writeScaling.scaleOnUtilization({
      targetUtilizationPercent: 65
    })

    writeScaling.scaleOnSchedule('ScaleUpInMorning', {
      schedule: appScaling.Schedule.cron({hour: '6', minute: '30'}),
      maxCapacity: 10,
      minCapacity: 5,
    })

    writeScaling.scaleOnSchedule('ScaleDownInNight', {
      schedule: appScaling.Schedule.cron( { hour: '22', minute: '00' }),
      maxCapacity: 5,
      minCapacity: 1,
    })

  }
}

In this code,

  1. First, we must import `appScaling` from `aws-cdk-lib/aws-applicationautoscaling`. This is necessary to schedule autoscaling for a table.
  2. Then we have enabled read and write autoscaling for a table. This has a limit of a minimum of 1 and a Maximus of 10 capacity units.
  3. For read autoscaling, we have set up scale RCUs on utilization. This means that when our read capacity reaches 65%, our RCUs will keep increasing to a maximum of 10RCUs.
  4. For write autoscaling, we have set up the scale on utilization along with scale on schedule. In the above code, WCUs will scale every morning on 6:30 AM and scale down every night on 22:00.

Let us deploy this code and validate our changes.

DynamoDB table autoscaling using AWS CDK
DynamoDB table autoscaling using AWS CDK

Point in time recovery for DynamoDB table using CDK

With a point-in-time recovery, we can restore the DyanmoDB table to extract points in time. This protects us from accidental writes or deletes in the DynamoDB table. We can enable point-in-time recovery for the DynamoDB table using CDK with one line of code.

const dynamoDBTable = new dynamodb.Table(this, "SimpleDynamoDB", {
      partitionKey: {
        name: "id",
        type: dynamodb.AttributeType.STRING
      },
      pointInTimeRecovery: true,
    });

Create DynamoDB table using On-demand billing mode

We can also create a DynamoDB table using the on-demand billing mode. Using on-demand billing mode, we only have to pay when we read or write data to a table. Also, we do not have to worry about autoscaling as AWS scales resources automatically depending on the number of requests to the table.

const onDemandTable = new dynamodb.Table(this, "OnDemandTable", {
      partitionKey: {
        name: "order_id",
        type: dynamodb.AttributeType.STRING
      },
      sortKey: {
        name: "order_date",
        type: dynamodb.AttributeType.STRING
      },
      billingMode: dynamodb.BillingMode.PAY_PER_REQUEST,
    })

We have created a DynamoDB table in the above code using the on-demand (PAY_PER_REQUEST) model. We have added a sort key and partition key to this table.

Cleaning Up

When we delete the stack, DynamoDB tables in that stack won’t be deleted. CDK does this to protect us from the accidental deletion of the stack. If we are sure that we want to delete Dynamodb Table along with CDK stack, we can pass `removalPolicy` to dynamo DB construct.

import {RemovalPolicy, Stack, StackProps} from 'aws-cdk-lib';

const onDemandTable = new dynamodb.Table(this, "OnDemandTable", {
      partitionKey: {
        name: "order_id",
        type: dynamodb.AttributeType.STRING
      },
      sortKey: {
        name: "order_date",
        type: dynamodb.AttributeType.STRING
      },
      billingMode: dynamodb.BillingMode.PAY_PER_REQUEST,
      removalPolicy: RemovalPolicy.DESTROY,
    })

Now we can delete our stack and clean up all resources created by a stack.

DynamoDB construct parameters

The below table lists the most common parameters accepted by the DynamoDB table. This table includes some parameters we have not discussed in this blog. Let me know if you want me to create content about specific parameters in the DynamoDB construct.

NameTypeDescriptionDefault Value
partitionKeyObject { name: string; type: dynamodb.AttributeType}Creates primary key for DynamoDB with given name and type
sortKeyObject { name: string; type: dynamodb.AttributeType}Creates sort key for DynamoDB with given name and type
billingModedynamodb.BillingMode enumSets billing mode of PROVISIONED or PAY_PER_REQUEST for DynamoDB tablePROVISIONED
tableClassdynamodb.TableClass enumSets table class of STANDARD or STANDARD_INFREQUENT_ACCESS for DyanmoDB table.STANDARD
replicationRegionsList of available AWS regionsWhen we pass multiple regions to this property, it creates Global DynamoDB table
encryptiondynamodb.TableEncryption enumDynamoDb tables are fully encrypted at rest. Using this parameter, we can decide which type of Customer Master Key(CMK) will be used for encryption. Possible values are AWS owned CMK, AWS managed CMK, Customer managed CMKAWS_OWNED

Conclusion

We have learned how to create a DyamoDB table using AWS CDK. We have also set up auto-scaling for that table. I hope you have found this useful. See you in the next blog.

Similar Posts