RDS "Too Many Connections" with Lambda: How to Fix It
Each concurrent Lambda environment opens its own database connection, so traffic spikes exhaust the limit. RDS Proxy is the main fix.
Typical errors:
FATAL: sorry, too many clients already (PostgreSQL)
ERROR 1040 (HY000): Too many connections (MySQL)Why it happens
Lambda scales by running many copies of your function at once. Each copy (execution environment) opens its own
database connection. 300 concurrent invocations means roughly 300 connections. A small database instance may only
allow a few dozen to a few hundred, because max_connections scales with instance memory.
Fix 1: Put RDS Proxy in front of the database
RDS Proxy keeps a pool of database connections and shares them across all your invocations. Your function connects to the proxy endpoint instead of the database, with no code change beyond the hostname. It also makes failovers faster and integrates with Secrets Manager and IAM authentication.
Fix 2: Reuse connections across invocations
Open the connection outside the handler, so warm invocations reuse it:
conn = None
def get_conn():
global conn
if conn is None or conn.closed:
conn = psycopg.connect(...)
return conn
def lambda_handler(event, context):
with get_conn().cursor() as cur:
...Opening a new connection inside the handler on every call (and not closing it) is the fastest way to hit the limit.
Fix 3: Cap concurrency
Set reserved concurrency on the function (or maximum concurrency on an SQS event source) so it can never exceed what the database can handle.
Fix 4: Consider alternatives
- Aurora Serverless v2 + RDS Data API: query over HTTPS with no persistent connections.
- DynamoDB: no connection limits at all, if your access patterns fit.
Learn more: RDS best practices & Lambda tips and DynamoDB vs RDS.
Key takeaways
- Every concurrent Lambda environment holds its own connection.
- RDS Proxy pools connections and is the standard fix.
- Reuse connections outside the handler and cap concurrency.