DynamoDB Time to Live (TTL) does not trigger a standard delete operation. When a record expires, DynamoDB removes it from your table silently in the background. If you rely on event-driven architectures to archive data to S3 or update downstream analytics tables, expecting a standard DeleteItem call will leave your audit logs and data lake incomplete.
The solution requires enabling DynamoDB Streams to capture the REMOVE event generated by the TTL process. This approach ensures that every record lifecycle event—whether initiated by an application or the internal TTL sweeper—is captured and delivered to your consuming architecture. This guide covers how to implement this pattern using Terraform and Lambda, focusing on the mechanics of stream processing.
How it actually works
The TTL sweeper process runs periodically to identify expired items. When an item is deleted, the event contains a userIdentity field of dynamodb.amazonaws.com. By processing these events through a stream, you decouple the expiration logic from your archive storage.
flowchart LR
DDB[DynamoDB Table] --> Stream[DynamoDB Stream]
Stream --> Lambda[Lambda Function]
Lambda --> S3[Amazon S3 Archive]
Lambda --> RDS[Amazon RDS/Aurora]
To implement this, you must first enable both TTL and Streams on your table.
resource "aws_dynamodb_table" "records" {
name = "OperationalRecords"
billing_mode = "PAY_PER_REQUEST"
hash_key = "PK"
attribute {
name = "PK"
type = "S"
}
ttl {
attribute_name = "ExpirationTimestamp"
enabled = true
}
stream_enabled = true
stream_view_type = "OLD_IMAGE"
}
The stream_view_type set to OLD_IMAGE is critical. It ensures that the Lambda function receives the entire record as it existed before deletion, which is necessary if you need to store the historical state of that record in your data lake or analytical database.
When the function triggers, you filter for the REMOVE event type. In Python, your handler would look like this:
import boto3
def lambda_handler(event, context):
for record in event['Records']:
if record['eventName'] == 'REMOVE':
# Check if deletion was triggered by TTL
if record['userIdentity']['type'] == 'Service' and \
record['userIdentity']['principalId'] == 'dynamodb.amazonaws.com':
old_image = record['dynamodb']['OldImage']
archive_record(old_image)
def archive_record(item):
# Logic to push to S3 or target database
pass
To verify this works, insert a record with an ExpirationTimestamp set to a few minutes in the future. After the timestamp passes, query your downstream destination (e.g., S3 using Amazon Athena) to confirm the record appeared.
Design choices and tradeoffs
Streams, not polling. You might consider scanning the table for expired items, but that consumes Read Capacity Units (RCUs) and risks missing records deleted by the sweeper. Streams provide a push-based mechanism that is more cost-effective and precise for change data capture (CDC).
Old Image, not New Image. For deletions, the NewImage is always empty. You must use OLD_IMAGE to retain the payload. You give up the ability to see the "final state" of the item (which is null) but gain the ability to audit exactly what was purged from your system.
Lambda Batching, not per-record processing. When configuring your Event Source Mapping, adjust the batch_size and maximum_batching_window_in_seconds. Processing records in small batches increases throughput and reduces invocation costs, though it adds slight complexity to your error handling if a single record in a batch causes a failure.
Failure modes
Stream shard iterator expiration. If your Lambda function fails repeatedly or is disabled, the stream shard iterator can expire after 24 hours. Once expired, you lose access to those specific events.
- Fix: Monitor
IteratorAgeMillisecondsin CloudWatch. If it trends upward, it indicates your function cannot keep up with the stream volume or is stuck in an error loop.
Lambda execution limits. If your archive destination (such as an RDS instance) is unreachable or slow, the Lambda function will retry the batch. If the function times out, the entire batch is retried.
- Fix: Implement a "Dead Letter Queue" (DLQ) or an "On-Failure Destination" on your Event Source Mapping. This prevents a single poisonous record from blocking the entire stream of deletes.
TTL latency. TTL is not a real-time event. DynamoDB documentation notes that the sweeper usually deletes items within 48 hours of expiration.
- Fix: Do not design business processes that depend on the exact second of expiration. If you need precise data lifecycle management (e.g., immediate deletion for regulatory reasons), use a scheduled trigger or a specific application delete command instead of relying solely on TTL.
When to reach for it (and when not to)
Use this pattern when you are building an operational-to-analytical pipeline where your DynamoDB table acts as a short-lived buffer. It is ideal for compliance-heavy environments where every record deletion must be logged for audit purposes.
Do not use this pattern if you require strict, deterministic timing for deletions. Because the TTL sweeper is a background process, the "delete event" will arrive in your stream whenever the sweeper gets to it. If you need data to vanish at a specific time, perform an explicit DeleteItem from your application code and handle the archival logic within that same transaction or a downstream event.
Conclusion
By combining DynamoDB TTL with Streams, you transform a simple "discard" operation into a traceable, auditable data event. You now have a mechanism to move data from hot storage to cold storage automatically.
To finalize your environment, ensure you have set up least-privilege IAM roles for your Lambda function, granting it dynamodb:GetRecords, dynamodb:GetShardIterator, dynamodb:DescribeStream, and dynamodb:ListStreams. Once you have verified the data flow, remove the development table and Lambda function to avoid unnecessary costs.
Clean up
- Delete the DynamoDB table:
aws dynamodb delete-table --table-name OperationalRecords. - Delete the Lambda function:
aws lambda delete-function --function-name <your-function-name>. - Delete any associated IAM roles and CloudWatch log groups created during your test.
References
- DynamoDB Time to Live (TTL)
- DynamoDB Streams and AWS Lambda triggers
- AWS Event Source Mapping Documentation
About the examples: automated checks confirmed that the Python block parses and that 2 AWS CLI commands match the AWS service API models (operation and parameter names). The examples have not been run end to end, so test them in a non-production environment before relying on them.
Cover photo by selcuk sarikoz on Unsplash.
This article was drafted with AI assistance and is intended for technical review and fact-checking before publication.
Top comments (0)