Dynamodb Table Example in AWS CDK - Complete Guide

avatar

Borislav Hadzhiev

Wed Apr 28 20214 min read

Table of Contents #

  1. Creating a Dynamodb Table in AWS CDK
  2. Granting Dynamodb table Permissions in AWS CDK
  3. Configuring Auto Scaling for a Dynamodb Table in AWS CDK

Creating a Dynamodb Table in AWS CDK #

In order to create a dynamodb table in AWS CDK, we have to instantiate the Table class.

The code for this article is available on GitHub

Let's look at a simple example, where we create a dynamodb table and add a local secondary index to it:

lib/cdk-starter-stack.ts
import * as dynamodb from '@aws-cdk/aws-dynamodb'; import * as iam from '@aws-cdk/aws-iam'; import * as cdk from '@aws-cdk/core'; export class CdkStarterStack extends cdk.Stack { constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { super(scope, id, props); // ๐Ÿ‘‡ create Dynamodb table const table = new dynamodb.Table(this, id, { billingMode: dynamodb.BillingMode.PROVISIONED, readCapacity: 1, writeCapacity: 1, removalPolicy: cdk.RemovalPolicy.DESTROY, partitionKey: {name: 'id', type: dynamodb.AttributeType.STRING}, sortKey: {name: 'createdAt', type: dynamodb.AttributeType.NUMBER}, pointInTimeRecovery: true, }); console.log('table name ๐Ÿ‘‰', table.tableName); console.log('table arn ๐Ÿ‘‰', table.tableArn); // ๐Ÿ‘‡ add local secondary index table.addLocalSecondaryIndex({ indexName: 'statusIndex', sortKey: {name: 'status', type: dynamodb.AttributeType.STRING}, projectionType: dynamodb.ProjectionType.ALL, }); } }

Let's go over what we did in the code snippet.

  1. we created a dynamodb table. The configuration props we've passed to the Table class are:
  • billingMode - in our case we've selected PROVISIONED, the alternative is PAY_PER_REQUEST, where the table will automatically scale with the traffic.

  • readCapacity and writeCapacity - te provisioned throughput for the table

  • removalPolicy - specify what should happen to the table if we delete the cdk stack, or the table resource itself.

    The default removalPolicy for stateful resources (databases, S3 buckets, Cognito User Pools, etc) is RETAIN, which means that the resource will remain in an orphaned state in the account, even after the CDK stack is deleted.

  • partitionKey and sortKey - the primary key for our dynamodb table

  • pointInTimeRecovery - when set to true - enables continuous backups for our dynamodb table

  1. we added a local secondary index to the dynamodb table. Note that we can only add local secondary indexes to a dynamodb table at table creation time

Let's execute a deployment:

shell
npx cdk deploy

If we take a look at the dynamodb management console, we can see that the table has been created:

dynamodb table created

Granting Dynamodb table Permissions in AWS CDK #

In order to grant permissions on a dynamodb table in CDK, we have to use the grant* methods on an instance of the Table class, for example:

  • grantWriteData - permits an IAM principal to execute all write operations on a dynamodb table
  • grantReadData - permits an IAM principal to execute all read operations on a dynamodb table
  • grant - allows for a more fine-grained approach, where we pick which actions a principal can execute on a dynamodb table
The code for this article is available on GitHub

Let's look at an example of using grantReadData:

lib/cdk-starter-stack.ts
import * as cdk from '@aws-cdk/core'; import * as dynamodb from '@aws-cdk/aws-dynamodb'; import * as iam from '@aws-cdk/aws-iam'; export class CdkStarterStack extends cdk.Stack { constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { super(scope, id, props); // ... rest // ๐Ÿ‘‡ grant permissions on table table.grantReadData(new iam.AccountRootPrincipal()); } }

In the code snippet we've allowed the AWS account, into which the stack was deployed, to execute read operations on the dynamodb table.

A very common scenario is to use the grant* methods to grant permissions to a lambda function. For example, this line grants permission to a lambda to execute all read operations on the table:

table.grantReadData(lambda);

A more fine-grained approach would be to use the grant method and specify the action:

table.grant(lambda, ['dynamodb:Query']);

By using the grant method we can follow the IAM best practice of granting only the permissions, that are required to perform a task.

Configuring Auto Scaling for a Dynamodb Table in AWS CDK #

In order to configure auto scaling for a Dynamodb table in CDK, we have to use the autoScaleReadCapacity and autoScaleWriteCapacity methods on an instance of the Table class.

The code for this article is available on GitHub

Let's look at an example where we configure auto scaling for the write capacity of our table.

lib/cdk-starter-stack.ts
import * as dynamodb from '@aws-cdk/aws-dynamodb'; import * as iam from '@aws-cdk/aws-iam'; import * as cdk from '@aws-cdk/core'; import * as appautoscaling from '@aws-cdk/aws-applicationautoscaling'; export class CdkStarterStack extends cdk.Stack { constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { super(scope, id, props); // ... rest // ๐Ÿ‘‡ configure auto scaling on table const writeAutoScaling = table.autoScaleWriteCapacity({ minCapacity: 1, maxCapacity: 2, }); // ๐Ÿ‘‡ scale up when write capacity hits 75% writeAutoScaling.scaleOnUtilization({ targetUtilizationPercent: 75, }); // ๐Ÿ‘‡ scale up at 9 o'clock in the morning writeAutoScaling.scaleOnSchedule('scale-up', { schedule: appautoscaling.Schedule.cron({hour: '9', minute: '0'}), minCapacity: 2, }); // ๐Ÿ‘‡ scale down in the afternoon writeAutoScaling.scaleOnSchedule('scale-down', { schedule: appautoscaling.Schedule.cron({hour: '14', minute: '0'}), maxCapacity: 2, }); } }

In the code snippet:

  1. we used the autoScaleWriteCapacity method to enable auto scaling for the write capacity of our dynamodb table
  2. we used the scaleOnUtilization method to scale our dynamodb table up, in the event that the table's utilization reaches 75%.
  3. we used the scaleOnSchedule method to scale our table up and down depending on the time of the day.

Let's deploy the changes:

shell
npx cdk deploy

If we take a look at the dynamodb management console, we can see that the write capacity auto scaling configuration of the table has been updated:

dynamodb table auto scaling

Clean up #

To delete the resources we've provisioned, execute the destroy command:

shell
npx cdk destroy

Further Reading #

Add me on LinkedIn

I'm a Web Developer with TypeScript, React.js, Node.js and AWS experience.

Let's connect on LinkedIn

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee