Functionless-based mini-framework for DynamoDB migrations in AWS CDK.

Overview

dynamodb-migrations

This repo is heavily in progress! Readme describes desired contract and functionality. Please do not try using it yet!. I'm not even sure if it's a good idea.

Functionless-based mini-framework for DynamoDB migrations in AWS CDK. dynamodb-migrations leverages Step Functions to enable massively parallel reads and writes to DynamoDB making your migrations faster.

dynamodb-migrations uses "Migrations as Infrastructure" approach - each migration ends up being a separate State Machine, each one of them is deployed as a separate Nested Stack.

Migrations are ran as a part of CloudFormation deployment cycle - each migration, provisioned as a state machine, gets invoked via CloudFormation Custom Resource which is also part of the stack itself.

sequenceDiagram
  participant User
  participant CloudFormation
  User-->>+CloudFormation: Start deployment with a migration via `cdk deploy`
  Note right of CloudFormation: Update/Create Stack
  CloudFormation->>Cloud: Provision Application Resources
  CloudFormation->>+Step Functions: Provision Migration State Machine as a Nested Stack
  Step Functions->>-CloudFormation: Provisioned
  CloudFormation->>+Custom Resource: Perform Migrations by starting executions
  Custom Resource->>+Migrations History Table: Check which migrations have been already ran
  Migrations History Table->>-Custom Resource: Here are migrations ran in the past
  Note Right of Custom Resource: There's one new migration that hasn't been ran yet
  Custom Resource-->>Step Functions: Run State Machine
  Note left of Step Functions: State machine is an actual definition of migration
  par Perform migration
    Step Functions->>+DynamoDB Table: Update / Delete Items
  end
  par Periodically check if migration is done
    Custom Resource->>+Step Functions: Is done?
  and State Machine Finished Execution
    Custom Resource->>Migrations History Table: Store info about completed migration
    Custom Resource->>-CloudFormation: End
  end

Questions to answer / notes

  • Why Step Function is better than just CloudFormation Custom Resource running some business logic?
    • Step Function can run up to a year. Singular lambda function - 15 minutes.
  • What about throtting? Maybe it's easier thanks to Step Functions? Or maybe it's not? Think about token bucket.
  • Is it possible to track migration progress? Probably some reporting can be added.
  • Excessive resource provisioning might be a problem.
  • Each state machine transition is a cost so one migration can be expensive.
  • Maybe migrations table is not needed since each state machine is persistent?
    • It's definitely more convenient to have a table. State machines can be disposed after running.

Installation / Getting Started

  1. Install dynamodb-migrations:
npm i @dynobase/dynamodb-migrations --save
  1. Include Migrations construct in the stack where your DynamoDB Table is located.
import { MigrationsManager } from '@dynobase/dynamodb-migrations';

...

new MigrationsManager(this, 'MigrationsManager', {
  migrationsDir: './migrations',
});

This will create an additional DynamoDB table that will be used to store the migrations history.

  1. Write an actual migration.

Create file called 20220101-add-attribute.ts in the migrationsDir and paste following contents. This migration will add a new attribute called migrated to every item in the table.

import { $AWS } from "functionless";
import { unmarshall, marshall } from "typesafe-dynamodb/lib/marshall";
import { Migration, MigrationFunction } from "../..";

const tableArn =
  "arn:aws:dynamodb:us-east-1:085108115628:table/TestStack-TableCD117FA1-ZVV3ZWUOWPO";

export const migration: MigrationFunction = (scope, migrationName) => {
  const migrationDefinition = new Migration<any>(scope, migrationName, {
    tableArn,
    migrationName,
  });

  const table = migrationDefinition.table;

  // Actual migration code goes here.
  // For each item in the table
  migrationDefinition.scan(async ({ result }) => {
    for (const i of result.Items as any[]) {
      // Do the following
      await $AWS.DynamoDB.PutItem({
        Table: table,
        // Add migratedAt attribute to the item
        Item: marshall({ ...unmarshall(i), migratedAt: Date.now() }),
      });
    }
  });

  return migrationDefinition;
};

And that's it! This migration will be executed as a part of the next cdk deploy command fully under CloudFormation's control. After successfully running it, the migration will be marked as migrated in the migrations history table.

Todo

  • Do not re-run previously applied migrations
  • Query and Scan functionality
  • Storing executionArn in the migrations history table
  • Add an option for disposing state machines after running migrations
  • Distinguish up/down migrations - if rollback is being performed, then Custom Resource should call down migration which will reverse the effect of the up migration
  • Dry runs
  • CLI for creating new migration files
  • Better contract for writing migrations/semantics
  • Reporting progress
  • Package and publish to NPM
  • More examples

Limitations

  • Migrations cannot be running for longer than two hours, that's a custom resource provisioning limitation
You might also like...

Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

