日本語

Delivering DynamoDB Changes to Lambda with AWS Emulator

​​AWS Emulator​Amazon SQS,AWS CLI,AWS Lambda,DynamoDB,Python

When you enable a stream on a DynamoDB table and connect it to a Lambda function with an event source mapping, the function is invoked for every insert, update, and delete. This article shows how to run "process data when it changes" logic, such as sending a notification when an order's status changes, or copying data to another table or a search index. It covers testing this locally or in CI without an AWS account. I also cover what happens when the function fails and the changes after it stop, and the settings that get you out of that state: the retry count, the failure destination, and batch splitting. The commands and output from my test environment are included as they are (I omit parts of long output).

Note

The test environment was Ubuntu 24.04 (x86_64), AWS Emulator 1.0.531 (released November 19, 2026, Debian package), and AWS CLI 2.41.2. I did not use an AWS account or credentials. I did not verify how the real Amazon DynamoDB and AWS Lambda behave (how long until changes arrive, retry intervals, shard splitting, pricing). Where this article touches on those, it relies on the official documentation. I did not test ParallelizationFactor, MaximumRecordAgeInSeconds, ReportBatchItemFailures, tumbling windows, or runtimes other than Python. The emulator does not evaluate IAM policies the same way AWS does, so the permission errors in this article do not confirm whether the same role would work on real AWS.

Diagram of the flow: a DynamoDB table, its stream, the event source mapping, and the Lambda function (the labels in the image are in Japanese). The two boxes below compare what happens when the retry limit of 2 is used up. Without batch splitting, the failing bad-3 is discarded along with o-4, and SQS receives the positions of two changes. With BisectBatchOnFunctionError enabled, only the position of bad-6 is sent, and the function processes o-7 and o-8.
The flow in this article, where Lambda is invoked from a stream, and the difference in which changes are discarded on failure

Start the emulator and point the AWS CLI at it

I installed AWS Emulator as a Debian package after verifying its signature, following the Linux installation steps in the official guide. In the first terminal, I started it with aws-emulator -t off. -t off disables sending usage data (telemetry).

In a second terminal, I set the environment variables that point the AWS CLI at the emulator. I added AWS_PAGER so the output is printed directly instead of being opened in a pager.

bash
export AWS_ENDPOINT_URL=https://127.0.0.1:9297
export AWS_SHARED_CREDENTIALS_FILE=~/.aws/emulator/9297/emulator_credentials
export AWS_CONFIG_FILE=~/.aws/emulator/9297/config
export AWS_CA_BUNDLE=~/.aws/emulator/9297/ca.pem
export AWS_EC2_METADATA_DISABLED=true
export AWS_DISABLE_HOST_PREFIX_INJECTION=true
export AWS_REGION=us-east-1
export AWS_DEFAULT_REGION=us-east-1
unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN AWS_PROFILE
export AWS_PAGER=""

Create a table with a stream enabled

I created the orders table example-orders with --stream-specification. StreamViewType specifies what gets written to the stream. The DynamoDB Streams documentation lists these options: KEYS_ONLY (only the key), NEW_IMAGE (the item after the change), OLD_IMAGE (the item before the change), and NEW_AND_OLD_IMAGES (both). I wanted to see state transitions (before and after), so I chose NEW_AND_OLD_IMAGES.

text
$ aws dynamodb create-table --table-name example-orders --attribute-definitions AttributeName=orderId,AttributeType=S --key-schema AttributeName=orderId,KeyType=HASH --billing-mode PAY_PER_REQUEST --stream-specification StreamEnabled=true,StreamViewType=NEW_AND_OLD_IMAGES --query "TableDescription.{Status:TableStatus,Stream:StreamSpecification,LatestStreamArn:LatestStreamArn}"
{
    "Status": "CREATING",
    "Stream": {
        "StreamEnabled": true,
        "StreamViewType": "NEW_AND_OLD_IMAGES"
    },
    "LatestStreamArn": "arn:aws:dynamodb:us-east-1:<12桁のアカウントID>:table/example-orders/stream/2026-11-20T02:30:25.689"
}
$ aws dynamodb wait table-exists --table-name example-orders

