skip to Main Content

I’m using an AWS lambda function to connect to the internet. It belongs to a VPC with 1 public subnet and 3 private subnets (3 availability zones) with 2 routes tables (public route for public subnet and private route for private subnets) but when I run the Lambda function, it gives me a timeout. Does anyone know what to do?

import json
import urllib.request

def lambda_handler(event, context):
    url = "https://www.google.com"
    
    try:
        # Make HTTP GET request
        response = urllib.request.urlopen(url)
        
        # Read response data
        html = response.read().decode("utf-8")
        
        # Log response
        print("Response from", url, ":", html)
        
        return {
            'statusCode': 200,
            'body': json.dumps('Successfully accessed the internet!')
        }
    except Exception as e:
        # Log error
        print("Error:", str(e))
        
        return {
            'statusCode': 500,
            'body': json.dumps('Failed to access the internet!')
        }

2

Answers


  1. If your Lambda function does not need to connect to any resources in the VPC, then simply disconnect the Lambda function from the VPC and it will have full Internet access. That’s all you need to do and it is the cheapest option.

    However, if the Lambda function also needs to access resources in the VPC, then you will need this configuration:

    • Connect the Lambda function only to private subnets (not the public subnet)
    • Launch a NAT Gateway in the public subnet (charges apply)
    • Update the Route Table on the private subnets to send traffic destined for 0.0.0.0/0 to the NAT Gateway

    This way, when the Lambda function wants to access the Internet, the request will be sent via the NAT Gateway.

    Login or Signup to reply.
  2. The default timeout for a lambda function is around 3 seconds. Try updating the timeout from

    AWS Management Console -> Configuration -> General Configuration -> Timeout -> Save.

    The maximum duration a Lambda function can run is 15 minutes (So set timeout accordingly).

    Try to run again and check output.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search