AWS Lambda in a VPC: S3 Connect Timeouts and Slow First Invocations Despite a NAT Gateway

TechLab Editorial TeamPublished 71 views1 answer
1

Editorial Q&A · This problem and its answer were written by the TechLab editorial team to document a common issue. It isn't a question from a community member. If you've hit a variation of it or know a better approach, add a reply below.

The problem

A Lambda function processes user events from a mobile app. It writes structured data to an RDS PostgreSQL database in private subnets, and uploads the raw event JSON to S3. To reach the database, the function is attached to the VPC's private subnets. A NAT Gateway in the public subnets, with a default route from the private subnets, is supposed to give it access to S3 and other public endpoints.

The setup:

  • Runtime: Python 3.12
  • AWS Region: ap-south-1
  • Database: RDS PostgreSQL in private subnets of the same VPC
  • VPC: 3 public subnets (NAT Gateway) and 3 private subnets (Lambda and RDS), one of each per Availability Zone.
  • Security groups: the function's group allows outbound traffic to the database on port 5432 and all outbound traffic to 0.0.0.0/0. The database's group allows inbound 5432 from the function's group.

Database writes work reliably. S3 uploads don't:

  1. Slow first invocations: some new execution environments take 8–12 seconds to handle their first request, against under 200 ms for warm invocations.
  2. Intermittent S3 timeouts: in those same environments, put_object() takes 5–10 seconds or fails with botocore.exceptions.ConnectTimeoutError. Other environments upload in milliseconds.

A simplified version of the function:

Python
import json
import logging
import os

import boto3
import botocore.exceptions
import psycopg2

logger = logging.getLogger()
logger.setLevel(os.environ.get('LOG_LEVEL', 'INFO'))

# Environment variables
DB_HOST = os.environ.get('DB_HOST')
DB_NAME = os.environ.get('DB_NAME')
DB_USER = os.environ.get('DB_USER')
DB_PASSWORD = os.environ.get('DB_PASSWORD')
S3_BUCKET = os.environ.get('S3_BUCKET_NAME')

s3_client = boto3.client('s3')
db_conn = None

def get_db_connection():
    global db_conn
    if not db_conn or db_conn.closed:
        logger.info("Establishing new DB connection...")
        try:
            db_conn = psycopg2.connect(
                host=DB_HOST,
                database=DB_NAME,
                user=DB_USER,
                password=DB_PASSWORD,
                connect_timeout=5
            )
        except Exception as e:
            logger.error(f"Error connecting to database: {e}")
            raise
    return db_conn

def lambda_handler(event, context):
    request_id = context.aws_request_id
    logger.info(f"Processing event {request_id}")

    try:
        # 1. Store data in RDS
        conn = get_db_connection()
        with conn.cursor() as cur:
            # Example: insert a record
            user_id = event.get('userId')
            event_type = event.get('eventType')
            cur.execute("INSERT INTO events (user_id, event_type) VALUES (%s, %s);", (user_id, event_type))
            conn.commit()
            logger.info(f"Event for user {user_id} stored in RDS.")

        # 2. Upload raw event data to S3
        event_data_bytes = json.dumps(event).encode('utf-8')
        s3_key = f"raw-events/{request_id}.json"
        
        logger.info(f"Attempting to upload {len(event_data_bytes)} bytes to S3 bucket {S3_BUCKET} with key {s3_key}")
        
        # This is where the delay/timeout happens during cold starts
        s3_client.put_object(
            Bucket=S3_BUCKET,
            Key=s3_key,
            Body=event_data_bytes,
            ContentType='application/json'
        )
        logger.info(f"Raw event {request_id} uploaded to S3.")

        return {
            'statusCode': 200,
            'body': json.dumps({'message': 'Event processed successfully!'})
        }
    except botocore.exceptions.ConnectTimeoutError as e:
        logger.error(f"S3 Connect Timeout Error: {e}")
        return {
            'statusCode': 500,
            'body': json.dumps({'message': 'S3 operation timed out during cold start.'})
        }
    except Exception as e:
        logger.error(f"Unhandled error: {e}")
        # Invalidate DB connection on unhandled error to force re-establishment
        global db_conn
        if db_conn:
            db_conn.close()
            db_conn = None
        return {
            'statusCode': 500,
            'body': json.dumps({'message': 'Internal Server Error'})
        }