I replaced the account ID in the output with <12桁のアカウントID>. LatestStreamArn is the ARN of the stream that I connect the function to. I use it repeatedly, so I stored it in the shell variable STREAM.

bash
STREAM=$(aws dynamodb describe-table --table-name example-orders --query Table.LatestStreamArn --output text)

Create an execution role and a function

I created an execution role that Lambda can assume. I wrote the trust policy in trust.json.

json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": { "Service": "lambda.amazonaws.com" },
      "Action": "sts:AssumeRole"
    }
  ]
}
text
$ aws iam create-role --role-name example-stream-role --assume-role-policy-document file://trust.json --query Role.Arn --output text
arn:aws:iam::<12桁のアカウントID>:role/example-stream-role

The function code is fn/lambda_function.py. For each change it receives, it logs the event type (eventName), the order ID, and the status before and after the change. To observe failure behavior, changes whose order ID starts with bad raise an exception.

python
import json


def lambda_handler(event, context):
    records = event["Records"]
    print(f"records={len(records)}")
    for r in records:
        ddb = r["dynamodb"]
        order_id = ddb["Keys"]["orderId"]["S"]
        old = ddb.get("OldImage", {}).get("status", {}).get("S")
        new = ddb.get("NewImage", {}).get("status", {}).get("S")
        print(f"{r['eventName']} orderId={order_id} old={old} new={new}")
        if order_id == "o-1":
            print(json.dumps(event))
        # Changes whose order ID starts with bad are made to fail
        if order_id.startswith("bad"):
            raise RuntimeError(f"failed: {order_id}")
    return {}

I packaged the function as a zip and waited until it was ready to use.

text
$ zip -j function.zip fn/lambda_function.py
  adding: lambda_function.py (deflated 42%)
$ aws lambda create-function --function-name example-order-stream --runtime python3.12 --handler lambda_function.lambda_handler --role arn:aws:iam::<12桁のアカウントID>:role/example-stream-role --zip-file fileb://function.zip --timeout 10 --query '{State:State,Timeout:Timeout}'
{
    "State": "Pending",
    "Timeout": 10
}
$ aws lambda wait function-active-v2 --function-name example-order-stream

Connect the stream and the function with an event source mapping

I ran create-event-source-mapping with no policy attached to the role. The emulator returned an error saying the role could not read the stream.

text
$ aws lambda create-event-source-mapping --function-name example-order-stream --event-source-arn $STREAM --starting-position TRIM_HORIZON

aws: [ERROR]: An error occurred (InvalidParameterValueException) when calling the CreateEventSourceMapping operation: Cannot access stream arn:aws:dynamodb:us-east-1:<12桁のアカウントID>:table/example-orders/stream/2026-11-20T02:30:25.689. Please ensure the role can perform the GetRecords, GetShardIterator, DescribeStream, and ListStreams Actions on your stream in IAM.
(以下は省略)

Following the official steps for processing DynamoDB records with Lambda, I attached the AWS managed policy AWSLambdaDynamoDBExecutionRole to the execution role. This policy grants the four operations named in the error message (DescribeStream, GetRecords, GetShardIterator, ListStreams) and permission to write to CloudWatch Logs. After attaching it, I added --batch-size 10 and created the mapping again. This time it succeeded.

text
$ aws iam attach-role-policy --role-name example-stream-role --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaDynamoDBExecutionRole
$ aws lambda create-event-source-mapping --function-name example-order-stream --event-source-arn $STREAM --starting-position TRIM_HORIZON --batch-size 10
{
    "UUID": "9ca52178-b9c6-4bed-a647-547d9559bc6d",
    "StartingPosition": "TRIM_HORIZON",
    "BatchSize": 10,
    "MaximumBatchingWindowInSeconds": 0,
    "ParallelizationFactor": 1,
(中略)
    "State": "Creating",
(中略)
    "MaximumRecordAgeInSeconds": -1,
    "BisectBatchOnFunctionError": false,
    "MaximumRetryAttempts": -1,
(以下は省略)
}

