Sub topic 14
Connecting functions to VPC resources
This chapter assumes you know what a VPC, a subnet, a route table and a security group are. It also assumes you have read the earlier chapters on the execution role and cold starts. You will learn how to give a function a network path to private resources such as an RDS database, and how to keep its access to the internet and to AWS APIs working afterwards.
Default networking and why you would change it
By default, a Lambda function runs in a VPC that AWS owns and manages. That network can reach the public internet and public AWS service endpoints. It cannot reach private addresses in your own VPC, such as an RDS instance in a private subnet, an ElastiCache cluster or an internal load balancer.
To reach those resources, you attach the function to your VPC by giving it subnets and security groups. Do this only when the function needs a private resource. A function that only calls DynamoDB, S3 or SQS through their public endpoints does not need it, and attaching it adds networking you must maintain.
How VPC attachment works
When you attach a function to a VPC, Lambda creates a shared network interface (ENI) in each subnet you list. Lambda manages these interfaces through a layer called Hyperplane. The key properties are:
- Lambda creates the interfaces when you create or update the function's VPC configuration, not on each invocation. Setup can take up to a minute, and the function is not ready until it finishes.
- Many execution environments share one interface. Interfaces are keyed by the unique combination of subnet and security group, so functions that share both reuse the same interface.
- Because interfaces exist before invocation, VPC attachment no longer adds the multi-second cold start penalty that older documentation describes. A VPC cold start is close to a non-VPC one.
- The interface count is not tied to concurrency, so scaling out does not by itself consume more IP addresses.
Permissions needed for VPC attachment
Lambda creates the interfaces on your behalf, using the function's execution role. The role needs these EC2 actions:
ec2:CreateNetworkInterfaceec2:DescribeNetworkInterfacesec2:DescribeSubnetsec2:DeleteNetworkInterfaceec2:AssignPrivateIpAddressesec2:UnassignPrivateIpAddresses
The managed policy AWSLambdaVPCAccessExecutionRole grants all of them, plus the CloudWatch Logs permissions from the basic execution policy. If the role lacks them, the create or update call fails with an error about the role not being authorized to perform ec2:CreateNetworkInterface.
Security groups
A security group on the function controls what the function can reach. Security groups are stateful, so you only need to think about the direction that opens the connection.
- Give the function its own security group, for example
lambda-sg, with outbound rules for only the ports it needs (such as 5432 to the database and 443 for HTTPS). - On the database's security group, add an inbound rule that allows the database port from
lambda-sgas the source. Reference the group itself, not an IP range, because function addresses are not stable. - Do not add inbound rules to
lambda-sg. Lambda invocations do not arrive over your network, so nothing needs to connect in.
Internet access: the part that surprises people
A function attached to a VPC loses its default route to the internet. Two points cause most of the confusion:
- The function's interface never gets a public IP address. Placing the function in a public subnet does not give it internet access. Public subnets only help resources that have a public or Elastic IP.
- To reach the internet, put the function in private subnets whose route table sends
0.0.0.0/0to a NAT gateway. The NAT gateway sits in a public subnet whose route table sends0.0.0.0/0to an internet gateway.
A NAT gateway costs an hourly fee plus a per-gigabyte processing charge. For functions that only talk to AWS services, VPC endpoints are usually cheaper and keep traffic off the internet.
| Target | Endpoint type | How it works |
|---|---|---|
| S3, DynamoDB | Gateway endpoint | Adds a route to the route table. No hourly charge. |
| SQS, SNS, Secrets Manager, STS, KMS, CloudWatch Logs and most others | Interface endpoint | Places an interface with private IPs in your subnets. Charged per hour per Availability Zone plus data. |
| Third-party APIs | NAT gateway | Required, since endpoints only cover AWS services and some partner services. |
Interface endpoints need a security group that allows inbound HTTPS (port 443) from the function's security group. Enable private DNS on the endpoint so the standard service hostname resolves to the private address, and your SDK code needs no changes.
Two common cases:
- A function that reads Secrets Manager at startup needs either a NAT gateway or a
secretsmanagerinterface endpoint. - Lambda itself writes logs to CloudWatch through its own path. Your function does not need a CloudWatch Logs endpoint just to log, but it does if your code calls the Logs API.
Defining the configuration with SAM
This template attaches a function to two private subnets in different Availability Zones. It passes the subnet and security group IDs as parameters.
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Parameters:
PrivateSubnetIds:
Type: List<AWS::EC2::Subnet::Id>
LambdaSecurityGroupId:
Type: AWS::EC2::SecurityGroup::Id
Resources:
DbCheckFunction:
Type: AWS::Serverless::Function
Properties:
Handler: app.handler
Runtime: python3.12
CodeUri: src/
MemorySize: 256
Timeout: 10
Policies:
- AWSLambdaVPCAccessExecutionRole
VpcConfig:
SubnetIds: !Ref PrivateSubnetIds
SecurityGroupIds:
- !Ref LambdaSecurityGroupId
Environment:
Variables:
DB_HOST: orders-db.internal.example.com
DB_PORT: '5432'Always list subnets in at least two Availability Zones. If one zone has an outage, Lambda runs the function in the others. With a single subnet, the function depends on that one zone.
Testing connectivity from inside the function
When a connection fails, first check whether the network path works at all, before you debug your database client. This handler opens a plain TCP connection and reports the result and the time taken.
import os
import socket
import time
def handler(event, context):
host = os.environ["DB_HOST"]
port = int(os.environ["DB_PORT"])
start = time.time()
try:
with socket.create_connection((host, port), timeout=3):
status = "reachable"
except OSError as exc:
status = f"failed: {exc}"
return {
"host": host,
"port": port,
"status": status,
"seconds": round(time.time() - start, 3),
}The error tells you where to look. A timed out result usually means a route or security group is blocking packets, because dropped packets produce no reply. Connection refused means the packets arrived but nothing listens on that port. A name resolution error points to DNS, such as a private hosted zone not associated with the VPC.
Managing database connections
Network attachment solves reachability. It does not solve connection volume. Each execution environment handles one request at a time and holds its own connections. A traffic spike that creates hundreds of environments can open hundreds of database connections and exhaust the database's limit.
- Create the connection outside the handler, as you did for the boto3 client, so warm invocations reuse it. Add logic to reconnect if a reused connection has been closed.
- Use RDS Proxy for relational databases. It pools connections, so many environments share a small set of database connections. The proxy lives in your VPC, so the function reaches it through the same subnet and security group setup.
- Cap the function's reserved concurrency if the database cannot handle the load, as described in the concurrency chapter.
Common failures
| Symptom | Likely cause | Fix |
|---|---|---|
| Function create or update fails with an EC2 authorization error | Execution role lacks the network interface permissions | Attach `AWSLambdaVPCAccessExecutionRole` |
| Calls to a public API or AWS service hang until the function times out | No route to a NAT gateway, or no VPC endpoint | Add a NAT route or an interface or gateway endpoint |
| Function in a public subnet still has no internet | Lambda interfaces never get public IPs | Move to a private subnet with a NAT route |
| Database connection times out | Database security group does not allow the function's group | Allow the port from `lambda-sg` |
| `Connection refused` | Wrong port or host, or database not listening | Check the endpoint and port |
| `Too many connections` under load | Each environment opens its own connection | Use RDS Proxy or limit concurrency |
| Intermittent failures in one Availability Zone | Only one subnet configured, or one subnet's route is broken | Use subnets in several zones with identical routing |
| Errors about insufficient IP addresses | Subnets are too small | Use larger subnets, since the interfaces consume addresses |
Event sources and VPC attachment
Attaching a function to a VPC only changes what the function's own code can reach. It does not change how triggers reach the function. API Gateway, S3 notifications and asynchronous invocations call Lambda through the Lambda service, not through your VPC. For poll-based sources such as SQS, the Lambda service polls the queue itself, so you do not need an SQS endpoint for the trigger to work. You only need one if your handler's code calls SQS, for example to send a message.
Exercise
A function is attached to two private subnets and reads from an RDS database successfully. After you attach it, a new call to the Secrets Manager API times out, and the VPC has no NAT gateway. Name two ways to fix it, and say which you would choose if the function only calls AWS services.
Show answer
One fix is to add a NAT gateway in a public subnet and route 0.0.0.0/0 from the private subnets to it. The other is to create an interface VPC endpoint for Secrets Manager with private DNS enabled, in the function's subnets, with a security group that allows port 443 from the function's security group. If the function only calls AWS services, choose the interface endpoint. It keeps traffic on the AWS network and avoids NAT processing charges, while a NAT gateway is only required for non-AWS destinations.
Exercise
Why does placing a VPC-attached function in a public subnet not give it internet access, and what must be true of its subnet instead?
Show answer
Lambda's network interfaces only have private IP addresses and never receive a public or Elastic IP, so an internet gateway route cannot translate their traffic. The function must be in a private subnet whose route table sends 0.0.0.0/0 to a NAT gateway, which itself sits in a public subnet with a route to an internet gateway.