Search code examples
amazon-web-servicesaws-lambdaamazon-rdsamazon-elasticachevpc

How to Enable Cost-Effective Internet Access for AWS Lambda in a VPC?


I have an AWS Lambda function written in Go that needs to connect to an RDS and an ElastiCache instance, both of which are in a VPC. To achieve this, I placed the Lambda function in an allowed security group and a public subnet. This setup works, and the Lambda function can connect to both RDS and ElastiCache.

Now, I need the Lambda function to make requests to the public internet, for example, https://google.com.br. What is the most cost-effective solution for enabling this?

I came across the option of using a NAT Gateway, but it seems too expensive and overly complex for just making HTTP requests.

How can I achieve internet access for my Lambda function in a cost-effective manner?


Solution

  • AWS NAT Gateway is the AWS recommended way to allow IPv4 traffic from a Lambda in a VPC to connect to the internet.

    You can use either an AWS NAT Gateway or setup your own NAT Instance. The AWS NAT Gateway is a managed NAT device and is simpler than the NAT instance. However, the NAT instance would be the cheaper option. For a pre-built nat instance option, I recommend checking out the fck-nat project.

    With either NAT device type, you will need to configure the subnet routing. The lambda function will need to be assigned to a "Private subnet" and the NAT device will need to be in a "Public Subnet".

    • A Public subnet is a subnet that has a direct route to an internet gateway. Resources in a public subnet can access the public internet.

    • A Private subnet is a subnet that does not have a direct route to an internet gateway. Resources in a private subnet require a NAT device to access the public internet.

    source

    Then, configure the default route (0.0.0.0/0 route) of the route table for the public subnet to point to the Internet Gateway (IGW).

    Lastly, configure the default route (0.0.0.0/0 route) of the route table for the private subnet to point to the NAT device.

    Traffic flow:

    • Lambda --> NAT --> IGW --> Internet

    This should allow the Lambda to reach the internet. The source IP of the Lambda requests will be the NAT device Public IP.

    Note: This configuration is only required when the Lambda function is associated with a VPC. If the lambda, is not associated with a VPC, it will have public internet access by default.


    For more details on how to implement this, AWS has a knowledge article relevant to Lambda in a VPC

    There is also a more general guide for configuring access to the internet from private subnets.


    Using IPv6 as mentioned in comments can work but will require the destination to support IPv6, which may not always be the case.

    Hope this helps!