Expected behaviour: S3 uploads complete in milliseconds through the NAT Gateway, like the database writes.

Actual behaviour: some first invocations take 8–12 seconds, and put_object() sometimes fails with a connect timeout. Warm invocations are fine.

Example error:

Code
[ERROR] 2023-10-27T10:30:10.567Z <request-id> S3 Connect Timeout Error: Connect timeout on endpoint URL: "https://my-log-bucket-123.s3.ap-south-1.amazonaws.com/raw-events/abc-123.json"
Traceback (most recent call last):
  File "/var/task/lambda_function.py", line 75, in lambda_handler
    ContentType='application/json'
  File "/var/runtime/botocore/client.py", line 403, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/var/runtime/botocore/client.py", line 695, in _make_api_call
    http, parsed_response = self._endpoint.make_request(request_dict, request_context)
  File "/var/runtime/botocore/endpoint.py", line 105, in make_request
    return self._send_request(request_dict, request_context)
  File "/var/runtime/botocore/endpoint.py", line 170, in _send_request
    raise ConnectTimeoutError(endpoint_url=request.url, error=e)
botocore.exceptions.ConnectTimeoutError: Connect timeout on endpoint URL: "https://my-log-bucket-123.s3.ap-south-1.amazonaws.com/raw-events/abc-123.json"

The question: what causes the slow, failing S3 connections, and what's the right fix without weakening security or adding much cost?

Advertisement

1 Answer

0

The pattern, where some execution environments time out and others are fast, points to a network path problem in part of the VPC rather than to slow cold starts in general.

Why the Problem Occurs

It isn't network interface creation. Before 2019, Lambda created a network interface (ENI) in your VPC during cold starts, which added many seconds. Since the move to shared Hyperplane ENIs, those interfaces are created when you create or reconfigure the function, not on each cold start, so VPC attachment adds little to a cold start today. Older guides that blame ENI setup are out of date.

