DynamoDB
TTL
24-hour expiration
data management
AWS

Dynamodb TTL 24hours

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Amazon DynamoDB is a fully managed NoSQL database service that provides fast and predictable performance with seamless scalability. One of its advantageous features is the Time to Live (TTL) attribute, which automatically deletes items from a table once the specified timestamp expires. Although TTL can be defined with various time durations, using a 24-hour TTL is common for many applications. This article will explore the technical aspects of using DynamoDB TTL set to 24 hours, its implementation, and practical use cases.

Technical Explanation of TTL in DynamoDB

Before diving into the specifics of a 24-hour TTL, it's essential to understand the general concept of TTL in DynamoDB. TTL allows you to manage the life cycle of data by enabling automatic deletion of items that are no longer required. This feature helps reduce storage costs and manage stale data efficiently.

How TTL Works

  • TTL Attribute: A TTL attribute is a designated attribute in the DynamoDB table that stores the expiration time for each item. This value is a timestamp in Unix epoch time format (in seconds).
  • Scheduled Deletion: Once the TTL attribute reaches the current time or is in the past, DynamoDB will asynchronously delete the expired item. This deletion normally occurs within 48 hours.

Implementing a 24-Hour TTL

  1. Add a TTL Attribute: When creating a table or modifying an existing item, include a TTL attribute to define its expiration.
  2. Set the TTL Value: Calculate the Unix epoch time for 24 hours from the current moment and store it as the value of the TTL attribute. This represents the exact time when the item should be expired. For instance:
python
1   import time
2
3   # Current time in seconds
4   current_time = int(time.time())
5   
6   # 24 hours later
7   ttl_expiry = current_time + 86400  # 86400 seconds = 24 hours
  1. Enable TTL: Use the AWS Management Console, CLI, or SDK to enable TTL on the desired table. Specify the attribute name you've chosen as the TTL attribute.

Example Code

Here's an example using Python and the Boto3 library to set a 24-hour TTL for a DynamoDB item:

python
1import boto3
2from datetime import datetime, timedelta
3
4dynamodb = boto3.client('dynamodb')
5
6# Your table name
7table_name = 'YourTableName'
8
9# Current time + 24 hours in epoch
10ttl = int((datetime.now() + timedelta(hours=24)).timestamp())
11
12# Example item to insert
13item = {
14    'PartitionKey': {'S': 'exampleKey'},
15    'DataAttribute': {'S': 'exampleData'},
16    'TTL': {'N': str(ttl)}  # TTL attribute
17}
18
19# Put item into table
20dynamodb.put_item(TableName=table_name, Item=item)

Use Cases for 24-Hour DynamoDB TTL

  • Session Management: Applications where user sessions need to be expired automatically after 24 hours can leverage DynamoDB TTL for cleanup without manual intervention.
  • Caching Layer: Use DynamoDB as a caching layer to store temporary data that should be automatically invalidated and removed after 24 hours.
  • Log Data Management: Reduce the storage of logs by ensuring that entries older than 24 hours are deleted, helping maintain performance and cost management.

Using DynamoDB Streams with TTL

When an item expires and is deleted by TTL, if DynamoDB Streams is enabled on the table, the deletion can generate a stream record. This can be useful for triggering an AWS Lambda function for any additional cleanup or processing required when data is removed.

Limitations of DynamoDB TTL

  • Accuracy: AWS does not guarantee immediate deletion at the exact expiration time. TTL can take up to 48 hours post-expiry for deletion.
  • Conditional Layout: If your application logic requires precise deletion timing, relying solely on TTL may not be ideal. Additional logic might be needed.

Summary Table

Below is a summary of the key points regarding DynamoDB TTL:

FeatureDescription
TTL AttributeAn attribute representing expiration in seconds
TTL FormatUnix epoch time (seconds)
TTL RangeTypical range, including 24-hour duration
Expiration ProcessingAsynchronous, can take up to 48 hours
Use CasesSession expiry, caching, log management
LimitationsNon-instant deletion, requires additional logic if precise timing is needed
Additional CapabilityIntegration with DynamoDB Streams for item deletion

In conclusion, using a 24-hour TTL in DynamoDB provides a powerful mechanism for maintaining efficient databases by automating data expiration, thus optimizing storage and enhancing application performance. While there are certain limitations, when used correctly, TTLs become a key player in designing resilient and cost-effective architectures.


Course illustration
Course illustration

All Rights Reserved.