Home > Blockchain >  Invoking AWS Lambda from Dynamodb Steam in Nodejs
Invoking AWS Lambda from Dynamodb Steam in Nodejs

Time:09-23

When I try to run the lambda function from AWS console the code works fine. Since I want to run a specific code only if there is a new dynamo DB record added, I want to run a lambda function from the dymanoDB stream insert event. I tried the following code, it seems the lambda is not invoking.

Permission in serverless.yml

  - Effect: "Allow"
    Action:
      - "lambda:InvokeFunction"
    Resource: 
      - "*"

Code for dynamoDB stream

 

exports.main = async (event) => {
    const records = event.Records.filter((record) => {
        if (record.eventName.toUpperCase() === "INSERT") {
            const recordType = record.dynamodb.NewImage.type.S;

            if (recordType.toUpperCase() === "TRA") {
                 // here I capture the value for the arguments. They work fine
                 inkvokeTraLamda(keyword, key, tag);
            }  
        }
    });
};

The function where lambda is called

const AWS = require("aws-sdk");
const lambda = new AWS.Lambda({ region: "us-west-1" });
exports.inkvokeTraLamda = async function invoke(
    keyword,
    key,
    tag
) {
    const playload = {
        keyword,
        key,
        tag,
    };

    const LambdaPromise = (params) => lambda.invoke(params).promise();

    const resp = await LambdaPromise(params);
    console.log(resp);
    return resp;  
};


I will highly appreciate your guidance.

CodePudding user response:

Instead of telling one lambda function to invoke another. Configure your concerned Lambda function to listen to DynamoDB Streams. So your listener Lambda will have this added into its events config.

  events:
  - stream:
      type: dynamodb
      batchSize: 1
      # INFO: Batch Window size in seconds allows you to wait as long as 300s to build a batch before invoking a function.
      # Now, a function is invoked when one of the following conditions is met: the payload size reaches 6MB, the Batch Window reaches its maximum value, or the Batch Size reaches its maximum value.
      # With Batch Window, you can increase the average number of records passed to the function with each invocation.
      batchWindow: 5
      # This gives the option to recursively split the failed batch and retry on a smaller subset of records, eventually isolating the metadata causing the error.
      bisectBatchOnFunctionError: true
      maximumRetryAttempts: 3
      maximumRecordAgeInSeconds: 120

      arn:
        Fn::GetAtt:
          - <TableName>
          - <TableStreamArn>

As soon as something is inserted, your second code snippet will respond. The third snippet seems non-related to be DB Streams.

  • Related