May 18, 2022

Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

May 3, 2022

Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

Jan 3, 2023

Public project to perform migrations on mysql database.

node-mysql-migrate Public project to perform migrations on mysql database. How to run First step, install the dependency for your project. To make it,

Aug 16, 2022

This project provides a CDK construct creating AWS organizations.

AWS Organizations This project provides a CDK construct creating AWS organizations. Currently, there is no @aws-cdk/aws-organizations available. See t

Dec 29, 2022

Sample AWS microservices app with service discovery defined using the CDK. Uses Docker + Fargate & ELB.

Sample AWS microservices app with service discovery defined using the CDK. Uses Docker + Fargate & ELB.

AWS Microservices Demo with CDK and Fargate About Simple AWS microservice-based app. Consists of two Spring Boot based services: Name Service GET /nam

Nov 23, 2022

Easy-to-use CDK constructs for monitoring your AWS infrastructure

CDK Monitoring Constructs Easy-to-use CDK constructs for monitoring your AWS infrastructure. Easily add commonly-used alarms using predefined properti

Jan 6, 2023

AWS CDK compiled for web (and Node!)

cdk-web 🚀 DEMO 💪 AWS CDK compiled for web (and Node!) cdk-web and aws-cdk-web are functionally identical packages on npm. read about the differences

Dec 5, 2022

A sample CICD Deployment Pipeline for your Alexa Skills, using AWS CDK, CodeBuild and CodePipeline

A sample CICD Deployment Pipeline for your Alexa Skills, using AWS CDK, CodeBuild and CodePipeline

Alexa Skils - CI/CD CDK Pipeline This repository will help you setting up a CI/CD pipeline for your Alexa Skills. This pipeline is powered by AWS Clou

Nov 23, 2022
Releases(v0.0.0)
Owner
Rafal Wilinski
Founder of @dynobase, Serverless Consultant
Rafal Wilinski
Example Serverless DynamoDB integration tests using Jest, TypeScript and the AWS CDK

serverless dynamodb integration tests ?? Example Serverless DynamoDB integration tests using Jest, TypeScript and the AWS CDK Introduction How to inte

Lee Gilmore 8 Nov 4, 2022
Learn Web 2.0 and Web 3.0 Development using Next.js, Typescript, AWS CDK, AWS Serverless, Ethereum and AWS Aurora Serverless

Learn Web 2.0 Cloud and Web 3.0 Development in Baby Steps In this course repo we will learn Web 2.0 cloud development using the latest state of the ar

Panacloud Multi-Cloud Internet-Scale Modern Global Apps 89 Jan 3, 2023
A serverless AWS expense tracker API. AWS Lambda functions, API gateway, and Dynamodb are among the ingredients.

AWS-Serverless-API A serverless AWS expense tracker API. AWS Lambda functions API gateway Dynamodb Endpoints Create a new expense: Method: POST Body f

Ondiek Elijah Ochieng 1 Jul 16, 2022
Under the Sea is an official AWS workshop delivered by AWS SAs and AWS Partners to help customers and partners to learn about AIOps with serverless architectures on AWS.

Under the Sea - AIOps with Serverless Workshop Under the Sea is an exciting MMORPG developed by the famous entrepreneur behind Wild Rydes, the most po

AWS Samples 4 Nov 16, 2022
An Amazon Kendra REST API CDK example with an API Gateway, including authentication with AWS Cognito and AWS X-Ray Tracing

Amazon Kendra Web Service CDK Sample Amazon Kendra has a robust JSON API for use with the AWS SDK (software development kit), but does not expose endp

AWS Samples 8 Nov 28, 2022
The Remix Stack for deploying to AWS with DynamoDB, authentication, testing, linting, formatting, etc.

The Remix Stack for deploying to AWS with DynamoDB, authentication, testing, linting, formatting, etc.

Remix 311 Jan 1, 2023
TypeScript plugin for service-to-service (aka. "functionless") cloud integrations.

Functionless λ< Functionless is a TypeScript plugin that transforms TypeScript code into Service-to-Service (aka. "functionless") integrations, such a

sam 303 Jan 2, 2023
MerLoc is a live AWS Lambda function development and debugging tool. MerLoc allows you to run AWS Lambda functions on your local while they are still part of a flow in the AWS cloud remote.

MerLoc MerLoc is a live AWS Lambda function development and debugging tool. MerLoc allows you to run AWS Lambda functions on your local while they are

Thundra 165 Dec 21, 2022
AWS Lambda & Serverless - Developer Guide with Hands-on Labs. Develop thousands line of aws lambda functions interact to aws serverless services with real-world hands-on labs

AWS Lambda & Serverless - Developer Guide with Hands-on Labs UDEMY COURSE WITH DISCOUNTED - Step by Step Development of this Repository -> https://www

awsrun 35 Dec 17, 2022