dynamo-db
  1. dynamo-db-configuring-ttl-for-automatic-data-expiration

Configuring TTL for Automatic Data Expiration in DynamoDB

DynamoDB Time to Live (TTL) allows you to specify when items in a table should expire and automatically be deleted from the table. You can use TTL to lower storage cost and reduce the amount of time and resources it takes to remove expired data. This tutorial will teach you how to configure TTL for automatic data expiration in DynamoDB.

Syntax

To enable TTL on a DynamoDB table, set an attribute as the time to live attribute and set the time to live in seconds for the items in the attribute.

{
  "TimeToLiveSpecification": {
    "Enabled": true,
    "AttributeName": "ExpirationTime"
  }
}

Example

To enable TTL on a table named "Customers" and specify the time to live attribute as "ttl" with a time to live of 60 seconds, you can use the following AWS CLI command:

aws dynamodb update-time-to-live \
    --table-name Customers \
    --time-to-live-specification "Enabled=true, AttributeName=ttl"

Output

If TTL is successfully enabled on the table, you will receive a response that looks like this:

{
    "TimeToLiveSpecification": {
        "AttributeName": "ttl",
        "Enabled": true
    }
}

Explanation

TTL is enabled on a DynamoDB table by specifying an attribute as the time to live attribute and setting the time to live in seconds for the items in the attribute. When TTL is enabled on a table, each item in the time to live attribute is checked against the current time. If the item has expired, it is automatically deleted from the table.

In the above example, the update-time-to-live command is used to enable TTL on the Customers table with the time to live attribute set as ttl and a time to live of 60 seconds. This means that any items in the ttl attribute that are older than 60 seconds will be automatically deleted from the table.

Use

You can use TTL to automatically delete data from your DynamoDB tables, which can lower storage costs and reduce the amount of time and resources it takes to manage your tables. TTL is useful for data that has a limited lifespan, such as session data, temporary data, or event logs.

Important Points

  • TTL can only be set on attributes that are of type Number or String.
  • TTL is stored at the item level, not the attribute level.
  • Once TTL is enabled on a table, it cannot be disabled.
  • TTL only applies to non-expired items in the time to live attribute. If an item is deleted or updated before it expires, its TTL is effectively reset.

Summary

In this tutorial, we learned how to enable TTL on a DynamoDB table to automatically delete expired data. We discussed the syntax for enabling TTL, provided an example using the AWS CLI, explained the output, and discussed the use cases and important points of configuring TTL for automatic data expiration.

Published on: