sakshi rawal
sakshi rawal

Reputation: 1

How to fix Lambda function timeout when interacting with DynamoDB using AWS SDK v3 in Node.js?

I’m building a serverless API with Node.js using AWS Lambda, and my function interacts with DynamoDB to retrieve data. However, every time I try to interact with DynamoDB, the Lambda function times out before the request completes.

I have correctly configured my Lambda function’s execution role with the necessary permissions, and I’ve ensured that the AWS SDK v3 (@aws-sdk/client-dynamodb) is properly installed and initialized. Despite this, the Lambda function times out without successfully querying DynamoDB.

Here’s what I’ve done so far:

I expect the Lambda function to complete successfully and return data from DynamoDB without any timeouts.

Task timed out after 30.01 seconds

const { DynamoDBClient, GetItemCommand } = require("@aws-sdk/client-dynamodb");

const client = new DynamoDBClient({ region: "us-east-1" });

const params = {
  TableName: "MyTable",
  Key: { "id": { S: "123" } }
};

exports.handler = async (event) => {
  try {
    const data = await client.send(new GetItemCommand(params));
    return {
      statusCode: 200,
      body: JSON.stringify(data),
    };
  } catch (err) {
    console.error("Error", err);
    return {
      statusCode: 500,
      body: JSON.stringify({ error: "Could not retrieve data" }),
    };
  }
};

I’ve verified that the DynamoDB table exists and contains data for the provided id, but the Lambda function still times out.

Upvotes: 0

Views: 112

Answers (1)

jarmod
jarmod

Reputation: 78842

The most obvious reason that your Lambda function times out when connecting to DynamoDB (or any internet endpoint) is that you configured the Lambda function to attach to a VPC.

Unless you need access to other resources within your VPC, such as an RDS database, there's no need to attach the Lambda function to your VPC so re-configure and re-deploy the Lambda function. The Lambda function will then use a default route to the internet provided by the Lambda service.

If you do need to access to other resources within your VPC, then add a DynamoDB VPC Endpoint to your VPC.

Upvotes: 0

Related Questions