

# Deploy multiple-stack applications using AWS CDK with TypeScript
<a name="deploy-multiple-stack-applications-using-aws-cdk-with-typescript"></a>

*Dr. Rahul Sharad Gaikwad, Amazon Web Services*

## Summary
<a name="deploy-multiple-stack-applications-using-aws-cdk-with-typescript-summary"></a>

This pattern provides a step-by-step approach for application deployment on Amazon Web Services (AWS) using AWS Cloud Development Kit (AWS CDK) with TypeScript. As an example, the pattern deploys a serverless real-time analytics application.

The pattern builds and deploys nested stack applications. The parent AWS CloudFormation stack calls the child, or nested, stacks.  Each child stack builds and deploys the AWS resources that are defined in the CloudFormation stack. AWS CDK Toolkit, the command line interface (CLI) command `cdk`, is the primary interface for the CloudFormation stacks.

## Prerequisites and limitations
<a name="deploy-multiple-stack-applications-using-aws-cdk-with-typescript-prereqs"></a>

**Prerequisites**
+ An active AWS account
+ Existing virtual private cloud (VPC) and subnets
+ AWS CDK Toolkit installed and configured
+ A user with administrator permissions and a set of access keys.
+ Node.js
+ AWS Command Line Interface (AWS CLI)

**Limitations **
+ Because AWS CDK uses AWS CloudFormation, AWS CDK applications are subject to CloudFormation service quotas. For more information, see [AWS CloudFormation quotas](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cloudformation-limits.html).

**Product versions**

This pattern has been built and tested using the following tools and versions.
+ AWS CDK Toolkit 1.83.0
+ Node.js 14.13.0
+ npm 7.0.14

The pattern should work with any version of AWS CDK or npm. Note that Node.js versions 13.0.0 through 13.6.0 are not compatible with the AWS CDK.

## Architecture
<a name="deploy-multiple-stack-applications-using-aws-cdk-with-typescript-architecture"></a>

**Target technology stack  **
+ AWS Amplify Console
+ Amazon API Gateway
+ AWS CDK
+ Amazon CloudFront
+ Amazon Cognito
+ Amazon DynamoDB
+ Amazon Data Firehose
+ Amazon Kinesis Data Streams
+ AWS Lambda
+ Amazon Simple Storage Service (Amazon S3)

**Target architecture**

The following diagram shows multiple-stack application deployment using AWS CDK with TypeScript.