A connect timeout means packets aren't getting a reply. ConnectTimeoutError means the TCP connection to S3 never completed. When it only happens in some execution environments, the usual cause is that the subnets differ. Each new environment is placed in one of the function's subnets, so if one subnet's route table is wrong, only environments in that subnet fail. Check, for every subnet attached to the function:

  • The route table has 0.0.0.0/0 → nat-.... A private subnet that was never associated with the right route table (and falls back to the VPC's main route table) often has no route out at all.
  • The function isn't attached to a public subnet. Lambda functions never get public IP addresses, so a subnet whose default route points at an Internet Gateway gives them no outbound access.
  • Network ACLs allow return traffic on ephemeral ports (1024–65535). Security groups are stateful, but NACLs aren't.

The 8–12 second delays come from the SDK: botocore's default connect timeout is 60 seconds, and it retries failed connections, so a blocked path shows up as a long hang before the error. VPC Reachability Analyzer, or a test invocation pinned to each subnet, finds the bad subnet quickly.

S3 doesn't need the NAT Gateway at all. Even with every route fixed, sending S3 traffic through a NAT Gateway costs data processing charges per GB and adds a hop. S3 is a regional service, and a VPC can reach it privately.

The Solution: AWS VPC Gateway Endpoint for S3

Fix the broken subnet route, and also add an AWS VPC Gateway Endpoint for S3. A gateway endpoint lets resources in private subnets reach S3 in the same region without a NAT Gateway or Internet Gateway. Traffic stays on the AWS network, and gateway endpoints for S3 have no hourly or per-GB charge.

When you associate the endpoint with route tables, AWS adds a route for S3's managed prefix list (pl-...) pointing at the endpoint. That route is more specific than 0.0.0.0/0, so S3 traffic takes it instead of the NAT Gateway.

Corrected Configuration (Infrastructure-as-Code Example)

No application change is needed. In CloudFormation:

YAML
Resources:
  # ... other resources like your Lambda function, subnets, etc. ...

  S3VPCEndpoint:
    Type: AWS::EC2::VPCEndpoint
    Properties:
      VpcId: !Ref YourVPC # Reference to your VPC ID
      ServiceName: !Sub 'com.amazonaws.${AWS::Region}.s3' # S3 Gateway Endpoint Service Name
      RouteTableIds: # List of Route Table IDs associated with your private subnets
        - !Ref PrivateSubnet1RouteTable
        - !Ref PrivateSubnet2RouteTable
        - !Ref PrivateSubnet3RouteTable
      VpcEndpointType: Gateway # This is crucial for S3/DynamoDB
      PolicyDocument: # Optional: Restrict S3 access via this endpoint (e.g., only to specific buckets)
        Version: '2012-10-17'
        Statement:
          - Sid: AllowEventLogBucketOnly
            Effect: Allow
            Principal: '*'
            Action:
              - s3:PutObject
              - s3:GetObject
            Resource:
              - !Sub 'arn:aws:s3:::${S3BucketName}/*'

Key Changes Explained:

  1. Type: AWS::EC2::VPCEndpoint: Declares a new VPC Endpoint.
  2. VpcId: The ID of your existing VPC where the Lambda resides.
  3. ServiceName: !Sub 'com.amazonaws.${AWS::Region}.s3': This is the specific service name for the S3 Gateway Endpoint in your region. AWS automatically provides this.
  4. RouteTableIds: This is critical. You must associate the Gateway Endpoint with the route tables of all the private subnets where your Lambda functions are deployed. This tells your private subnets to route S3 traffic through this endpoint.
  5. VpcEndpointType: Gateway: Specifies it's a Gateway Endpoint, which is suitable for S3 and DynamoDB.
  6. PolicyDocument: limits which buckets and actions can be reached through this endpoint. Without it, the endpoint allows full access to all of S3, including buckets in other accounts, which is a data exfiltration path. The function's IAM role still needs its own s3:PutObject permission. Both must allow the request.

After deployment, the same S3 hostnames resolve as before, but the route table now sends that traffic to the endpoint. The SDK doesn't need to know the endpoint exists.

Make Failures Fast in the Code

Set short timeouts and bounded retries on the S3 client, so a network problem fails in a couple of seconds instead of hanging most of the way to the function's timeout:

Python
from botocore.config import Config

s3_client = boto3.client(
    "s3",
    config=Config(connect_timeout=2, read_timeout=5, retries={"max_attempts": 3, "mode": "standard"}),
)
  1. Interface Endpoints vs. Gateway Endpoints: While S3 and DynamoDB use Gateway Endpoints (which are free and modify route tables), most other AWS services (e.g., SQS, SNS, EC2 APIs) use Interface Endpoints. Interface Endpoints are powered by AWS PrivateLink, cost money per hour and per GB of data, and require security groups and ENIs within your subnets. Ensure you select the correct type for the service you're trying to reach.
  2. Endpoint Policies: Always define an explicit endpoint policy to restrict access. A permissive policy (like AllowAllS3Access above) can create security vulnerabilities if not properly managed. Restrict access to only the necessary S3 buckets or prefixes.
  3. Same region only: a gateway endpoint covers S3 buckets in the VPC's own region. Requests to a bucket in another region still go through the NAT Gateway. Gateway endpoints work through routing, not DNS: S3 names still resolve to public addresses. (Interface endpoints for S3, by contrast, use private IPs and DNS, and are what you need for access from on-premises networks.)
  4. NAT Gateway costs: S3 traffic stops incurring NAT data processing charges. Other outbound traffic, such as third-party APIs, still needs the NAT Gateway. If the function only talks to AWS services, interface endpoints for those services can remove the NAT dependency entirely.
  5. One NAT Gateway per AZ: private subnets in every AZ should route to a NAT Gateway in their own AZ. Routing all AZs through one NAT Gateway works, but adds cross-AZ data charges and makes that AZ a single point of failure.

💡 Bonus Tip: Leverage CloudWatch Metrics for Cold Start Analysis

Every invocation writes a REPORT line to CloudWatch Logs, and cold starts include an Init Duration field: the time spent loading your code and running module-level setup (imports, creating clients). Query it with CloudWatch Logs Insights (filter @type = "REPORT" | stats avg(@initDuration), max(@duration) by bin(1h)) to separate slow initialization from slow first requests. Turning on AWS X-Ray tracing shows exactly which call (the S3 upload, the database connection) took the time.

TechLab Editorial TeamAuthorAnswered

Know the answer?

Posting answers needs a TechLab plan. Reading every discussion stays free.