Expiring Items Automatically with Time to Live
This lesson explains how Time to Live (TTL) deletes items automatically after a timestamp stored in each item, removing expired data such as sessions and temporary records at no cost and with no scheduled jobs.
Learning outcomes
After completing this lesson, you will be able to:
- Describe the attribute format that TTL requires and why deletion can be delayed.
- Explain why an application should filter out expired items that have not yet been deleted.
- Describe how expired items can be archived through DynamoDB Streams.
How TTL works
Many applications store data that is only useful for a limited time, such as user sessions, one-time passwords, temporary shopping carts or event records kept for 90 days. Time to Live (TTL) removes such items automatically. TTL is enabled on a table by naming one attribute, such as expiresAt, and each item stores its own expiry time in that attribute.
The value must be a Number containing a Unix epoch time in seconds, the number of seconds since 1 January 1970 UTC. Items without the attribute, or where it holds another type such as a string, never expire. A background process scans for items whose expiry time has passed and deletes them, usually within a few days of expiry. These deletions consume no write capacity and are free, which makes TTL cheaper than a scheduled job that finds and deletes items itself. Until an expired item is actually deleted, it still appears in reads, queries and scans.
aws dynamodb update-time-to-live --table-name Sessions \
--time-to-live-specification "Enabled=true, AttributeName=expiresAt"The application sets the expiry when it writes each item, as in the following example, which keeps a session for 24 hours.
import time
table.put_item(Item={
"sessionId": session_id,
"userId": user_id,
"expiresAt": int(time.time()) + 24 * 60 * 60, # expires in 24 hours (epoch seconds)
})Handling expired items correctly
Because deletion can be delayed, an application that must never use expired data filters it out itself:
table.query(
KeyConditionExpression=Key("userId").eq(user_id),
FilterExpression=Attr("expiresAt").gt(int(time.time())),
)Common mistakes are storing milliseconds instead of seconds, which places the expiry thousands of years in the future, and storing the timestamp as a string, which TTL ignores.
Archiving expired data
Deletion by TTL is permanent, but expired items do not have to be lost. When DynamoDB Streams is enabled on the table, each TTL deletion appears in the stream as a REMOVE record. These records can be told apart from deletions made by the application because their userIdentity field identifies the DynamoDB service as the principal that performed the deletion.
A Lambda function attached to the stream, with an event filter that matches only those TTL REMOVE records, can write each expired item to Amazon S3 before it is gone. This keeps the table small and fast while retaining a low-cost archive, for example of old orders that must be kept for audit.
Sessions that never expire
A team enables TTL on a sessions table using the attribute expiresAt, but a week later the table still holds every session ever created.
| Check | Finding |
|---|---|
| Attribute type | Some items store expiresAt as a string, which TTL ignores |
| Units | The rest store Date.now() + 86400000: milliseconds, placing expiry in the year 58,000 |
| Attribute name | Matches the TTL setting exactly |
The code is changed to store Math.floor(Date.now() / 1000) + 86400 as a Number, and a one-off script corrects existing items. Expired sessions now disappear within days, and the login code filters on expiresAt so that an expired but not yet deleted session is never accepted.
Why can a query still return items whose TTL time has passed?
Show answer
TTL deletes expired items in the background, usually within a few days of expiry. An application that must never use expired data filters them out itself, for example with a filter expression on the TTL attribute.
Exam Tips
Remember for the exam
- To expire session data or temporary records automatically, use TTL.
- The TTL attribute must be a Number holding epoch seconds.
- TTL deletions consume no write capacity but can be delayed, so filter expired items in reads when exactness matters.
- To archive items as they expire, process the TTL
REMOVErecords from DynamoDB Streams.