Sub topic 14
Pooling connections with RDS Proxy
This chapter assumes you can provision an RDS instance, that you know how security groups control traffic between resources in a VPC, and that you have used the AWS CLI. It also assumes you know what a database connection costs. For PostgreSQL, each connection is a server process that uses memory, and each engine has a max_connections limit tied to the instance class.
The problem a proxy solves
Applications that open many short-lived connections can exhaust a database. Typical cases are AWS Lambda functions, which each open their own connection, and autoscaled web fleets. Each new connection costs a TCP handshake, a TLS negotiation, authentication, and server memory. Once max_connections is reached, new clients get errors such as too many connections, even when the CPU is idle.
Amazon RDS Proxy is a managed service that sits between your application and the database. Clients connect to the proxy endpoint. The proxy keeps a pool of long-lived connections to the database and shares them among clients. RDS Proxy supports RDS for MySQL, MariaDB, PostgreSQL, and SQL Server, and Aurora MySQL and PostgreSQL. Check the current documentation for supported engine versions.
It gives you three things:
- Connection reuse. Many client connections are multiplexed onto fewer database connections.
- Faster failover. During a Multi-AZ failover, the proxy keeps client connections open and reconnects to the new primary. Applications see a pause instead of a dropped connection.
- Central credentials. The proxy reads database credentials from Secrets Manager, and clients can authenticate to the proxy with IAM.
How multiplexing works
When a client sends a transaction, the proxy borrows a database connection from the pool. When the transaction ends, the connection returns to the pool and another client can use it. This lets thousands of mostly idle client connections share a few dozen database connections.
Session pinning
Multiplexing only works if the database connection carries no client-specific state between transactions. When a client changes session state, the proxy must pin the client to one database connection until the client disconnects. Pinned connections are not shared, so heavy pinning removes the benefit of the proxy.
Common causes of pinning depend on the engine and change between versions. Examples are:
SETstatements that change session variables.- Temporary tables.
- Advisory locks, or locks taken with functions such as
GET_LOCK. - Some uses of prepared statements. In PostgreSQL, protocol-level prepared statements can pin a connection.
- Text values larger than the proxy's internal buffer in some MySQL cases.
Watch the DatabaseConnectionsCurrentlySessionPinned CloudWatch metric. If it stays close to the number of borrowed connections, the proxy is acting as a pass-through. Fixes include moving SET statements into the database role or parameter group, avoiding temporary tables on hot paths, and using the proxy's session pinning filters where the engine supports them. The EXCLUDE_VARIABLE_SETS filter tells the proxy to ignore variable settings when deciding to pin. Use it only if you are sure your session variables do not affect query results, because the proxy cannot tell that for you.
Creating a proxy
Setting up a proxy involves four resources: a secret with the database credentials, an IAM role the proxy can assume, the proxy itself, and the target registration that links the proxy to your instance.
Credentials and role
Create a dedicated application user in the database, store its credentials in a Secrets Manager secret, and give the proxy a role that can read it. The secret is a JSON document:
{
"username": "app_user",
"password": "replace-with-a-strong-password"
}Use an application user rather than the master user managed by --manage-master-user-password. That keeps the proxy's access limited to what the application needs. The proxy's IAM role needs a trust policy for rds.amazonaws.com and permission to call secretsmanager:GetSecretValue on the secret. It also needs kms:Decrypt if the secret uses a customer managed KMS key.
Proxy and target
aws rds create-db-proxy \
--db-proxy-name demo-pg-proxy \
--engine-family POSTGRESQL \
--auth '[{"AuthScheme":"SECRETS","SecretArn":"arn:aws:secretsmanager:us-east-1:111122223333:secret:demo-app-user-AbCdEf","IAMAuth":"REQUIRED"}]' \
--role-arn arn:aws:iam::111122223333:role/demo-pg-proxy-role \
--vpc-subnet-ids subnet-0123456789abcdef0 subnet-0fedcba9876543210 \
--vpc-security-group-ids sg-0aaaaaaaaaaaaaaa1 \
--require-tls
aws rds register-db-proxy-targets \
--db-proxy-name demo-pg-proxy \
--db-instance-identifiers demo-pgThe subnets must be in the same VPC as the database. The proxy is reachable only from inside the VPC, or from networks connected to it, and it cannot be made public. Setting IAMAuth to REQUIRED means clients must present an IAM authentication token instead of a password. Use DISABLED if clients should send the database password.
Security group rules
Two rules must be in place, and a missing one is the most common reason a new proxy appears to hang:
- The proxy's security group allows inbound traffic from your clients on the database port.
- The database's security group allows inbound traffic from the proxy's security group on the database port.
Reference security groups by ID instead of using CIDR ranges, so the rules keep working if addresses change.
Tuning the pool
The target group holds the pool settings. A new proxy uses a target group named default.
aws rds modify-db-proxy-target-group \
--db-proxy-name demo-pg-proxy \
--target-group-name default \
--connection-pool-config MaxConnectionsPercent=80,MaxIdleConnectionsPercent=40,ConnectionBorrowTimeout=30| Setting | Meaning | Guidance |
|---|---|---|
| `MaxConnectionsPercent` | Share of the database's `max_connections` that the proxy may use | Leave headroom for admin tools, replication, and other direct clients |
| `MaxIdleConnectionsPercent` | How many idle connections the proxy keeps open | Lower values free database memory. Higher values absorb bursts faster |
| `ConnectionBorrowTimeout` | Seconds a client waits for a free database connection | The default is 120. A shorter value makes overload fail fast |
If you set MaxConnectionsPercent to 100, direct administrative connections can be locked out. Because the percentage is computed from the database's max_connections, changing that parameter in a parameter group also changes the pool ceiling.
Connecting through the proxy
With IAM authentication, the client generates a short-lived token and uses it as the password. The token is valid for 15 minutes, but it only matters when a connection is established. Connections that are already open stay open.
import boto3
import psycopg2
region = "us-east-1"
proxy_host = "demo-pg-proxy.proxy-example.us-east-1.rds.amazonaws.com"
rds = boto3.client("rds", region_name=region)
token = rds.generate_db_auth_token(
DBHostname=proxy_host, Port=5432, DBUsername="app_user", Region=region
)
conn = psycopg2.connect(
host=proxy_host,
port=5432,
dbname="postgres",
user="app_user",
password=token,
sslmode="verify-full",
sslrootcert="AmazonRootCA1.pem",
)
with conn, conn.cursor() as cur:
cur.execute("SELECT 1")
print(cur.fetchone())The proxy presents a certificate issued by Amazon Trust Services, so you verify it with the Amazon root certificate (or your operating system's trust store), not the RDS CA bundle you use for direct connections. The hostname above is a placeholder for your proxy endpoint.
When a proxy helps and when it does not
| Situation | Proxy helps? | Reason |
|---|---|---|
| Lambda functions with bursts of concurrency | Yes | Each invocation would otherwise open its own connection |
| Frequent Multi-AZ failovers or planned failover tests | Yes | Client connections survive the switch |
| One long-lived app with a client-side pool already tuned | Little | Pooling already exists, and the proxy adds a network hop |
| Sessions that set variables or use temporary tables on every request | Limited | Pinning removes multiplexing |
| Latency-critical queries measured in sub-millisecond steps | Possibly not | The proxy adds a small amount of latency per query |
A proxy does not replace read replicas, and it does not fix slow queries. For Aurora, you can also create a read-only proxy endpoint that routes to the reader instances.
Cost and cleanup
RDS Proxy is billed per vCPU-hour of the target database instance, so it adds a continuous charge for as long as it exists. Check the RDS Proxy pricing page for current rates. When you finish a test, delete the proxy before the instance:
aws rds delete-db-proxy --db-proxy-name demo-pg-proxyAlso delete the Secrets Manager secret and the IAM role if you created them only for the test.
Exercise
A Lambda-based API sits behind an RDS Proxy. Latency is fine, but CloudWatch shows DatabaseConnectionsCurrentlySessionPinned almost equal to the number of borrowed database connections, and the database still hits its connection limit at peak. What is the likely cause, and what two actions would you take?
Show answer
Nearly every client connection is pinned, so the proxy cannot multiplex and behaves like a pass-through. The likely cause is session state set on each connection, such as SET statements, temporary tables, or prepared statements that pin the session. First, find and remove the state-changing statements, for example by moving settings to the database role or parameter group. Second, if the session variables do not affect results, add the EXCLUDEVARIABLESETS session pinning filter to the target group, and lower MaxConnectionsPercent so the proxy cannot consume every connection slot.