DEV Community

Fixing Lambda to Aurora PostgreSQL Connection Timeout Issues in AWS

Fixing Lambda to Aurora PostgreSQL Connection Timeout Issues in AWS

"errorMessage": "connection to server at \"my-aurora-database.cluster-xxxxx.region.rds.amazonaws.com\" (10.0.0.1), port 5432 failed: timeout expired"
Enter fullscreen mode Exit fullscreen mode

If you've encountered the dreaded "connection timeout" error when trying to connect your AWS Lambda function to Aurora PostgreSQL, you're not alone.
This post will guide you through the common causes and solutions to this frustrating issue.

The Error

{
  "cause": {
    "errorMessage": "connection to server failed: timeout expired",
    "errorType": "OperationalError"
  }
}
Enter fullscreen mode Exit fullscreen mode

Common Causes

  1. VPC Configuration Issues: Lambda can't reach Aurora
  2. Security Group Misconfigurations: Missing or incorrect inbound/outbound rules
  3. Missing VPC Endpoints: Required for proper AWS service communication
  4. Network ACL Issues: Blocking necessary traffic

Step-by-Step Solution

1. VPC Setup

First, ensure your VPC is properly configured with CDK:

const vpc = new ec2.Vpc(this, 'MyVPC', {
  maxAzs: 2,
  natGateways: 1,
  subnetConfiguration: [
    {
      cidrMask: 24,
      name: 'Private',
      subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS,
    },
    {
      cidrMask: 24,
      name: 'Public',
      subnetType: ec2.SubnetType.PUBLIC,
    }
  ]
});
Enter fullscreen mode Exit fullscreen mode

2. Add Required VPC Endpoints

// Add necessary VPC endpoints
vpc.addInterfaceEndpoint('SecretsManagerEndpoint', {
  service: ec2.InterfaceVpcEndpointAwsService.SECRETS_MANAGER
});

vpc.addInterfaceEndpoint('RDSEndpoint', {
  service: ec2.InterfaceVpcEndpointAwsService.RDS
});

vpc.addGatewayEndpoint('S3Endpoint', {
  service: ec2.GatewayVpcEndpointAwsService.S3
});
Enter fullscreen mode Exit fullscreen mode

3. Configure Security Groups

// Lambda security group
const lambdaSG = new ec2.SecurityGroup(this, 'LambdaSG', {
  vpc,
  description: 'Security group for Lambda functions'
});

// Aurora security group
const auroraSG = new ec2.SecurityGroup(this, 'AuroraSG', {
  vpc,
  description: 'Security group for Aurora'
});

// Allow Lambda to connect to Aurora
auroraSG.addIngressRule(
  lambdaSG,
  ec2.Port.tcp(5432),
  'Allow PostgreSQL access from Lambda'
);
Enter fullscreen mode Exit fullscreen mode

4. Lambda Function Configuration

const lambda = new lambda.Function(this, 'MyFunction', {
  runtime: lambda.Runtime.PYTHON_3_9,
  handler: 'index.handler',
  code: lambda.Code.fromAsset('lambda'),
  vpc: vpc,
  vpcSubnets: {
    subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS
  },
  securityGroups: [lambdaSG],
  timeout: Duration.seconds(30)  // Increase from default 3 seconds
});
Enter fullscreen mode Exit fullscreen mode

5. Database Connection Code

Implement proper connection handling in your Lambda:

import psycopg2
from psycopg2 import OperationalError

def get_db_connection():
    try:
        conn = psycopg2.connect(
            host="your-aurora-endpoint",
            database="your-database",
            user="your-username",
            password="your-password",
            connect_timeout=5,
            keepalives=1,
            keepalives_idle=30,
            keepalives_interval=10,
            keepalives_count=5
        )
        return conn
    except OperationalError as e:
        print(f"Connection error: {e}")
        raise
Enter fullscreen mode Exit fullscreen mode

Troubleshooting Checklist

  • [ ] Verify Lambda and Aurora are in the same VPC
  • [ ] Check security group inbound/outbound rules
  • [ ] Confirm VPC endpoints are properly configured
  • [ ] Validate subnet configurations
  • [ ] Review Network ACL settings
  • [ ] Check Aurora instance status and capacity
  • [ ] Verify database credentials

Conclusion

Connection timeout issues between Lambda and Aurora typically stem from networking misconfigurations. By following this systematic approach to VPC setup, security groups, and connection handling, you can establish reliable connectivity between your Lambda functions and Aurora PostgreSQL database.
With these implementations, your Lambda functions should successfully connect to Aurora PostgreSQL without timeout issues.

Additional Resources

Top comments (0)