node.jsamazon-web-servicesamazon-s3aws-lambdatimeout

Timeout response when trying to use AWS S3 SDK with lambda (Node.js)


My Lambda runs fine with all services except S3. Any action I try to perform, the execution hangs and I get a timeout. For testing purposes, I'm using a default vpc configuration.

I have the S3 full access policy attached to the Lambda's role.

My function:

import AWS from "aws-sdk";

export const handler = async (event) => {
  var s3 = new AWS.S3();
  try {
    var params = { 
      Bucket: 'bucket-name',
      Key: 'original-b31a4e7537250988ddd0a7e6c241c64b.png'
    }

    let res = await s3.getObject(params).promise();

    console.log(res);
  } catch (error) {
    console.error(error);
  }
}

Response:

{
  "errorMessage": "2024-11-16T17:53:39.400Z a4412f66-e960-4f0f-ac3d-c1c71e6bc81a Task timed out after 63.07 seconds"
}

Solution

  • You Lambda resides within a VPC, so it doesn't have a direct connection to the internet. and S3 is an external service. Without the internet access, your Lambda hangs becaues it cannot reach S3.

    Other service can work out without any issue because AWS offers VPC endpoint, however S3 requires an additional steps if your Lambda resides in the VPC.

    To solve this out you need to:

    1. Add an S3 VPC Endpoint

      • Create an S3 VPC Endpoint in the VPC where your Lambda function runs.

      • This allows your Lambda to connect to S3 privately without needing internet access.

    or

    1. Use a NAT Gateway or NAT Instance

      • If you want your Lambda to have full internet access, deploy a NAT Gateway or NAT Instance in a public subnet.

      • Ensure your Lambda’s private subnet route table points to the NAT gateway for internet traffic.

    If your Lambda doesn’t need to access resources within a private VPC (like RDS or private EC2 instances), the simplest fix is to run the Lambda outside the VPC.