Preventing Accidental Deletion of DynamoDBs using Table Protection Strategy Feature (March 2023)
Tags: dynamodb, cloud, devops, aws
Published: 2023-03-09 05:35:43

DynamoDB is the most popular NoSQL database service provided by AWS. It is considered as the de facto choice for storage of serverless-based projects because of its highly scalable, durable, and available nature. 

DynamoDB traditionally offered various mechanisms that could be used to protect both the table and data contained in them which included:

- Usage of IAM-based [guardrails](https://aws.amazon.com/blogs/database/use-guardrails-to-protect-dynamodb-tables/) to deny delete operations on DynamoDB tables.
- CloudFormation resource [deletion policy](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-deletionpolicy.html) which prevents CloudFormation tools from deleting your Dynamo DB tables when deleting a stack.
- Point-in-time-recovery [(PITR)](https://aws.amazon.com/dynamodb/pitr/) feature which allows continuous backup of data on a second-based granularity for the past 35 days.
- On-demand [backup and restore ](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/BackupRestore.html)which allows us to handle data restoration beyond the 35 days limitation of PITR capability.
- [AWS Backup for DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/backuprestore_HowItWorksAWS.html) which allows organizations to align their backup policies and management strategies with other storage resources.

However, one feature that has been requested by end-users is "Deletion Protection" that is highly comparable with EC2 and RDS deletion protection options. The status quo changed today as [AWS announced](https://aws.amazon.com/blogs/database/how-to-use-deletion-protection-to-enhance-your-amazon-dynamodb-table-protection-strategy/) the feature as a response to customer demand.

If you visit the new DynamoDB console, you can now find a feature that enables you to turn on the deletion protection flag.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qmzzyz0ofknlx29uhna1.png)

The list of tables in DynamoDB console now includes a column that indicates protection status for each DynamoDB table:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ng90q1et9jrzqn58totc.png)

### Using AWS CLI

You can also start applying protection status on new tables using  CLI-based commands as the documentation on how to implement this has been published:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ph844fx8nzcr5n0a3au1.png)

You would have to update your version of AWS CLI to get hold of this feature:

```sh
pip3 install --upgrade awscli

aws --version

# aws-cli/2.7.19 Python/3.9.11 Darwin/22.3.0 exe/x86_64 prompt/off
```

After making sure your CLI version is of at least 2.7.19, you can now run the following shell command to test out the feature:

```sh
aws dynamodb create-table \
    --table-name "cant-delete-db" \
    --attribute-definitions \
        AttributeName=ID,AttributeType=S \
        AttributeName=DeleteOpName,AttributeType=S \
    --key-schema \
        AttributeName=ID,KeyType=HASH \
        AttributeName=DeleteOpName,KeyType=RANGE \
    --provisioned-throughput \
        ReadCapacityUnits=5,WriteCapacityUnits=5 \
    --deletion-protection-enabled \
    --table-class STANDARD \
    --profile="my-poc-profile"
```

### CloudFormation

DynamoDB CloudFormation template now supports delete protection flag. This could be done by specifying the `DeletionProtectionEnabled` property to true.

```yaml
  SampleTable:
    Type: AWS::DynamoDB::Table
    Properties:
      TableName: "my-delete-resilient-db"
      BillingMode: PAY_PER_REQUEST
      DeletionProtectionEnabled: true # Focus here
      SSESpecification:
        SSEEnabled: true
      AttributeDefinitions:
        - AttributeName: id
          AttributeType: S
      KeySchema:
        - AttributeName: id
          KeyType: HASH

```

### Terraform

Terraform update was released 1 week later at [March 17, 2023](https://github.com/hashicorp/terraform-provider-aws/releases/tag/v4.59.0).

```tf
resource "aws_dynamodb_table" "basic-dynamodb-table" {
  name                        = "GameScores"
  billing_mode                = "PROVISIONED"
  deletion_protection_enabled = true
  hash_key                    = "UserId"
  range_key                   = "GameTitle"

  attribute {
    name = "UserId"
    type = "S"
  }

  attribute {
    name = "GameTitle"
    type = "S"
  }
}
```

### CDK

At the time of this writing, there is still no or documentation updates that has been published from CDK provider. 

**Update March 20, 2023** there's been a new [pull request](https://github.com/aws/aws-cdk/pull/24581) in Github for DynamoDB delete protection and will be published soon in CDK and CDK DynamoDB documentation.

**Update March 22, 2023** [pull request](https://github.com/aws/aws-cdk/pull/24581) was merged, still no documentation updates.

 Below is a preview of how could you do it in CDK upon release.

```ts
const table = new dynamodb.Table(this, 'Table', {
  partitionKey: { name: 'id', type: dynamodb.AttributeType.STRING },
  deletionProtection: true,
});
```

### Key Benefits

- **Multiple developers working on the same table:** In a team environment, multiple developers may be working on the same DynamoDB table. Without proper access controls and protection strategies, there is a risk of accidental deletions or modifications that could impact the entire team's work. By using Table Protection Strategy, you can prevent accidental deletions and maintain the integrity of the table, even with multiple developers working on it.

- **Testing and development environments:** In testing and development environments, there may be a need to create and delete tables frequently. However, this also increases the risk of accidentally deleting important data or tables. By using Table Protection Strategy, you can prevent accidental deletions and ensure that your data remains intact during the testing and development process.

- **Compliance requirements:** Depending on your industry and regulatory requirements, you may need to have additional protections in place to prevent accidental deletions or modifications of data. By using Table Protection Strategy, you can demonstrate that you have taken appropriate measures to protect your data and comply with regulatory requirements.

- **Production environments:** In a production environment, accidental deletions can have serious consequences, including data loss and downtime. By using Table Protection Strategy, you can prevent accidental deletions and ensure that your tables remain available and operational.

## Summary 

Overall, using Table Protection Strategy in DynamoDB can help you reduce the risk of data loss, maintain data integrity, and ensure compliance with regulatory requirements.