CodexBloom - Programming Q&A Platform

AWS Lambda Timeout Issues When Integrating with RDS: Connection Not Established in Time

๐Ÿ‘€ Views: 84 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-05
aws lambda rds postgresql Python

I'm working with a timeout scenario with my AWS Lambda function that connects to an Amazon RDS PostgreSQL database. I've configured my Lambda function with a timeout of 30 seconds, but frequently I am getting 'Task timed out after 30.00 seconds' errors when trying to execute queries. The Lambda function is triggered by an API Gateway request and should return the results of a SELECT query from the database. Iโ€™ve ensured that my Lambda function has the necessary VPC configurations and security group rules that allow outbound traffic to the RDS instance. The RDS instance is in the same VPC with proper subnet configurations. Hereโ€™s the relevant part of my Lambda code: ```python import json import psycopg2 def lambda_handler(event, context): db_host = 'my-rds-instance.abcdefg12345.us-west-2.rds.amazonaws.com' db_name = 'mydb' db_user = 'myuser' db_password = 'mypassword' try: connection = psycopg2.connect( host=db_host, database=db_name, user=db_user, password=db_password ) cursor = connection.cursor() cursor.execute('SELECT * FROM my_table') rows = cursor.fetchall() return { 'statusCode': 200, 'body': json.dumps(rows) } except Exception as e: return { 'statusCode': 500, 'body': str(e) } finally: if connection: cursor.close() connection.close() ``` I've tried increasing the timeout to 60 seconds, but the scenario continues. I also checked the RDS performance insights and it seems like the queries are actually executing quickly, so it doesnโ€™t appear to be a database performance scenario. Moreover, the VPC settings look correct, with the appropriate NAT Gateway configured for outbound internet access. One thing to note is that the Lambda function successfully connects and fetches data in some cases, but it fails intermittently, especially under load. Has anyone experienced similar issues, or can anyone suggest debugging steps or configuration checks? Any help would be appreciated!