0
0
AWScloud~5 mins

Time to live (TTL) for expiration in AWS - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you want data to disappear automatically after a certain time. TTL helps by setting an expiration time for items in a database so you don't have to delete them manually.
When you want to automatically remove old user sessions from your database.
When you store temporary tokens that should expire after a few hours.
When you keep logs that only need to be saved for a limited time.
When you want to save storage costs by deleting outdated data automatically.
When you want to ensure data privacy by removing sensitive info after a set period.
Config File - ttl-config.json
ttl-config.json
{
  "TableName": "example-table",
  "TimeToLiveSpecification": {
    "Enabled": true,
    "AttributeName": "expireAt"
  }
}

This JSON file enables TTL on the DynamoDB table named example-table. The TimeToLiveSpecification section turns TTL on and sets the attribute expireAt as the timestamp when the item should expire.

Commands
This command enables TTL on the DynamoDB table using the configuration file. It tells AWS which attribute to use for expiration time.
Terminal
aws dynamodb update-time-to-live --cli-input-json file://ttl-config.json
Expected OutputExpected
{ "TimeToLiveSpecification": { "Enabled": true, "AttributeName": "expireAt" } }
--cli-input-json - Specifies the JSON file with TTL settings
This command checks the current TTL status on the table to confirm it is enabled and shows the attribute used.
Terminal
aws dynamodb describe-time-to-live --table-name example-table
Expected OutputExpected
{ "TimeToLiveDescription": { "TimeToLiveStatus": "ENABLED", "AttributeName": "expireAt" } }
--table-name - Specifies the DynamoDB table to check
Key Concept

If you remember nothing else from this pattern, remember: TTL automatically deletes items after the time you set in a special attribute.

Common Mistakes
Not enabling TTL on the table before adding expiration attributes.
TTL won't work if it is not enabled, so items will never expire automatically.
Always run the update-time-to-live command to enable TTL before relying on expiration.
Using a wrong attribute name or not setting the expiration timestamp in items.
TTL only deletes items based on the attribute you specify; if it's missing or wrong, items stay forever.
Use the exact attribute name enabled in TTL and set a valid Unix timestamp for expiration.
Summary
Create a JSON config file to enable TTL on your DynamoDB table with the attribute name for expiration.
Run the AWS CLI command to apply TTL settings using the config file.
Verify TTL is enabled and check the attribute name with the describe-time-to-live command.