AWS Builder Center
DynamoDB TTL is not a timer: set it up in CDK and filter expired items yourself

DynamoDB TTL is not a timer: set it up in CDK and filter expired items yourself

Enable DynamoDB TTL in CDK, store the expiry as epoch seconds, and filter expired items in queries, because deletion can lag by days.

Estudiante de ingeniería de software | DevOps
DynamoDB time to live (TTL) is a cheap way to get rid of data that has a natural expiry: sessions, one-time tokens, cached API responses. You name an attribute, put a timestamp in it, and DynamoDB removes the item once that time has passed.
The catch is in the word "once". TTL is a cleanup process, not a timer. The documentation says expired items are typically deleted within a few days of their expiration time. Until that happens, the item is still in the table, and a Query or Scan can return it.

Turn it on in CDK

In CDK, TTL is one property on the table. The attribute name is the only thing you choose.
const cdk = require('aws-cdk-lib');
const dynamodb = require('aws-cdk-lib/aws-dynamodb');

class SessionsStack extends cdk.Stack {
constructor(scope, id, props) {
super(scope, id, props);
new dynamodb.Table(this, 'Sessions', {
partitionKey: { name: 'sessionId', type: dynamodb.AttributeType.STRING },
billingMode: dynamodb.BillingMode.PAY_PER_REQUEST,
timeToLiveAttribute: 'expiresAt',
});
}
}

const app = new cdk.App();
new SessionsStack(app, 'SessionsStack');
Running cdk synth on this produces an AWS::DynamoDB::Table with this block, which is what turns TTL on:
TimeToLiveSpecification:
AttributeName: expiresAt
Enabled: true
The synthesized template also carries DeletionPolicy: Retain, because CDK's default removal policy for a table is to keep it when the stack is deleted. That has nothing to do with TTL, but it is worth knowing before you delete a test stack and wonder where the table went.

What goes in the attribute

The TTL attribute has to be a Number holding a Unix epoch time in seconds. Items whose TTL attribute is not a Number are ignored by the TTL process, so a string like "2026-12-01" will sit in the table forever without any error. The name is case sensitive too: if the table is configured with expiresAt and your code writes ExpiresAt, nothing expires.
Seconds is the part that is easy to get wrong in JavaScript, where Date.now() returns milliseconds.
const expiresAt = Math.floor(Date.now() / 1000) + 60 * 60 * 24; // 24 hours from now
I did not find anything in the documentation about what happens if you write a millisecond value, so I would not rely on any particular behaviour. Compute seconds explicitly and move on.

Filter expired items on read

Because deletion lags, the item that expired an hour ago can still be returned. For a session table that means an expired session may look valid. The documentation recommends filter expressions to remove expired items from Scan and Query results. A lookup by key can do the same check in application code or with a condition.
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb');
const { DynamoDBDocumentClient, QueryCommand } = require('@aws-sdk/lib-dynamodb');

const doc = DynamoDBDocumentClient.from(new DynamoDBClient({}));

async function activeSessions(userId) {
const now = Math.floor(Date.now() / 1000);
const out = await doc.send(new QueryCommand({
TableName: process.env.TABLE_NAME,
IndexName: 'byUser',
KeyConditionExpression: 'userId = :u',
FilterExpression: '#exp > :now',
ExpressionAttributeNames: { '#exp': 'expiresAt' },
ExpressionAttributeValues: { ':u': userId, ':now': now },
}));
return out.Items;
}
The synth output above is the only part of this article I ran. The query snippet and the byUser index it refers to are not deployed or executed, and the index is not part of the stack shown earlier, so treat that block as a pattern to adapt.

Timing details that matter

A few documented behaviours are worth keeping in mind when you plan around TTL:
  • Enabling TTL takes approximately one hour to apply across all partitions, so do not expect the first expirations immediately after a deploy.
  • Calling UpdateTimeToLive again within that window, or enabling TTL when it is already on, returns a ValidationException. This is mostly relevant if you manage TTL outside CloudFormation.
  • Renaming the TTL attribute means disabling TTL and enabling it again with the new name.
  • Restored tables need TTL configured again.

Cost

The documentation states that TTL deletes do not consume write throughput, so clearing out old items does not add to your write bill. Global tables are the exception: the delete is free in the region where the item expired, but replicating it to other regions consumes replicated write capacity, and charges apply there.
The storage side is where the lag costs you. An expired item keeps occupying space until it is removed, so TTL is a good fit for trimming a table over time and a poor fit for anything that must disappear at an exact moment. If a record has to stop being visible at a precise time, enforce that in your read path with the filter above and let TTL handle the storage.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article