AWS Lambda VPC Connection Timeout Fix
In this tutorial, you'll learn about AWS Lambda VPC Connection Timeout Fix. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
Your Lambda function connected to a VPC times out when accessing resources inside the VPC or the internet — the function lacks proper subnet routing, NAT gateway access, or security group permissions.
Step-by-Step Fix
1. Check VPC configuration on the function
aws lambda get-function-configuration --function-name my-function --query 'VpcConfig'
Expected output:
{
"SubnetIds": ["subnet-abc", "subnet-def"],
"SecurityGroupIds": ["sg-123"],
"VpcId": "vpc-456"
}
If VpcConfig is empty, the function is not in a VPC.
2. Add public internet access via NAT Gateway
# Wrong: using private subnets without NAT Gateway
# Lambda in private subnet has no route to 0.0.0.0/0
# Right: create a NAT Gateway in a public subnet and route
aws ec2 create-nat-gateway --subnet-id subnet-public --allocation-id eipalloc-123
aws ec2 create-route --route-table-id rtb-private --destination-cidr-block 0.0.0.0/0 --nat-gateway-id nat-123
3. Update Lambda VPC configuration
aws lambda update-function-configuration \
--function-name my-function \
--vpc-subnet-ids subnet-private-a subnet-private-b \
--vpc-security-group-ids sg-lambda
4. Fix security group rules
# Allow Lambda to connect to RDS on port 5432
aws ec2 authorize-security-group-ingress \
--group-id sg-rds \
--protocol tcp \
--port 5432 \
--source-group sg-lambda
# Allow Lambda to connect to ElastiCache on port 6379
aws ec2 authorize-security-group-ingress \
--group-id sg-cache \
--protocol tcp \
--port 6379 \
--source-group sg-lambda
import boto3
import psycopg2
import os
def lambda_handler(event, context):
# Wrong: hardcoded connection without timeout
conn = psycopg2.connect(
host=os.environ['DB_HOST'],
dbname=os.environ['DB_NAME'],
user=os.environ['DB_USER'],
password=os.environ['DB_PASSWORD']
)
# Right: connection with timeout and retry logic
import socket
socket.setdefaulttimeout(5)
try:
conn = psycopg2.connect(
host=os.environ['DB_HOST'],
dbname=os.environ['DB_NAME'],
user=os.environ['DB_USER'],
password=os.environ['DB_PASSWORD'],
connect_timeout=5
)
return {"statusCode": 200, "body": "Connected"}
except Exception as e:
return {"statusCode": 500, "body": str(e)}
5. Test connectivity with a simple function
import urllib.request
import json
def lambda_handler(event, context):
# Test VPC connectivity
try:
response = urllib.request.urlopen('http://internal-lb-123.us-east-1.elb.amazonaws.com/health', timeout=5)
return {"statusCode": 200, "body": "VPC connectivity OK"}
except Exception as e:
return {"statusCode": 500, "body": f"VPC error: {str(e)}"}
Prevention
- Always use private subnets with NAT Gateway for Lambda functions that need internet access.
- Use VPC endpoints for AWS services (S3, DynamoDB) instead of NAT Gateway.
- Set connection timeouts in your code to avoid infinite hangs.
- Test VPC connectivity from a Lambda function before deploying production code.
- Use at least 2 subnets in different Availability Zones for high availability.
Common Mistakes with lambda vpc connect
- Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
These mistakes appear frequently in real-world AWS code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro