How to enable Time To Live (TTL) in DynamoDB

Introduction

The time-to-live (TTL) feature of a dynamoDB table is very useful in certain scenarios. It essentially expires and later deletes items from the table based on the value of a particular attribute in that item. This helps you keep the storage costs in check. And implementation of the TTL feature comes at no extra cost.

The expiration of an item based on this feature is dependent on the following conditions:

  1. The item contains the attribute specified
  2. The type of the attribute is Number
  3. The value of the attribute is a timestamp in the Unix epoch time format, in seconds
  4. The value is not beyond five years in the past

Enabling TTL

Assuming you have a table already, with an attribute that meets the criteria specified above, open the table in the dynamoDB console. Navigate to ‘Additional settings’.

DynamoDB Additional Settings

Scroll down to TTL, and click ‘Enable’. Enter the name of the attribute that you’d like to set as the TTL attribute.

At the bottom, in the Preview, if you set a particular epoch time value and click on ‘Run preview’, it will show some (not all) of the items that will be deleted at that particular time. If you are satisfied with the results, you can click on ‘Enable TTL’. The changes can take an hour to propagate through all the partitions of your table.

Please note that the items are not deleted immediately on the passage of the expiry time. There is some lag (of the order of a couple of minutes as per my experience). Therefore, if you are using the TTL feature for some real-time application (like OTP validation), your client application should also check if the expiry attribute has exceeded the current time, even if the query returned results.

Setting the expiration time

At the time of item creation, your application can fetch the current time in epoch format, add the desired number of seconds to it, and add it to the relevant attribute. For example, in Nodejs, this is how you’d implement it:

let alive_seconds = 3600; //Keep the item alive for 1 hour
let exp_time = Math.trunc(new Date().getTime()/1000 + alive_seconds);

The .getTime() function returns the epoch time in milliseconds. Therefore, it is divided by 1000, and the alive seconds are added.

Similarly, in Python, you’d achieve this as follows:

import time
alive_seconds = 3600
exp_time = int(time.time() + alive_seconds)

For more tutorials on AWS, check out https://iotespresso.com/category/aws/. Also, if you are planning to become a certified AWS Solutions Architect, I’d recommend that you check out this course on Udemy. I took this course and found the lectures to be lucid, to-the-point, and fun. I hope they will help you as well.

Leave a comment

Your email address will not be published.