![\[Stack architecture in the VPC, with a parent stack and two child stacks that contain resources.\]](http://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/images/pattern-img/0ac29a11-1362-4084-92ed-6b85205763ca/images/8f92e86a-aa3d-4f8a-9b11-b92c52a7226c.png)


 

The following diagram shows the architecture of the example serverless real-time application.

![\[Application architecture in the Region.\]](http://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/images/pattern-img/0ac29a11-1362-4084-92ed-6b85205763ca/images/2df00faf-f871-4aec-9655-19ba2eb14cf8.png)


 

## Tools
<a name="deploy-multiple-stack-applications-using-aws-cdk-with-typescript-tools"></a>

**Tools**
+ [AWS Amplify Console](https://docs.aws.amazon.com/amplify/latest/userguide/welcome.html) is the control center for fullstack web and mobile application deployments in AWS. Amplify Console hosting provides a git-based workflow for hosting fullstack serverless web apps with continuous deployment. The Admin UI is a visual interface for frontend web and mobile developers to create and manage app backends outside the AWS console.
+ [Amazon API Gateway](https://docs.aws.amazon.com/apigateway/latest/developerguide/welcome.html) is an AWS service for creating, publishing, maintaining, monitoring, and securing REST, HTTP, and WebSocket APIs at any scale.
+ [AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/latest/guide/home.html) is a software development framework that helps you define and provision AWS Cloud infrastructure in code.
+ [AWS CDK Toolkit](https://docs.aws.amazon.com/cdk/latest/guide/cli.html) is a command line cloud development kit that helps you interact with your AWS CDK app. The `cdk` CLI command is the primary tool for interacting with your AWS CDK app. It runs your app, interrogates the application model you defined, and produces and deploys the AWS CloudFormation templates generated by the AWS CDK.
+ [Amazon CloudFront](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Introduction.html) is a web service that speeds up distribution of static and dynamic web content, such as .html, .css, .js, and image files. CloudFront delivers your content through a worldwide network of data centers called edge locations for lower latency and improved performance.
+ [Amazon Cognito](https://docs.aws.amazon.com/cognito/latest/developerguide/what-is-amazon-cognito.html) provides authentication, authorization, and user management for your web and mobile apps. Your users can sign in directly or through a third party.
+ [Amazon DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html) is a fully managed NoSQL database service that provides fast and predictable performance with seamless scalability.
+ [Amazon Data Firehose](https://docs.aws.amazon.com/firehose/latest/dev/what-is-this-service.html) is a fully managed service for delivering real-time [streaming data](https://aws.amazon.com/streaming-data/) to destinations such as Amazon S3, Amazon Redshift, Amazon OpenSearch Service, Splunk, and any custom HTTP endpoint or HTTP endpoints owned by supported third-party service providers.
+ [Amazon Kinesis Data Streams](https://docs.aws.amazon.com/streams/latest/dev/introduction.html) is a service for collecting and processing large streams of data records in real time.
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) is a compute service that supports running code without provisioning or managing servers. Lambda runs your code only when needed and scales automatically, from a few requests per day to thousands per second. You pay only for the compute time that you consume—there is no charge when your code is not running.
+ [Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) is a cloud-based object storage service that helps you store, protect, and retrieve any amount of data.

**Code**

The code for this pattern is attached.

## Epics
<a name="deploy-multiple-stack-applications-using-aws-cdk-with-typescript-epics"></a>

### Install AWS CDK Toolkit
<a name="install-aws-cdk-toolkit"></a>


| Task | Description | Skills required | 
| --- | --- | --- | 
| Install AWS CDK Toolkit. | To install AWS CDK Toolkit globally, run the following command.`npm install -g aws-cdk` | DevOps | 
| Verify the version. | To verify the AWS CDK Toolkit version, run the following command. `cdk --version` | DevOps | 

### Set up AWS credentials
<a name="set-up-aws-credentials"></a>


| Task | Description | Skills required | 
| --- | --- | --- | 
| Set up credentials. | To set up credentials, run the `aws configure` command and follow the prompts.<pre>$aws configure<br />AWS Access Key ID [None]: <br />AWS Secret Access Key [None]: your_secret_access_key<br />Default region name [None]:<br />Default output format [None]:</pre> | DevOps | 

### Download the project code
<a name="download-the-project-code"></a>


| Task | Description | Skills required | 
| --- | --- | --- | 
| Download the attached project code. | For more information about the directory and file structure, see the *Additional information* section. | DevOps | 

### Bootstrap the AWS CDK environment
<a name="bootstrap-the-aws-cdk-environment"></a>


| Task | Description | Skills required | 
| --- | --- | --- | 
| Bootstrap the environment. | To deploy the AWS CloudFormation template to the account and AWS Region that you want to use, run the following command.`cdk bootstrap <account>/<Region>`For more information, see the [AWS documentation](https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html). | DevOps | 

### Build and deploy the project
<a name="build-and-deploy-the-project"></a>


| Task | Description | Skills required | 
| --- | --- | --- | 
| Build the project. | To build the project code, run the `npm run build` command. | DevOps | 
| Deploy the project. | To deploy the project code, run the `cdk deploy` command. |  | 

### Verify outputs
<a name="verify-outputs"></a>


| Task | Description | Skills required | 
| --- | --- | --- | 
| Verify stack creation. | On the AWS Management Console, choose **CloudFormation**. In the stacks for the project, verify that a parent stack and two child stacks have been created. | DevOps | 

### Test the application
<a name="test-the-application"></a>


| Task | Description | Skills required | 
| --- | --- | --- | 
| Send data to Kinesis Data Streams. | Configure your AWS Account to send data to Kinesis Data Streams using Amazon Kinesis Data Generator (KDG). For more information, see [Amazon Kinesis Data Generator](https://awslabs.github.io/amazon-kinesis-data-generator/web/help.html). | DevOps | 
| Create an Amazon Cognito user. | To create an Amazon Cognito user, download the cognito-setup.json CloudFormation template from the *Create an Amazon Cognito User* section on the [Kinesis Data Generator help page](https://awslabs.github.io/amazon-kinesis-data-generator/web/help.html). Initiate the template, and then enter your Amazon Cognito **Username** and **Password**.The **Outputs** tab lists the Kinesis Data Generator URL. | DevOps | 
| Log in to Kinesis Data Generator | To log in to KDG, use the Amazon Cognito credentials that you provided and the Kinesis Data Generator URL. | DevOps | 
| Test the application. | In KDG, in **Record template**, **Template 1**, paste the test code from the *Additional information* section, and choose **Send data**. | DevOps | 
| Test API Gateway. | After the data has been ingested, test API Gateway by using the `GET` method to retrieve data. | DevOps | 

## Related resources
<a name="deploy-multiple-stack-applications-using-aws-cdk-with-typescript-resources"></a>

**References**
+ [AWS Cloud Development Kit](https://aws.amazon.com/cdk/)
+ [AWS CDK on GitHub](https://github.com/aws/aws-cdk)
+ [Working with nested stacks](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-nested-stacks.html)
+ [AWS sample example - Serverless real-time analytics](https://github.com/aws-samples/serverless-realtime-analytics)

## Additional information
<a name="deploy-multiple-stack-applications-using-aws-cdk-with-typescript-additional"></a>

**Directory and file details**

This pattern sets up the following three stacks.
+ `parent-cdk-stack.ts` – This stack acts as the parent stack and calls the two child applications as nested stacks. 
+ `real-time-analytics-poc-stack.ts` – This nested stack contains the infrastructure and application code.
+ `real-time-analytics-web-stack.ts` – This nested stack contains only the static web application code.

*Important files and their functionality*
+ `bin/real-time-analytics-poc.ts` – Entry point of the AWS CDK application. It loads all stacks defined under `lib/`.
+ `lib/real-time-analytics-poc-stack.ts` – Definition of the AWS CDK application’s stack (`real-time-analytics-poc`).
+ `lib/real-time-analytics-web-stack.ts` – Definition of the AWS CDK application’s stack (`real-time-analytics-web-stack`).
+ `lib/parent-cdk-stack.ts` – Definition of the AWS CDK application’s stack (`parent-cdk`).
+ `package.json` – npm module manifest, which includes the application name, version, and dependencies.
+ `package-lock.json` – Maintained by npm.
+ `cdk.json` – Toolkit for running the application.
+ `tsconfig.json` – The project’s TypeScript configuration.
+ `.gitignore` – List of files that Git should exclude from source control.
+ `node_modules` – Maintained by npm; includes the project’s dependencies.

The following section of code in the parent stack calls child applications as a nested AWS CDK stacks.

```
import * as cdk from '@aws-cdk/core';
import { Construct, Stack, StackProps } from '@aws-cdk/core';
import { RealTimeAnalyticsPocStack } from './real-time-analytics-poc-stack';
import { RealTimeAnalyticsWebStack } from './real-time-analytics-web-stack';


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


    new RealTimeAnalyticsPocStack(this, 'RealTimeAnalyticsPocStack');
    new RealTimeAnalyticsWebStack(this, 'RealTimeAnalyticsWebStack');
  }
}
```

**Code for testing**

```
session={{date.now('YYYYMMDD')}}|sequence={{date.now('x')}}|reception={{date.now('x')}}|instrument={{random.number(9)}}|l={{random.number(20)}}|price_0={{random.number({"min":10000, "max":30000})}}|price_1={{random.number({"min":10000, "max":30000})}}|price_2={{random.number({"min":10000, "max":30000})}}|price_3={{random.number({"min":10000, "max":30000})}}|price_4={{random.number({"min":10000, "max":30000})}}|price_5={{random.number({"min":10000, "max":30000})}}|price_6={{random.number({"min":10000, "max":30000})}}|price_7={{random.number({"min":10000, "max":30000})}}|price_8={{random.number({"min":10000, "max":30000})}}|
```

**Testing API Gateway**

On the API Gateway console, test API Gateway by using the `GET` method. 

![\[API Gateway Console with GET chosen under OPTIONS.\]](http://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/images/pattern-img/0ac29a11-1362-4084-92ed-6b85205763ca/images/452e5b8f-6d61-401d-8484-e5a436cb6f1b.png)


 

## Attachments
<a name="attachments-0ac29a11-1362-4084-92ed-6b85205763ca"></a>

To access additional content that is associated with this document, unzip the following file: [attachment.zip](samples/p-attach/0ac29a11-1362-4084-92ed-6b85205763ca/attachments/attachment.zip)