Create Flawless Workflows with AWS Step Functions and the AWS CDK!
Tags: awsstepfunctions, serverless, aws, cloudcomputing
Published: 2023-01-28 15:17:26

---
title: Create Flawless Workflows with AWS Step Functions and the AWS CDK!
published: true
date: 2023-01-19 22:26:32 UTC
tags: AWSStepFunctions,Serverless,AWS,CloudComputing
canonical_url: https://techdevblog.io/create-flawless-workflows-with-aws-step-functions-and-the-aws-cdk/
---

AWS Step Functions is a powerful and easy-to-use serverless workflow service. It makes it easy to coordinate the components of distributed applications and microservices using visual workflows. With Step Functions, you can design and run workflows that stitch together services such as AWS Lambda and Amazon ECS into feature-rich applications.

With AWS CDK and TypeScript, you can quickly and easily create AWS Step Functions using a few lines of code, and in a matter of minutes. In this tutorial, we'll cover the basics of AWS Step Functions, how to create them using AWS CDK and TypeScript, and a few best practices.

## Preqrequisites

Before you can create and use AWS Step Functions with the AWS CDK and TypeScript, you'll need to install a few prerequisites.

- [Node.js](https://nodejs.org/en/)

- [AWS CDK](https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html)

- [TypeScript](https://www.typescriptlang.org/)

Install the AWS CDK and TypeScript dependencies.

```
npm install --save-dev aws-cdk
npm install --save-dev typescript

```

## Creating an AWS Step Function

Now that you have the prerequisites installed, you can start creating an AWS Step Function with the AWS CDK and TypeScript. Creating AWS Step Functions with AWS CDK and TypeScript is a simple process.

### Creating a boilerplate Step Function

First, create a new directory and `cd` into it. Then, initialise a new TypeScript project.

```
mkdir my-project
cd my-project
npm init -y

```

Create a `src` directory and add a `cdk.ts` and a `hello.ts` file.

```
mkdir src
touch src/cdk.ts

```

You can use the following code to create a simple AWS Step Function. Add it in the `src/cdk.ts`.

```
import * as cdk from '@aws-cdk/core';
import * as stepfunctions from '@aws-cdk/aws-stepfunctions';

export class MyStepFunctionsStack extends cdk.Stack {
  constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    // Create a new Step Functions State Machine
    const myStateMachine = new stepfunctions.StateMachine(this, 'MyStateMachine', {
      definition: stepfunctions.Chain.start(new stepfunctions.Pass(this, 'FirstState')),
      timeout: cdk.Duration.minutes(5)
    });
  }
}

```

This code creates a new Step Functions State Machine with a single state, a `Pass` state. The `Pass` state is a simple state that does nothing but pass data from one state to the next. You can add additional states to the state machine by chaining them together with the `Chain.start` method.

### Integrating with AWS Lambda

Add a `hello.ts` file to your `src` directory

```
touch src/hello.ts

```

In `src/hello.ts`, add the following code.

```
const response = {
  statusCode: 200,
  body: JSON.stringify('Hello World!'),
};

exports.handler = async () => response;

```

Update your `src/cdk.ts` with the following code.

```
import * as cdk from '@aws-cdk/core';
import * as lambda from '@aws-cdk/aws-lambda';
import * as stepfunctions from '@aws-cdk/aws-stepfunctions';

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

    const helloWorldTask = new stepfunctions.Task(this, 'Hello World Task', {
      task: new stepfunctions.InvokeFunction(this, 'Hello World Lambda', {
        function: new lambda.Function(this, 'Hello World Lambda', {
          code: new lambda.AssetCode('src'),
          handler: 'hello.handler',
          runtime: lambda.Runtime.NODEJS_10_X
        })
      })
    });

    const helloWorldState = new stepfunctions.Pass(this, 'Hello World State', {
      result: 'Hello World'
    });

    const helloWorldStateMachine = new stepfunctions.StateMachine(this, 'Hello World State Machine', {
      definition: helloWorldTask.next(helloWorldState)
    });
  }
}

const app = new cdk.App();
new MyStepFunctionStack(app, 'MyStepFunctionStack');
app.synth();

```

This code creates a new AWS Step Function with a single task that invokes a Lambda function called `Hello World Lambda`. When the Lambda function is invoked, it will return the string `Hello World`.

## Best Practices

When creating AWS Step Functions with AWS CDK and TypeScript, there are a few best practices to keep in mind:

- Make sure to use meaningful names for your AWS Step Function tasks and states.
- Keep the number of tasks and states in your AWS Step Function to a minimum.
- Use the `Chain.start` method to chain together multiple states in your state machine.
- Use the `Parallel` state to execute multiple states in parallel.
- Use the `Wait` state to pause the execution of a state machine for a specified amount of time.
- Use the `Catch` state to handle errors in your state machine.
- Use the `Choice` state to dynamically route the execution of a state machine based on the data.
- Be aware of the [AWS Step Function limits](https://docs.aws.amazon.com/step-functions/latest/dg/limits.html).

## Conclusion

To sum up, creating and using AWS Step Functions with the AWS CDK and TypeScript is an excellent way to coordinate the components of distributed applications and microservices. With it, you can quickly and easily create distributed applications and workflows in a matter of minutes. Just remember to follow best practices and be aware of the limits. If you're looking for more great content like this, remember to subscribe to the [Tech Dev Blog's newsletter](https://techdevblog.io/#/portal/signup)!

<!--kg-card-end: markdown-->