Create Lambda Function

Create a lambda function to copy changed records from the Orders DynamoDB streams to the OrdersHistory table.

  1. Open the AWS Management Console and go to the Lambda Service dashboard.
  2. In the Functions section, click on Create function.
  3. Select Author from scratch.
  4. Set create-order-history-ddbs as the function name.
  5. Select a version of Python as the runtime.

AWS Lambda function creation wizard

  1. Expand the Change default execution role section.
  2. Select Create a new role from AWS policy templates.
  3. Set create-order-history-ddbs-execution-role as the role name.
  4. Select the Simple microservice permissions from the Policy templates options menu.

AWS Lambda function creation wizard

  1. Click Create function and wait to be redirected to the AWS Lambda console for your newly created function.

  2. Replace the content of lambda_function.py with the function code below.

import os
import boto3
import datetime
from aws_lambda_powertools import Logger
from aws_lambda_powertools.utilities.data_classes.dynamo_db_stream_event import (
    DynamoDBStreamEvent,
    DynamoDBRecordEventName
)
from botocore.exceptions import ClientError

table_name = os.getenv("ORDERS_HISTORY_DB")
logger = Logger()

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(table_name)


def store_history_record(old_item_image):
    logger.debug({"operation": "store_history_record", "old_image": old_item_image})

    # Set a value for the partition key - pk, and sort key - sk; for the OrdersHistory table
    # before writing the record to the OrdersHistory table.
    pk = old_item_image["id"]
    sk = str(datetime.datetime.now())
    old_item_image["pk"] = pk
    old_item_image["sk"] = sk

    try:
        response = table.put_item(
            Item=old_item_image
        )
        logger.debug({"operation": "table.put_item", "response": response})
    except ClientError as err:
        logger.error({"operation": "store_history_record", "details": err})
        raise Exception(err)


def lambda_handler(event, context):
    logger.debug({"operation": "lambda_handler", "event": event, "context": context})
    event: DynamoDBStreamEvent = DynamoDBStreamEvent(event)

    for record in event.records:
        if record.event_name == DynamoDBRecordEventName.MODIFY or record.event_name == DynamoDBRecordEventName.REMOVE:
            logger.debug({"record": record})
            if "id" in record.dynamodb.keys:
                store_history_record(record.dynamodb.old_image)
            else:
                raise ValueError("Expected partition key attribute - 'id' not found.")
Line Number Description
11 - 15 Get the Orders History DynamoDB table name from an environment variable, instantiate a logger for the lambda function then create a boto3 resource for interacting with the Orders hHstory DynamoDB table.
23 - 26 Create a new item for the Orders History table using an old image of an item updated on the Orders table. Set the partition key for the new item to the id of the updated order then set the sort key for the new item to the current time.
28 - 35 Write the new item to the Orders History table. Raise an exception if the item is not successfully written to the table.
42 - 45 Process old images of update item event and delete item event received from the Orders DynamoDB table through DynamoDB streams.

This lambda function receives events from DynamoDB streams and writes new items to a DynamoDB table i.e. the OrdersHistory table.

Since we only need to record changes to items on the Orders table, the lambda function is set to process only stream events for modified and deleted items from the Orders table.

  1. Deploy the code changes to your function by selecting Deploy.

AWS Lambda function creation wizard

Do not execute the lambda function you created yet. Additional configuration is required for the set up to work correctly. You will update your lambda function configuration in the next step.