DynamoDB TTL (Time to Live) - How to Use It Effectively
Written by Rafal Wilinski
Published on 2021-04-16
What is DynamoDB TTL?
DynamoDB allows you to specify a time-to-live timestamp attribute in an epoch timestamp format to define when the item is no longer needed. This attribute will tell DynamoDB to remove items whose TTL attribute is later than current time.
Time-to-live mechanism is super useful for removing temporary items such as session data - we don't want to store invalidated sessions in the store because they not only doesn't matter to us, they are also consuming storage which incurs costs (DynamoDB is also priced by the amount of data we're storing).
What's also cool about TTL is it is completely free. Moreover, the action of removing items is also free - we're not paying for consumed WCUs that we would be paying for if we were to delete these items on our own. These two features make TTL a great money saver.
Setting up TTL
In CLI, there's a special command called
update-time-to-live. Use it in conjunction with
Using CDK (Cloud Development Kit)
In CDK, you can specify TTL on creation. All you need to do is set
timeToLiveAttribute to the attribute of your choice.
Using AWS Console
In AWS Console, click "Manage TTL" in the Table Details section.
- The TTL attribute must use the Number (
N) data type
- The TTL attribute much use epoch time format in seconds, not miliseconds. For Example:
- The TTL attribute value must be a timestamp with an expiration of no more than five years in the past
- The TTL mechanism will work on items that have been inserted after the TTL has been enabled on the table
- TTL setting cannot be reconfigured. You need to first disable it and then re-enable on other attribute
- DynamoDB is removing items with expired TTL in up to 48 hours from the original expiration time. What I mean by that is that you shouldn't rely on it in 100%. In order to make sure that your scans or queries are not returning expired data, make sure to include following
FilterExpressionin your queries:
© 2021 Dynobase