--starting-position specifies where to start reading in the stream. It is required for DynamoDB. TRIM_HORIZON reads from the oldest change still in the stream, and LATEST reads from changes made after the mapping is created. According to the Lambda and DynamoDB documentation, on real AWS it can take several minutes from creating the mapping until reading begins. Changes made in that gap can be missed with LATEST, so TRIM_HORIZON is recommended. --batch-size is the maximum number of changes passed in one invocation. The CreateEventSourceMapping API reference gives 100 as the default for DynamoDB Streams.

Right after creation, State was Creating. By the time I first checked with get-event-source-mapping, it was already Enabled.

Inserts, updates, and deletes each arrive in one invocation

I inserted order o-1, updated its status to shipped, and then deleted it. After waiting 8 seconds, I read the function's logs from CloudWatch Logs. For --start-time, I passed the time immediately before the writes, in milliseconds.

text
$ aws dynamodb put-item --table-name example-orders --item "{\"orderId\":{\"S\":\"o-1\"},\"status\":{\"S\":\"received\"}}"
$ aws dynamodb update-item --table-name example-orders --key "{\"orderId\":{\"S\":\"o-1\"}}" --update-expression "SET #s = :s" --expression-attribute-names "{\"#s\":\"status\"}" --expression-attribute-values "{\":s\":{\"S\":\"shipped\"}}"
$ aws dynamodb delete-item --table-name example-orders --key "{\"orderId\":{\"S\":\"o-1\"}}"
$ aws logs filter-log-events --log-group-name /aws/lambda/example-order-stream --start-time 1795141836000 --query 'events[].message' --output text | tr '\t' '\n' | grep -E '^(records|INSERT|MODIFY|REMOVE)'
records=1
INSERT orderId=o-1 old=None new=received
records=1
MODIFY orderId=o-1 old=received new=shipped
records=1
REMOVE orderId=o-1 old=shipped new=None

Inserts arrived as INSERT, updates as MODIFY, and deletes as REMOVE. Updates contained both the old image (OldImage) and the new image (NewImage), and deletes contained only the old image. The INSERT event that the function received is shown below. As in the example event in the official documentation, each element of Records has an eventName, and under dynamodb the keys and item values appear in DynamoDB's typed format ({"S": "o-1"}).

json
{
    "Records": [
        {
            "eventID": "4df24e05f5e57267fce2df4dc16d3deb",
            "eventName": "INSERT",
            "eventVersion": "1.1",
            "eventSource": "aws:dynamodb",
            "awsRegion": "us-east-1",
            "dynamodb": {
                "ApproximateCreationDateTime": 1795141836,
                "Keys": {
                    "orderId": {
                        "S": "o-1"
                    }
                },
                "NewImage": {
                    "orderId": {
                        "S": "o-1"
                    },
                    "status": {
                        "S": "received"
                    }
                },
                "SequenceNumber": "100000000000000000001",
                "SizeBytes": 34,
                "StreamViewType": "NEW_AND_OLD_IMAGES"
            },
            "eventSourceARN": "arn:aws:dynamodb:us-east-1:<12桁のアカウントID>:table/example-orders/stream/2026-11-20T02:30:25.689"
        }
    ]
}

Writes that only rewrote the same values did not arrive. I inserted o-2 with put-item, then ran put-item again with exactly the same content, and ran update-item to set status to the same value. Only the first INSERT reached the function. The DynamoDB Streams documentation also states that PutItem and UpdateItem calls that do not change any item data do not write a stream record.

When the function fails, later changes stop

Here I look at failure behavior. The mapping kept the default settings it was created with, and MaximumRetryAttempts (the retry count) was -1. The API reference says -1 means there is no retry limit, so retries continue until the records expire from the stream.

