DynamoDB TTL: How It Works, When Items Actually Get Deleted, and the Patterns Around It
DynamoDB TTL deletes items after a timestamp you set. That’s the whole description, and it undersells the feature. You can use TTL to expire sessions, soft-delete records, enforce retention policies, archive data through Streams, and keep tables small without writing any cleanup code.
Two facts make TTL a design tool instead of a cleanup tool. First, deletion is not instant: AWS deletes expired items in the background, typically within a few days. Second, every TTL delete lands in the Stream, marked as a service delete. Once both are second nature, the patterns below follow.
How DynamoDB TTL works
The TTL attribute must be a Number holding epoch seconds. DynamoDB data types covers how to store dates in general.
You turn on TTL for a table and name one attribute as the TTL attribute. On each item you want to expire, you write a Unix epoch timestamp in seconds into that attribute. A background process finds items whose timestamp is in the past and deletes them.
const SEVEN_DAYS = 7 * 24 * 60 * 60
await SessionEntity.put({
sessionId,
userId,
ttl: Math.floor(Date.now() / 1000) + SEVEN_DAYS,
}).go()
The rules, all from the AWS docs:
| Rule | What it means in practice |
|---|---|
| The attribute must be a Number | DynamoDB ignores items where the TTL attribute is a String. An ISO date string never expires. |
| The value is epoch seconds | Date.now() returns milliseconds. A millisecond value is read as a date far in the future, so the item never expires. |
| Values more than five years in the past are ignored | ttl: 0 does not delete the item now. Epoch 0 is decades ago, so TTL skips it. |
| Items without the attribute never expire | Leave it off anything that should live forever. |
| Deletion happens within a few days of expiry | There is no SLA. Plan for days, not minutes. |
| Expired items still appear in reads until deleted | Queries, scans, and gets return them. They still count toward storage and read cost. |
| TTL deletes use no write capacity | Except on global tables, where each replica Region pays a replicated write. |
| Deletes also remove the item from GSIs and LSIs | Same as a normal delete. |
| You can rescue an expired item | Update the TTL to a future time, or remove it, before the delete runs. |
The write-capacity row is what makes TTL cheap enough to use everywhere. A normal DeleteItem costs a write. A TTL delete costs nothing.
Turning TTL on
TTL is a table setting. In SST it’s one line on the table:
const table = new sst.aws.Dynamo('AppTable', {
fields: { pk: 'string', sk: 'string', gsi1pk: 'string', gsi1sk: 'string' },
primaryIndex: { hashKey: 'pk', rangeKey: 'sk' },
globalIndexes: { GSI1: { hashKey: 'gsi1pk', rangeKey: 'gsi1sk' } },
ttl: 'ttl',
})
Or from the CLI on an existing table:
aws dynamodb update-time-to-live \
--table-name AppTable \
--time-to-live-specification "Enabled=true, AttributeName=ttl"
TTL in a single-table design
A table gets one TTL attribute. In a single-table design that means every entity type shares it. Sessions, invites, OTP codes, and soft-deleted articles all write to the same ttl attribute.
Two habits keep this safe:
- Use a name that means nothing else.
ttlworks.expiresAtis risky. Sooner or later someone adds aSubscriptionentity with a numericexpiresAtthat means “the plan ends here,” and TTL deletes the subscription record a few days after the plan lapses. In a multi-table design that collision can’t happen. In a single table it’s one attribute name away. - Set it per entity, on purpose. Entities that should never expire never set
ttl. Entities that do expire set it on every write path, including updates that recompute it.
In ElectroDB, declare it as a plain number attribute on each entity that needs it:
attributes: {
// ...
ttl: { type: 'number' }, // epoch seconds; DynamoDB TTL attribute for the whole table
},
Pattern 1: Pure expiry (the easy case)
Anything that doesn’t need to exist after a deadline:
- Session tokens: 24-hour TTL
- Email verification codes: 1-hour TTL
- Pending invitations: 7-day TTL, after which the invite is gone for good
- OTP and 2FA codes: 10-minute TTL
- Cache entries: whatever your cache TTL would be in Redis
The pattern is “set TTL on insert, never touch it again.” No cleanup job, no cron, no Lambda.
The deletion delay matters here only if business logic says “after expiry, the item must be gone.” A 10-minute OTP code can sit in the table for two more days. Your code that checks it must compare the timestamp itself, which brings us to the next pattern.
Pattern 2: Read-after-expiry filtering
Expired items keep coming back from reads until TTL deletes them. If that matters, filter on the timestamp at read time:
const nowEpoch = () => Math.floor(Date.now() / 1000)
const result = await SessionEntity.query
.byUser({ userId })
.where(({ ttl }, { gt }) => gt(ttl, nowEpoch()))
.go()
Items that have logically expired but haven’t been deleted yet drop out of the result. The cost: you still pay RCU for the filtered items, because the filter runs after the read. For a get, check the timestamp in code.
This is the standard pairing. TTL handles physical cleanup. The read-time filter handles correctness. Your storage stays bounded and your queries are right immediately.
Pattern 3: Soft delete with permanent purge
The most common user-facing delete in modern apps: don’t remove anything right away. Set a deletedAt timestamp, and let TTL hard-delete the item after a retention window (30 days, 90 days, whatever you pick).
async function softDelete(articleId: string) {
const now = new Date()
const THIRTY_DAYS = 30 * 24 * 60 * 60
await ArticleEntity.patch({ articleId })
.set({
deletedAt: now.toISOString(),
ttl: Math.floor(now.getTime() / 1000) + THIRTY_DAYS,
})
.go()
}
What you get without extra code:
- A restore window. A user who deletes by accident has 30 days to recover. Restore means clearing
deletedAtandttl. - No cleanup job. DynamoDB enforces the retention period.
- A “recently deleted” view. A sparse index on
deletedAtlists soft-deleted items without indexing live ones. The sparse index pattern is the partner technique here.
You also need a read-time filter on deletedAt so soft-deleted items stay out of normal queries:
ArticleEntity.query.byAuthor({ authorId })
.where(({ deletedAt }, { notExists }) => notExists(deletedAt))
.go()
Pattern 4: Retention windows for compliance
Some data has to be kept for a set period and then deleted. GDPR-style erasure deadlines, financial records with an X-year retention, audit logs that must purge after Y months.
Set the TTL at write time to the end of the retention window:
const ONE_YEAR = 365 * 24 * 60 * 60
await AuditEntity.put({
eventId,
userId,
action,
ttl: Math.floor(Date.now() / 1000) + ONE_YEAR, // hard-delete after 1 year
}).go()
Two cautions:
- Document the delay. “Deleted at the one-year mark” really means “deleted within a few days after the one-year mark.” Your compliance owner needs to know this. If the rule says “gone within 24 hours,” TTL alone does not meet it. Run an explicit delete job and keep TTL as the backstop.
- TTL doesn’t reach backups or copies. Point-in-time recovery, on-demand backups, and anything you streamed to S3 keep the data until you purge those separately.
Pattern 5: Archive on expiry via Streams
When TTL deletes an item, DynamoDB writes a REMOVE record to the Stream with userIdentity.type = "Service" and userIdentity.principalId = "dynamodb.amazonaws.com". That’s how you tell a TTL delete from a delete your code made. You can route that record to:
- S3 via Firehose, for long-term archive
- Another DynamoDB table, for cold storage
- OpenSearch or Athena, if you want to query after the live item is gone
- A Lambda that writes a tombstone so later code knows the item existed
// Lambda triggered by the table's Stream (NEW_AND_OLD_IMAGES or OLD_IMAGE)
export async function handler(event: DynamoDBStreamEvent) {
for (const record of event.Records) {
if (record.eventName !== 'REMOVE') continue
if (record.userIdentity?.principalId !== 'dynamodb.amazonaws.com') continue
// TTL-driven delete: archive it
const oldImage = unmarshall(record.dynamodb.OldImage)
await archiveToS3(oldImage)
}
}
On a global table, only the Region where the TTL delete happened marks it as a service delete. In the replica Regions the Stream record cannot be identified as a TTL delete, so run the archiver in one Region.
This is how old IoT readings flow to S3 without a custom cleanup pipeline. The IoT time-series pattern uses it. DynamoDB Streams: fan-out, CDC, and projections goes deeper on the streaming side.
Pattern 6: Sliding TTL (touch to extend)
Sessions that should expire after inactivity, not at a fixed time. Each access moves the TTL forward:
async function touchSession(sessionId: string) {
const FIFTEEN_MIN = 15 * 60
await SessionEntity.patch({ sessionId })
.set({ ttl: Math.floor(Date.now() / 1000) + FIFTEEN_MIN })
.go()
}
Run this on every authenticated request and the session lives as long as the user is active.
The trade-off: every request is now a write. On busy endpoints, throttle it, for example by updating only when the stored TTL is less than ten minutes away. Because deletion can lag by days, a sliding TTL also needs the read-time check from Pattern 2. Otherwise a session that expired an hour ago still authenticates.
Common bugs
Milliseconds instead of seconds. The item never expires. Every TTL write should go through one helper that divides by 1000.
Writing a String. ttl: new Date().toISOString() is silently ignored. TTL only reads Numbers.
Expecting ttl: 0 to delete now. It doesn’t. Values more than five years in the past are skipped. To delete now, call delete.
Forgetting the read-time filter. Soft-deleted and expired items show up in queries until TTL runs. Filter on deletedAt or on ttl > now.
Using TTL for time-critical deletes. “Delete this user’s data within one hour of cancellation” is not a TTL job. Use an explicit delete and treat TTL as the backstop.
Reusing the TTL attribute name for business data. In a single table, one entity’s expiresAt becomes every entity’s delete trigger.
Mental model
TTL is a free background job that does one thing: delete items whose TTL timestamp is in the past, eventually. Anything that must happen at the moment of expiry (notify the user, archive, decrement a counter) has to happen through the Stream. Anything that must hold before the delete runs has to happen through a read-time filter.
In a single-table design TTL slots in with three partners. A sparse index gives you the “recently deleted” or “expiring soon” view. A read-time filter keeps results correct during the days before deletion. A Stream and a Lambda handle the side effects. TTL itself does the cheap physical cleanup.
When all four work together, old data ages out, user code sees the right items, what needs archiving gets archived, and the table never grows without bound. No scheduled jobs.
The cheapest GB you can store in DynamoDB is the one TTL already deleted. The patterns at singletable.dev lean on TTL where it pays: analytics events, IoT readings, and chat messages all combine TTL with sparse indexes for retention windows. If you want GSIs explained the same way, read how DynamoDB GSIs work. I’m building singletable.dev to make these design choices visible at schema time.
TTL deletes also appear in the table’s stream. See DynamoDB Streams for how to tell them from user deletes.