How to Use TTL for Session Management in DynamoDB
Use DynamoDB's
Time To Live (TTL) feature by adding a timestamp attribute that marks when a session should expire. DynamoDB automatically deletes items after the TTL timestamp passes, making it ideal for managing session lifetimes without manual cleanup.Syntax
To enable TTL for session management, add a numeric attribute to your DynamoDB items that stores the expiration time as a Unix epoch timestamp (in seconds). Then, enable TTL on your table specifying this attribute.
TTLAttributeName: The name of the attribute holding the expiration timestamp.ExpirationTime: Unix epoch time in seconds when the item should expire.
bash
aws dynamodb update-time-to-live --table-name YourTableName --time-to-live-specification Enabled=true,AttributeName=ExpirationTimeOutput
An output confirming TTL is enabled on the table with the specified attribute.
Example
This example shows how to insert a session item with an expiration time 30 minutes from now, so DynamoDB will delete it automatically after that.
python
import time import boto3 dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('Sessions') # Current time plus 30 minutes (1800 seconds) expiration_time = int(time.time()) + 1800 # Put session item with TTL attribute response = table.put_item( Item={ 'SessionId': 'session123', 'UserId': 'user456', 'ExpirationTime': expiration_time } ) print('PutItem succeeded:', response)
Output
PutItem succeeded: {'ResponseMetadata': {'RequestId': '...', 'HTTPStatusCode': 200, ...}}
Common Pitfalls
- TTL attribute must be a number representing Unix epoch time in seconds; strings or other formats won't work.
- TTL deletion is not immediate; DynamoDB typically deletes expired items within 48 hours.
- Do not rely on TTL for critical immediate deletion; use it for eventual cleanup.
- Ensure TTL is enabled on the table and the attribute name matches exactly.
none
## Wrong: Using string timestamp # Item with 'ExpirationTime': '2024-06-01T12:00:00Z' will NOT expire ## Right: Use Unix epoch seconds # 'ExpirationTime': 1710000000
Quick Reference
Summary tips for using TTL in DynamoDB session management:
- Store expiration as Unix epoch seconds in a numeric attribute.
- Enable TTL on your table with that attribute name.
- Set expiration time when creating or updating session items.
- Expect eventual deletion, not immediate.
- Use TTL to reduce manual cleanup of expired sessions.
Key Takeaways
Enable TTL on your DynamoDB table specifying a numeric expiration attribute.
Store session expiration as Unix epoch time in seconds in each session item.
DynamoDB deletes expired items automatically but not instantly; expect some delay.
Use TTL to automate cleanup of expired sessions and reduce manual maintenance.
Ensure the TTL attribute is correctly named and formatted as a number for TTL to work.