I inserted bad-3, which makes the function raise an exception. Two seconds later I inserted a normal order, o-4, and then waited 20 seconds.

text
$ aws dynamodb put-item --table-name example-orders --item "{\"orderId\":{\"S\":\"bad-3\"},\"status\":{\"S\":\"received\"}}"
$ aws dynamodb put-item --table-name example-orders --item "{\"orderId\":{\"S\":\"o-4\"},\"status\":{\"S\":\"received\"}}"
$ aws logs filter-log-events --log-group-name /aws/lambda/example-order-stream --start-time 1795141859000 --query 'events[].message' --output text | tr '\t' '\n' | grep -E '^(records|INSERT|MODIFY|REMOVE|\[ERROR\])'
records=1
INSERT orderId=bad-3 old=None new=received
[ERROR] RuntimeError: failed: bad-3
records=1
INSERT orderId=bad-3 old=None new=received
[ERROR] RuntimeError: failed: bad-3
(中略)
records=2
INSERT orderId=bad-3 old=None new=received
[ERROR] RuntimeError: failed: bad-3

During those 20 seconds, the function failed on bad-3 seven times. At some point records=2 appeared, meaning o-4 was in the same batch. However, the exception was raised at the leading bad-3, so no o-4 line was ever printed. The mapping's LastProcessingResult was PROBLEM: Function call failed.

Stream changes are processed in order, so when one change fails, the changes after it cannot move forward. The documentation on handling failed records also says that with the default settings, a single bad record can block processing of its shard for up to one day. According to the DynamoDB Streams data retention documentation, stream records can be removed at any time after 24 hours.

Decide the retry count and the failure destination

To get out of this stalled state, set the retry count (--maximum-retry-attempts). Changes that exhaust their retries are discarded. To keep a record of what was discarded, I set an SQS queue as the failure destination (OnFailure). When I created the queue and tried to update the mapping, I got an error because the role did not have permission to send messages to SQS.

text
$ aws sqs create-queue --queue-name example-stream-failures --query QueueUrl --output text
https://sqs.us-east-1.amazonaws.com/<12-digit account ID>/example-stream-failures
$ aws lambda update-event-source-mapping --uuid 9ca52178-b9c6-4bed-a647-547d9559bc6d --maximum-retry-attempts 2 --destination-config '{"OnFailure":{"Destination":"arn:aws:sqs:us-east-1:<12桁のアカウントID>:example-stream-failures"}}'

aws: [ERROR]: An error occurred (InvalidParameterValueException) when calling the UpdateEventSourceMapping operation: The function execution role does not have permissions to call SendMessage on SQS
(以下は省略)

As described in the failure destination documentation, sending to SQS requires sqs:SendMessage on the execution role. I wrote the policy in dest-policy.json and attached it as an inline policy.

json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "sqs:SendMessage",
      "Resource": "arn:aws:sqs:us-east-1:<12桁のアカウントID>:example-stream-failures"
    }
  ]
}
text
$ aws iam put-role-policy --role-name example-stream-role --policy-name example-stream-failures --policy-document file://dest-policy.json
$ aws lambda update-event-source-mapping --uuid 9ca52178-b9c6-4bed-a647-547d9559bc6d --maximum-retry-attempts 2 --destination-config '{"OnFailure":{"Destination":"arn:aws:sqs:us-east-1:<12桁のアカウントID>:example-stream-failures"}}' --query '{State:State,MaximumRetryAttempts:MaximumRetryAttempts,DestinationConfig:DestinationConfig}'
{
    "State": "Updating",
    "MaximumRetryAttempts": 2,
    "DestinationConfig": {
        "OnFailure": {
            "Destination": "arn:aws:sqs:us-east-1:<12桁のアカウントID>:example-stream-failures"
        }
    }
}

In the 15 seconds after the update, the function failed once more on the two-record batch of bad-3 and o-4, and it was not invoked after that. The queue received the following message.

