Search code examples
amazon-web-servicesnetworkingaws-lambdaamazon-vpc

AWS Lambda public subnet EIP to give internet access


Grumping about the NAT gateway cost for allowing a lambda function attached to a VPC access to internet I found some suggestion about deploying the lambda in a public subnet instead of a private and attaching an EIP to the ENI that gets created by the Lambda. (I have an IGW attached to the VPC as well).

I followed this post: https://stackoverflow.com/a/74683282/3701903

This works! My lambda running in a public subnet gets access to internet.

However, I've read in a lot of places that "this shouldn't be possible", or "the only way to give internet access to a lambda is via a NAT-gateway/instance." or "If you do it like that, it wont scale properly".

Is this just a bad idea? My lambda needs access to both internet and resources in the VPC (rds in private subnet for instance)


Solution

  • That's a neat hack. It was made possible by the release of Lambda Hyperplane ENIs in September 2019. Prior to that time, each in-VPC Lambda instance required its own ENI. Afterwards, multiple instances could share the same ENI.

    The limitation on scaling is that each ENI requires its own Elastic IP, and there are a limited number of Elastic IPs that you can associate per region.

    Where this can cause a problem is that each combination of subnet and security groups requires its own ENI. If you just assign the "default" security group to all of your Lambdas, then you'll need one ENI per subnet, and can easily stay under the quota. However, in a multi-application environment, you will typically create multiple security groups that control communications within the app (for example, a database SG that allows inbound connections from one Lambda but not another).

    You should also be aware that when using an Elastic IP you will be subject to EC2 data transfer charges. Traffic into the Lambda will be free, while traffic out of the Lambda will be charged at $0.09 per GB (for US regions), which is less than traffic going through a NAT gateway.

    Bottom line: if you're just doing this for your personal account, have at it. But in a production environment, I think the total cost of ownership (including the risk of disruption) will be far higher than a NAT Gateway. If you really don't want to pay for the AWS-managed NAT, it's not that difficult to configure a t3.micro instance to serve in that capacity. But beware that you'll now be on the hook for keeping it healthy.