0
0
DynamoDBquery~5 mins

TTL use cases (sessions, logs, cache) in DynamoDB

Choose your learning style9 modes available
Introduction

TTL helps automatically remove old data from your database. This keeps it clean and saves space without you doing extra work.

You want to keep user login sessions only for a limited time.
You need to store logs but only want to keep recent ones.
You cache data to speed up your app but want old cache to expire.
You want to automatically delete temporary data after some time.
You want to reduce storage costs by removing outdated records.
Syntax
DynamoDB
TTL attribute: A timestamp attribute in your DynamoDB table that marks when an item should expire.
Enable TTL on the table and specify the attribute name.
DynamoDB automatically deletes items after the timestamp passes.
The TTL attribute must be a number representing Unix epoch time in seconds.
Expired items are deleted within 48 hours after the timestamp passes, not instantly.
Examples
This example shows a TTL attribute named session_expiry that stores when a user session should expire.
DynamoDB
TTL attribute: session_expiry
Value example: 1686000000 (Unix time in seconds)
Logs can have a log_expire_at attribute to remove old logs automatically.
DynamoDB
TTL attribute: log_expire_at
Value example: 1686003600
Cache items use cache_ttl to expire cached data after some time.
DynamoDB
TTL attribute: cache_ttl
Value example: 1686007200
Sample Program

This example creates a table for user sessions with a TTL attribute session_expiry. The session expires at the specified Unix timestamp.

DynamoDB
CREATE TABLE UserSessions (
  userId STRING HASH KEY,
  sessionId STRING SORT KEY,
  sessionData STRING,
  session_expiry NUMBER
);

-- Enable TTL on attribute 'session_expiry' in AWS Console or via CLI

-- Insert a session that expires at a specific Unix timestamp
INSERT INTO UserSessions (userId, sessionId, sessionData, session_expiry) VALUES (
  'user123', 'sess456', 'data here', 1725152400
);
OutputSuccess
Important Notes

TTL does not guarantee immediate deletion; it happens asynchronously within about 48 hours.

Expired items are not returned in queries after deletion but may still appear briefly before removal.

Use TTL to save costs and keep your database tidy without manual cleanup.

Summary

TTL automatically deletes old data based on a timestamp attribute.

Common uses: sessions, logs, and cache expiration.

TTL helps manage storage and keeps data fresh without manual work.