text
$ aws sqs receive-message --queue-url https://sqs.us-east-1.amazonaws.com/<12桁のアカウントID>/example-stream-failures --wait-time-seconds 5 --max-number-of-messages 10 --query 'Messages[0].Body' --output text | python3 -m json.tool
{
    "version": "1.0",
    "timestamp": "2026-11-20T02:31:31.727+0000",
    "responseContext": {
        "statusCode": 200,
        "executedVersion": "$LATEST",
        "functionError": "Unhandled"
    },
    "requestContext": {
        "functionArn": "arn:aws:lambda:us-east-1:<12桁のアカウントID>:function:example-order-stream",
        "condition": "RetryAttemptsExhausted",
        "approximateInvokeCount": 8,
        "requestId": "9c813ef4-b0d6-4c05-b767-4916d239ccbf"
    },
    "DDBStreamBatchInfo": {
        "shardId": "shardId-00000001795141825689-7ccfdb00",
        "batchSize": 2,
(中略)
        "startSequenceNumber": "100000000000000000005",
(中略)
        "endSequenceNumber": "100000000000000000006",
(以下は省略)
    }
}

RetryAttemptsExhausted in condition means the retries were used up. The approximateInvokeCount of 8 equals 7 invocations before I changed the setting plus 1 after. As in the example failure destination message, the message does not include the change contents. It records only which range of the stream was discarded (startSequenceNumber and endSequenceNumber). The contents can be read back from the stream.

text
$ IT=$(aws dynamodbstreams get-shard-iterator --stream-arn $STREAM --shard-id shardId-00000001795141825689-7ccfdb00 --shard-iterator-type AT_SEQUENCE_NUMBER --sequence-number 100000000000000000005 --query ShardIterator --output text); aws dynamodbstreams get-records --shard-iterator $IT --limit 2 --query 'Records[].[dynamodb.SequenceNumber,eventName,dynamodb.Keys.orderId.S]' --output text
100000000000000000005	INSERT	bad-3
100000000000000000006	INSERT	o-4
Warning

The discarded batch also included o-4, which the function had never processed. Setting a retry count alone means that normal changes sharing a batch with a failing change are discarded too. The destination keeps only positions, so if you want to read the contents back, do it before they are removed from the stream.

Split failed batches and drop only the failing change

The documentation on handling failed records says that if you enable BisectBatchOnFunctionError, a batch that fails is split into two and retried, which isolates the bad record. Splits do not count toward the retry count.

I deleted the earlier mapping and created a new one with all three settings from the start. To avoid reading the same stream from the beginning again, I set --starting-position to LATEST. After State became Enabled, I waited 3 seconds and then inserted bad-6, o-7, and o-8 in succession.

text
$ aws lambda delete-event-source-mapping --uuid 9ca52178-b9c6-4bed-a647-547d9559bc6d --query State
"Deleting"
$ aws lambda create-event-source-mapping --function-name example-order-stream --event-source-arn $STREAM --starting-position LATEST --batch-size 10 --maximum-retry-attempts 2 --bisect-batch-on-function-error --destination-config '{"OnFailure":{"Destination":"arn:aws:sqs:us-east-1:<12桁のアカウントID>:example-stream-failures"}}' --query '{UUID:UUID,State:State,StartingPosition:StartingPosition,MaximumRetryAttempts:MaximumRetryAttempts,BisectBatchOnFunctionError:BisectBatchOnFunctionError}'
{
    "UUID": "2ce65846-acf8-418e-9e34-e7f90c6fb34d",
    "State": "Creating",
    "StartingPosition": "LATEST",
    "MaximumRetryAttempts": 2,
    "BisectBatchOnFunctionError": true
}

In the logs after 30 seconds, the function failed six times on batches containing bad-6 (one or two records). It then succeeded when invoked with the two records o-7 and o-8.

