How TTL Deletion Works in DynamoDB: Explanation and Example
In DynamoDB,
TTL (Time to Live) automatically deletes items after a specified timestamp attribute expires. You enable TTL on a table by specifying an attribute that stores the expiry time in Unix epoch seconds, and DynamoDB deletes expired items asynchronously without affecting table performance.Syntax
To enable TTL in DynamoDB, you specify the name of the attribute that holds the expiration timestamp in Unix epoch time (seconds since 1970-01-01T00:00:00Z). This attribute must be a Number type.
DynamoDB then monitors this attribute and deletes items when the timestamp is in the past.
bash
aws dynamodb update-time-to-live \
--table-name YourTableName \
--time-to-live-specification Enabled=true,AttributeName=ttl_attributeExample
This example shows how to enable TTL on a DynamoDB table named Orders using the attribute expiryTime. Items with expiryTime set to a past Unix timestamp will be deleted automatically.
bash
aws dynamodb update-time-to-live \ --table-name Orders \ --time-to-live-specification Enabled=true,AttributeName=expiryTime # Example item with TTL attribute { "OrderId": {"S": "12345"}, "Product": {"S": "Book"}, "expiryTime": {"N": "1700000000"} # Unix epoch time in seconds }
Output
TimeToLiveSpecification:
Enabled: true
AttributeName: expiryTime
Common Pitfalls
- Wrong attribute type: TTL attribute must be a Number type representing Unix epoch time in seconds, not a string or date format.
- TTL is eventually consistent: Deletion is asynchronous and can take up to 48 hours, so expired items may still appear briefly.
- TTL attribute missing or zero: Items without the TTL attribute or with a value of 0 are never deleted.
- TTL disabled: If TTL is not enabled on the table, no automatic deletion occurs.
json
Wrong example:
{
"OrderId": {"S": "12345"},
"expiryTime": {"S": "2024-01-01T00:00:00Z"} # Wrong type: string instead of number
}
Correct example:
{
"OrderId": {"S": "12345"},
"expiryTime": {"N": "1700000000"} # Correct: Unix epoch time as number
}Quick Reference
| Concept | Description |
|---|---|
| TTL Attribute | A Number attribute storing expiry time in Unix epoch seconds |
| Enable TTL | Use AWS CLI or Console to enable TTL on the attribute |
| Deletion Timing | Asynchronous, can take up to 48 hours after expiry |
| Items without TTL | Not deleted automatically |
| TTL Disabled | No automatic deletion occurs |
Key Takeaways
Enable TTL by specifying a Number attribute with Unix epoch time in seconds.
DynamoDB deletes expired items asynchronously, which may take up to 48 hours.
TTL attribute must be a Number type, not a string or date format.
Items without the TTL attribute or with zero value are not deleted.
TTL helps automatically clean up expired data without impacting table performance.