Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 37 ยท Streams, TTL and Integrations

Time to Live (TTL)

Delete expired DynamoDB items automatically with Time to Live: the epoch-seconds attribute, background deletion delay, filtering expired reads and streams.

Some data is only useful for a while: login sessions, one-time codes, shopping carts, cached results, temporary locks, raw events you aggregate after a week. Deleting it with a scheduled job costs write capacity, code and operational attention. Time to Live (TTL) lets DynamoDB do it for you: you mark one attribute as the expiry time, and the service removes items after that time passes. The deletions do not consume write capacity and cost nothing.

TTL is a background cleanup, not a precise timer. Understanding that difference is the key to using it correctly.

How TTL works

  1. You enable TTL on the table and name an attribute (for example expiresAt).
  2. The attribute must hold a Number that is a Unix timestamp in seconds (not milliseconds).
  3. When the current time passes that value, the item becomes eligible for deletion.
  4. A background process scans the table and deletes expired items. This usually happens within a few days (typically 48 hours at most for most tables, but there is no hard promise). Items can remain readable after they have expired.
  5. The deletion removes the item from the table and from its indexes. If a stream is enabled, a REMOVE record appears, flagged as made by the DynamoDB service.
Terminal
# read-only CLI example
aws dynamodb update-time-to-live --table-name Sessions \
  --time-to-live-specification "Enabled=true,AttributeName=expiresAt"

Items without the attribute, or with a non-number or a value that is not valid epoch seconds, are never removed. Values more than five years in the past are ignored.

TTL in one slide

Epoch seconds A Number attribute
Free delete No write units used
Not instant Often delayed hours or days
Stream REMOVE Marked as a TTL delete

Filter expired items yourself when it matters.

1 / 2

Computing the attribute

Add the current time plus the lifetime when you create the item:

Python
import time
item = {
    "PK": "SESSION#9f2c", "SK": "META",
    "userId": "u1",
    "expiresAt": int(time.time()) + 3600,      # one hour from now, in seconds
}

Use integers. A float like 1.7e9 is stored as a number too, but integer seconds avoid confusion. A common bug is passing Date.now() from JavaScript, which is in milliseconds; the timestamp then lies thousands of years away and the item never expires. In JavaScript use Math.floor(Date.now() / 1000).

Do not trust reads to hide expired items

Because deletion lags, an expired item can still come back from GetItem, Query or Scan. If your logic must not see it (a session, a one-time code), filter on the attribute yourself. In a query add a filter expression, or compare after reading:

Python
resp = table.query(
    KeyConditionExpression="PK = :pk",
    FilterExpression="expiresAt > :now",
    ExpressionAttributeValues={":pk": "SESSION#9f2c", ":now": int(time.time())},
)

A filter still reads the item (you pay for it), but the result is correct. For one item, a conditional check in the application after GetItem is simplest.

Try it: simulate TTL with a lazy sweeper

The stand-in below shows the two behaviours: reads that ignore expired items, and a background sweeper that deletes later. It is a simulation (not the real service).

Python Expired but not yet deleted

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Until the sweep ran, the raw read still returned the expired session. Production code should use the live check.

Typical uses and design tips

  • Sessions and tokens: set expiresAt to the logout time. Check it when you read.
  • Rolling event history: keep events for 30 days, then let TTL drop them. A stream with OLD_IMAGE can archive each removed item to S3 before it is gone (see stream integrations).
  • Soft locks: store a lock item with a TTL so that a crashed worker's lock expires, but also store the time and compare it, since the item may linger.
  • Cheaper storage: a table that only needs recent data keeps its size and cost low without a purge job.
  • Extending life: update expiresAt on each activity (sliding expiration) with an UpdateItem.
  • Global tables: a TTL delete in one Region is replicated to others as a delete, which consumes write capacity in the replicas.

TTL is not a security control. If data must be unreadable after a deadline, enforce the deadline in the read path. Never rely on the background deletion for compliance timing.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In what format must the TTL attribute be?

    TTL reads a Number attribute with epoch seconds. Milliseconds produce a date thousands of years away, so the item never expires.
  2. 2. Does TTL deletion consume write capacity?

    TTL deletes are performed in the background without consuming write capacity.
  3. 3. A session expired five minutes ago. What may a GetItem return?

    Expired items can remain for hours or days. Compare expiresAt to the current time when it matters.
  4. 4. How can you archive items that TTL removes?

    TTL deletions appear in the stream as REMOVE events, so a consumer can copy the old image to S3 or another store.

Summary

  • Enable TTL on a table and name a Number attribute with epoch seconds.
  • Expired items are deleted by a free background process, usually within days, not at the exact second.
  • Filter on the attribute when reads must not return expired items.
  • TTL deletions appear in streams as REMOVE records, so they can be archived.
  • Great for sessions, tokens, caches and rolling history; not a security or compliance control.

Next: Stream Integrations