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:
- Slow first invocations: some new execution environments take 8–12 seconds to handle their first request, against under 200 ms for warm invocations.
- Intermittent S3 timeouts: in those same environments,
put_object()takes 5–10 seconds or fails withbotocore.exceptions.ConnectTimeoutError. Other environments upload in milliseconds.
A simplified version of the function:
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:
[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?
