Enable TTL on a Dynamodb Table in an Amplify project
TTL Feature
DynamoDB TTL (Time to Live) is a feature provided by Amazon Web Services (AWS) for its DynamoDB database service. It allows you to define a time period after which items in a DynamoDB table will expire and be automatically deleted. This feature is particularly useful for managing data that has a finite lifespan.
How it works
Attribute for Expiry: You specify a TTL attribute from your DynamoDB table. This attribute must contain a timestamp that represents the expiration time for each item in the table.
Automatic Deletion: DynamoDB automatically deletes an item from the table at its expiration time specified in the TTL attribute . This deletion process is handled by DynamoDB itself, so you don't need to write any code to manage the deletion of expired items.
Efficient Cleanup: DynamoDB continuously scans the table for expired items and removes them in the background. This ensures that your table stays optimized and doesn't become cluttered with expired data.
How to enable TTL on any Dynamodb table from AWS management console
Navigate to the AWS Management Console -> DynamoDB service -> Tables, find your table and open it.
- Go to Additional Settings and find Time to Live setting.
3. Click on Turn on button.
4. In TTL settings: TTL attribute name, enter the name of the attribute which has the expiration time.
5. Click on Turn on TTL button.
How to enable TTL on a Dynamodb table in AWS Amplify project
1. Add TTL attribute to the Graphql schema
ttl: Int
2. Add Expiration Time to the TTL attribute
- We use
datetime.utcnow()
to get the current UTC time. - We then add 30 days to the current time using
timedelta(days=30)
to calculate the TTL timestamp. - Finally, we convert the TTL timestamp to Unix epoch time using
timestamp()
method and then to integer, which gives us the TTL timestamp value that can be used in DynamoDB.
3. Use override feature to enable TTL on the dynamodb table
amplify override api
Run the command above to override Amplify-generated Amazon API Gateway resources.
The command creates a new overrides.ts
file under amplify/backend/api/<resource-name>/
.
Apply all the overrides in the override(...)
function. For example if we want to enable TTL on 2 dynamodb tables, namely, 'MyDynamodbTable' namely and 'MonthlyReport' namely and the attribute name is 'ttl'namely in both the tables, our overrides.ts
file should look like this:
Comments
Post a Comment