Amazon DynamoDB Tutorial 0/30 lessons ~6 min read Lesson 21

    Time to Live (TTL) and Expiry Events

    Time to Live deletes items automatically after a timestamp you store on each item.

    Course progress0%
    Focus
    10 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Time to Live deletes items automatically after a timestamp you store on each item. Deletes are free (they do not consume write capacity) and appear in the stream, so you can archive or react to expiry. TTL is ideal for sessions, carts, idempotency keys, and raw time-series data.

    Purpose of this lesson

    You will enable TTL, write items with expiry timestamps, filter out expired-but-not-yet-deleted items, and archive expiries to S3 from the stream.

    Understanding the topic

    How TTL works:

    • The TTL attribute must be a Number holding a Unix epoch time in seconds.
    • Expired items are deleted in the background, typically within a few days of expiry — not at the exact second.
    • Until deletion, expired items are still returned by reads; filter them out if correctness matters.
    • TTL deletions appear in the stream as REMOVE events with userIdentity.type = "Service" and principalId = "dynamodb.amazonaws.com".
    • Items whose TTL value is far in the past (more than five years) are not deleted by TTL.

    Syntax reference

    Enable TTL and write an expiring cart:

    bash
    aws dynamodb update-time-to-live \
    --table-name ShopTable \
    --time-to-live-specification "Enabled=true, AttributeName=expiresAt"
    ts
    import { PutCommand, QueryCommand } from "@aws-sdk/lib-dynamodb";
    import { ddb, TABLE } from "./ddb";
    const now = Math.floor(Date.now() / 1000);
    await ddb.send(new PutCommand({
    TableName: TABLE,
    Item: { PK: "CUSTOMER#c1", SK: "CART", items: ["BOOK-1"], expiresAt: now + 7 * 24 * 3600 },
    }));
    // Exclude items that expired but have not been deleted yet
    const { Items = [] } = await ddb.send(new QueryCommand({
    TableName: TABLE,
    KeyConditionExpression: "PK = :pk",
    FilterExpression: "attribute_not_exists(expiresAt) OR expiresAt > :now",
    ExpressionAttributeValues: { ":pk": "CUSTOMER#c1", ":now": now },
    }));

    Informative example

    Archive TTL expiries to S3 — distinguish system deletes from user deletes:

    ts
    import type { DynamoDBStreamEvent } from "aws-lambda";
    import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
    const s3 = new S3Client({});
    export const handler = async (event: DynamoDBStreamEvent) => {
    for (const record of event.Records) {
    const ttlDelete =
    record.eventName === "REMOVE" &&
    record.userIdentity?.type === "Service" &&
    record.userIdentity?.principalId === "dynamodb.amazonaws.com";
    if (!ttlDelete) continue;
    await s3.send(new PutObjectCommand({
    Bucket: process.env.ARCHIVE_BUCKET,
    Key: `expired/${record.dynamodb!.SequenceNumber}.json`,
    Body: JSON.stringify(record.dynamodb!.OldImage),
    }));
    }
    };

    The stream must include old images (OLD_IMAGE or NEW_AND_OLD_IMAGES) for the archive to contain the deleted data.

    Best practices

    • Store TTL as epoch seconds — milliseconds put expiry thousands of years in the future.
    • Filter expired items in reads when stale data would be a bug.
    • Use TTL instead of scheduled delete jobs; TTL deletes do not consume write capacity.

    Common mistakes

    • Relying on TTL for exact-time expiry (session security, coupon end times) — enforce the time in application logic too.
    • Storing the TTL attribute as a string, which TTL ignores.
    • Expecting restored tables to keep TTL settings — re-enable TTL after a restore.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    2 questions
    1BeginnerQuestionIs TTL deletion immediate?+

    Answer

    No. Items are deleted in the background, typically within a few days after the expiry time. Expired items can still be read until then, so filter on the TTL attribute where it matters.
    2IntermediateQuestionHow do you tell a TTL delete from an application delete in a stream?+

    Answer

    TTL deletes are REMOVE records whose userIdentity has type 'Service' and principalId 'dynamodb.amazonaws.com'. Application deletes have no such userIdentity.

    Hands-on exercise

    Hands-on: store idempotency keys for payment requests with expiresAt = now + 24h. Write a claimIdempotencyKey(key) function that uses attribute_not_exists(PK) OR expiresAt < :now so expired keys can be reused even before TTL deletes them.

    Summary

    TTL removes expired items for free, eventually. Store epoch seconds, filter expired items when needed, and use stream REMOVE events to archive or react.

    Ready to mark this lesson complete?Track your journey across the entire course.