In this section, we will learn how to build a NoSQL database with Amazon DynamoDB using AWS CDK (TypeScript) to store product catalog data for the Spring Boot microservice.
Within our backend application architecture:
Spring Boot Microservice: Provides CRUD (Create, Read, Update, Delete) REST APIs for the product catalog via the /api/products endpoint.
Amazon DynamoDB: Serves as a high-performance serverless NoSQL database. DynamoDB completely eliminates the operational burden of server management, requires no cluster provisioning, and automatically replicates data across 3 Availability Zones within the Region for high availability.
Connection with ECS Fargate: The ECS Fargate cluster requires permissions to access the DynamoDB table. Therefore, separating the DynamoDB table into an independent CDK Stack (DynamoDbStack) allows us to share the table object with EcsStack, thereby granting read/write IAM permissions (grantReadWriteData) to the Task Role explicitly and securely.
dynamodb-stack.ts)Navigate to the directory IaC-ECS-CDK/cdk/lib and open the file dynamodb-stack.ts (or create it if not present). Update the contents defining the DynamoDB stack:
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb';
export class DynamoDbStack extends cdk.Stack {
public readonly table: dynamodb.Table;
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
this.table = new dynamodb.Table(this, 'ProductsTable', {
tableName: 'products',
partitionKey: {
name: 'id',
type: dynamodb.AttributeType.STRING,
},
billingMode: dynamodb.BillingMode.PAY_PER_REQUEST, // On-Demand: Pay per request, zero idle maintenance fees
removalPolicy: cdk.RemovalPolicy.DESTROY, // Clean up table on stack deletion during lab cleanup
});
new cdk.CfnOutput(this, 'TableName', {
value: this.table.tableName,
description: 'DynamoDB Table Name',
exportName: 'ProductsTableName',
});
}
}

public readonly table: dynamodb.Table;:
bin/cdk.ts file.EcsStack to execute the command props.table.grantReadWriteData(fargateService.taskDefinition.taskRole) without hardcoding ARNs or manually configuring IAM policies.tableName: ‘products’:
partitionKey: { name: ‘id’, type: dynamodb.AttributeType.STRING }:
billingMode: dynamodb.BillingMode.PAY_PER_REQUEST:
removalPolicy: cdk.RemovalPolicy.DESTROY:
cdk.CfnOutput:
Architectural Tip: Separating the database into an independent DynamoDbStack from EcsStack adheres to the principle of Separation of Concerns. You can redeploy, update, or scale the Fargate container application without affecting the lifecycle and persisted data stored in DynamoDB.