text
$ aws logs filter-log-events --log-group-name /aws/lambda/example-order-stream --start-time 1795141920000 --query 'events[].message' --output text | tr '\t' '\n' | grep -E '^(records|INSERT|MODIFY|REMOVE|\[ERROR\])'
records=1
INSERT orderId=bad-6 old=None new=received
[ERROR] RuntimeError: failed: bad-6
(中略)
records=1
INSERT orderId=bad-6 old=None new=received
[ERROR] RuntimeError: failed: bad-6
records=2
INSERT orderId=o-7 old=None new=received
INSERT orderId=o-8 old=None new=received

One message reached the queue. Its batchSize was 1, and the position covered only the sequence number of bad-6 (100000000000000000007). The mapping's LastProcessingResult also returned to OK.

text
$ aws sqs receive-message --queue-url https://sqs.us-east-1.amazonaws.com/<12桁のアカウントID>/example-stream-failures --wait-time-seconds 5 --max-number-of-messages 10 --query 'Messages[].Body' --output json | python3 -c 'import json,sys; [print(json.dumps({k: json.loads(b)["DDBStreamBatchInfo"][k] for k in ("batchSize","startSequenceNumber","endSequenceNumber")}, indent=2)) for b in json.load(sys.stdin)]'
{
  "batchSize": 1,
  "startSequenceNumber": "100000000000000000007",
  "endSequenceNumber": "100000000000000000007"
}

If you want to drop only the failing change, enable batch splitting along with the retry count and the destination. The Lambda and DynamoDB documentation also describes returning a partial batch response from the function, so that only the failed records are retried and the successful ones are not. The same page also notes, in the section on stream reading and batching, that an event source mapping may deliver the same change more than once. It strongly recommends writing the function to be idempotent, so that calling it repeatedly with the same change is safe.

Pass only inserts to the function with a filter

If you only need to act on new orders, you can add a filter to the mapping. The function is then not invoked for changes that do not match. I deleted the current mapping and recreated it with a filter that passes only changes whose eventName is INSERT.

text
$ aws lambda create-event-source-mapping --function-name example-order-stream --event-source-arn $STREAM --starting-position LATEST --filter-criteria '{"Filters":[{"Pattern":"{\"eventName\":[\"INSERT\"]}"}]}' --query '{State:State,FilterCriteria:FilterCriteria}'
{
    "State": "Creating",
    "FilterCriteria": {
        "Filters": [
            {
                "Pattern": "{\"eventName\":[\"INSERT\"]}"
            }
        ]
    }
}

I inserted, updated, and deleted o-9, then waited 10 seconds. Only the one INSERT reached the function.

text
$ aws logs filter-log-events --log-group-name /aws/lambda/example-order-stream --start-time 1795141964000 --query 'events[].message' --output text | tr '\t' '\n' | grep -E '^(records|INSERT|MODIFY|REMOVE)'
records=1
INSERT orderId=o-9 old=None new=received

The DynamoDB event filtering documentation also explains how to filter on keys and on values in NewImage and OldImage. It notes that numeric comparison operators (numeric equality and ranges) cannot be used in DynamoDB filters.

Cleanup

I deleted the mapping, the function, the queue, and the table, in that order. The mapping's State changed to Deleting, and after 3 seconds the list was empty.

text
$ aws lambda delete-event-source-mapping --uuid 218ff4b7-5939-4b48-bf95-ec6e0cda076b --query State
"Deleting"
$ aws lambda list-event-source-mappings --function-name example-order-stream
{
    "EventSourceMappings": []
}
$ aws lambda delete-function --function-name example-order-stream
{
    "StatusCode": 204
}
$ aws sqs delete-queue --queue-url https://sqs.us-east-1.amazonaws.com/<12-digit account ID>/example-stream-failures
$ aws dynamodb delete-table --table-name example-orders --query TableDescription.TableStatus
"DELETING"

The emulator keeps created resources in memory and clears them when it stops. If you want to start from an empty state for each test, restarting the emulator also cleans up.

​Posted by 86