Lambda triggers on stream events let you run code automatically when your database changes. This helps you react quickly to updates without checking manually.
0
0
Lambda trigger on stream events in DynamoDB
Introduction
You want to send a notification when a new item is added to your database.
You need to update another system whenever data changes in your table.
You want to keep a backup of changes made to your database.
You want to analyze data changes in real-time for reports.
You want to clean or validate data right after it is inserted or updated.
Syntax
DynamoDB
1. Enable DynamoDB Streams on your table. 2. Create a Lambda function. 3. Configure the Lambda function as a trigger for the DynamoDB stream. Example JSON event structure received by Lambda: { "Records": [ { "eventID": "string", "eventName": "INSERT | MODIFY | REMOVE", "dynamodb": { "Keys": { ... }, "NewImage": { ... }, "OldImage": { ... }, "SequenceNumber": "string", "SizeBytes": number, "StreamViewType": "NEW_IMAGE | OLD_IMAGE | NEW_AND_OLD_IMAGES | KEYS_ONLY" }, "eventSource": "aws:dynamodb", "eventVersion": "1.1", "eventSourceARN": "string" } ] }
You must enable DynamoDB Streams on your table before Lambda can receive events.
The Lambda function receives an event object containing records of changes.
Examples
This Lambda function logs the type of change and the new data for each record.
DynamoDB
exports.handler = async (event) => { for (const record of event.Records) { console.log('Event Name:', record.eventName); console.log('New Image:', JSON.stringify(record.dynamodb.NewImage)); } };
This function only processes new items added to the table.
DynamoDB
exports.handler = async (event) => { event.Records.forEach(record => { if (record.eventName === 'INSERT') { console.log('New item added:', JSON.stringify(record.dynamodb.NewImage)); } }); };
Sample Program
This Lambda function collects all new items added in the event and logs them together.
DynamoDB
exports.handler = async (event) => { const addedItems = []; for (const record of event.Records) { if (record.eventName === 'INSERT') { addedItems.push(record.dynamodb.NewImage); } } console.log('Added items:', JSON.stringify(addedItems)); };
OutputSuccess
Important Notes
Lambda triggers run automatically and do not require manual polling.
StreamViewType setting controls what data is sent to Lambda (new image, old image, or both).
Remember to give your Lambda function permission to read from the DynamoDB stream.
Summary
Lambda triggers on DynamoDB streams let you run code when data changes.
Enable streams, create a Lambda, and connect them as a trigger.
Use the event data to react to inserts, updates, or deletes automatically.