What triggers ENIs to be created for AWS Lambdas accessing VPC resources

Viewed 1756

We have multiple lambdas deployed with access to our VPC using the VpcConfig setting.

I understand that AWS Lambda normally creates lambdas on demand, but if you have them connecting to your VPC then AWS will (at some point) create an ENI on one of the subnets specified in the VpcConfig and attach the lambda container to allow it access to your VPC.

But what actually triggers the ENI to be created and attached? I've noticed that there is not a 1-to-1 mapping between lambdas and ENIs, nor between ENIs and subnets. Also what decides which subnet the ENI attaches to?

If I run a test lambda (to ping localhost) manually, configured for our VPC, it never creates an ENI. So I'm guessing this is because it is not trying to access anything on the network.

1 Answers

This requires an understanding of Lambda containers and container reuse. When a Lambda function is first invoked a Lambda container is created and the Lambda function is deployed into the container. That container will be assigned an ENI if you have the function configured with VPC settings. Then the next time you invoke the function, if the container still exists with the function deployed, and isn't currently in use by another invocation, it will re-use that container (so no need to create a new ENI). If the container is busy handling another invocation then a second container will be deployed with a new ENI to handle the pending invocation. When a container is idle for a period of time then the Lambda service will automatically delete the container and the attached ENI.

Also what decides which subnet the ENI attaches to?

When you configured the Lambda function for VPC access you were required to list one or more subnets in the VPC that it would be deployed to. I don't believe the actual algorithm has been published by Amazon but it appears to use a round-robin algorithm to spread container creation out between the configured subnets. For practical purposes you could consider it to "randomly" pick a subnet every time it creates a new Lambda container. I assume it will also check that there are available IP addresses in the subnet, or fail over to another subnet if it has issues obtaining an IP for the new ENI in a given subnet, but again, I'm not aware of that being documented anywhere.

Related