RDS Proxy normally lends a backend for one transaction, but some statements make it reserve, or pin, that backend to the client until the client disconnects. This guide shows how to measure pinning in CloudWatch, find the statement that causes it, and verify the fix.

If database connections jump after a deploy while query execution times stay flat, check whether RDS Proxy can still reuse its backends. A client normally borrows a backend for a transaction. When the proxy detects session state that must persist, it reserves that backend for the client until the client disconnects. An idle application connection can then occupy a database connection, even after COMMIT.

Measure pinned connections and borrow pressure

In CloudWatch, open Metrics → RDS → Per-Proxy Metrics. Choose the same ProxyName dimension for every series in the table and use a 60-second period. Use Sum for the counts in each minute because AWS publishes values from the underlying proxy instances. Use Average for borrow latency, which AWS reports in microseconds. Plot matching windows before and after the deployment, with comparable client traffic. AWS metric definitions and dimensions.

Keep the period at 60 seconds when using Sum. Each proxy instance reports these gauges once a minute. A longer period adds minutes together and inflates the value.

Use the application's own request rate or DatabaseConnectionsBorrowRequests to compare traffic across windows. AWS notes that QueryRequests excludes PostgreSQL extended-query-protocol traffic, which is how most drivers send queries. AWS RDS Proxy metric definitions.

MetricStatisticWhat it tells you
DatabaseConnectionsCurrentlySessionPinnedSumBackends reserved because a client changed session state. This is a gauge, so a sustained value of 40 means roughly 40 occupied backends per sample, rather than 40 new pin events per minute.
DatabaseConnectionsSumBackend connections held by the proxy, including connections being set up. Use it as the denominator for the pinned share.
DatabaseConnectionsCurrentlyBorrowedSumBackends assigned to clients. Compare it with pinned and in-transaction counts on the same timeline.
DatabaseConnectionsCurrentlyInTransactionSumBackends in open transactions. A sustained rise here calls for a transaction-lifetime check.
MaxDatabaseConnectionsAllowedSumBackend capacity the proxy can use for workload traffic. Compare it with borrowed connections as a sign of diminishing headroom.
DatabaseConnectionsBorrowLatencyAverageTime to obtain a backend. Rising latency alongside pinning and shrinking headroom makes the pinning operationally significant.

In metric math, use 100 * pinned / backends, with matching dimensions and timestamps. Interpret the result only when both metrics have a sample and backends is positive. Check the raw pinned series before treating gaps as zero. For Aurora writer and reader separation, open the proxy's monitoring dashboard and use its per-role pinned percentage. Its role widgets have their own dimensions and aggregation. AWS proxy dashboard reference.

The pinned, total, borrowed, and in-transaction metrics also use the dimension set ProxyName, TargetGroup, and TargetRole. The CLI loop can split these counts by role. DatabaseConnectionsBorrowLatency has no per-role dimension. AWS metric dimensions.

To pull the pinned, total, borrowed, and in-transaction counts without changing proxy settings, set the name, region, and UTC bounds to your incident window. Repeat the same query for a baseline window.

proxy=my-proxy
region=us-east-1
start=2026-12-04T14:00:00Z
end=2026-12-04T14:30:00Z

for metric in DatabaseConnectionsCurrentlySessionPinned DatabaseConnections \
  DatabaseConnectionsCurrentlyBorrowed DatabaseConnectionsCurrentlyInTransaction
do
  printf '\n%s\n' "$metric"
  aws cloudwatch get-metric-statistics \
    --region "$region" --namespace AWS/RDS --metric-name "$metric" \
    --dimensions "Name=ProxyName,Value=$proxy" \
    --start-time "$start" --end-time "$end" \
    --period 60 --statistics Sum \
    --query 'sort_by(Datapoints, &Timestamp)[].[Timestamp, Sum]' --output table
done

To split by role, replace the --dimensions line with:

--dimensions "Name=ProxyName,Value=$proxy" "Name=TargetGroup,Value=default" "Name=TargetRole,Value=READ_WRITE" \

Use READ_ONLY for reader traffic. default is the proxy's default target group name.

Tell pinning apart from other pool pressure

  • Pinned tracks borrowed while open transactions stay low. Look for session state introduced by a driver, ORM, or connection initialization hook. A fast query can still leave its backend reserved between requests.
  • In-transaction tracks borrowed while pinned stays low. Check for idle in transaction and long transactions. End the transaction before waiting on remote calls or other application work.
  • Open backends stay high while pinned and borrowed stay low. Check the idle pool and fragmentation by database, user, or startup application_name. A different application name per worker can fragment the pool even when pinning is low.

These patterns can overlap. Add the application’s connection acquisition latency and request rate before changing pool limits. AWS examples of pinning, fragmentation, and open transactions.

In CloudWatch Logs Insights, select /aws/rds/proxy/<proxy-name> for the same time window. Start with standard pinning warnings. Inspect the reason and SQL digest, and match their first appearance to a deploy or connection-startup path. This query counts log events, while the CloudWatch gauge measures backends still reserved at each sample.

fields @timestamp, @logStream, @message
| filter @message like /was pinned to the database connection/
| sort @timestamp desc
| limit 50

AWS describes proxy logs as a troubleshooting aid for people and says their format can change, so recheck the filter text if the query stops matching. AWS proxy log format guidance.

Use enhanced logging briefly if you need to correlate borrow, release, and pin events for an individual backend. Restrict access and retention first because enhanced logs may contain SQL text. RDS Proxy turns enhanced logging off after 24 hours. It adds CloudWatch Logs charges, so turn it off as soon as the investigation is done. AWS connection-level log analysis.

Isolate the statement that pins the session

Use an isolated staging proxy and connect directly to its endpoint with psql -X so a local startup file cannot issue extra commands. Take a SELECT 1 baseline, then open a fresh client for each case. After running a case, leave the client connected at the prompt for at least two complete CloudWatch sampling intervals and close it before starting the next case. Check the pinning warning and the gauge before, during, and after. The expected differences below come from AWS documentation and should be checked against the application’s actual driver and configuration.

Session SET versus SET LOCAL

-- Client A. Leave connected after this statement.
SET statement_timeout = '5s';

-- Client B. Leave connected after COMMIT.
BEGIN;
SET LOCAL statement_timeout = '5s';
SELECT 1;
COMMIT;

The first setting persists across transactions. The second is scoped to the explicit transaction, and AWS documents an exemption for SET LOCAL inside it. Check what the driver actually sends. AWS lists set_config('statement_timeout', '5s', true) as a pinning case despite its local PostgreSQL scope. If every backend needs the same default, consider the proxy target group's initialization query, which runs on new backend connections. MySQL proxies support a session pinning filter for SET statements. PostgreSQL proxies require you to address these statements in the application, driver settings, or proxy initialization query. AWS session pinning filter guidance. Keep per-request state inside the transaction and validate boundaries before moving a setting. RDS for PostgreSQL pinning rules and Aurora PostgreSQL pinning rules.

Common driver and framework sources

SourceWhat it sendsEffect
PostgreSQL JDBC driver 42.2.x and olderSET extra_float_digits and SET application_name after connecting.Pins every connection before the first query. In 42.7.x and newer, these settings go in the startup packet, which the proxy treats as connection negotiation.
Spark DataFrame JDBC writerSET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL READ UNCOMMITTED before each write, from its default isolationLevel.Pins the session.
psycopg2 and psycopg 3No SET statements on their own.For this trigger, pinning occurs only if application code issues SET.

Connection pools configured with DISCARD ALL as the reset query pin the client connection on release. AWS examples of driver and framework pinning and PostgreSQL pinning rules.

SQL PREPARE versus protocol-level preparation

-- A fresh client running SQL commands.
PREPARE pin_probe(integer) AS SELECT $1 + 1;
EXECUTE pin_probe(41);

These are SQL commands, which AWS lists as pinning triggers. Driver-level prepared statements sent through PostgreSQL’s extended query protocol use messages such as Parse and Bind. RDS Proxy can track those statements and recreate them on a newly borrowed backend. Test the driver’s normal code path in a separate client. Looking at pg_prepared_statements through that proxy session can itself trigger a pin. Check startup and connection-release hooks too, especially DISCARD ALL, before changing preparation settings. AWS extended query protocol support.

Session advisory locks versus transaction advisory locks

-- Client A. Use a key reserved for this staging test.
SELECT pg_try_advisory_lock(721021::bigint);
-- Keep this client connected during the sample window, then clean up.
SELECT pg_advisory_unlock(721021::bigint);

-- Client B. Run after client A is disconnected.
BEGIN;
SELECT pg_try_advisory_xact_lock(721021::bigint);
-- Continue only if the result is true.
SELECT 1;
COMMIT;

A session lock can outlive COMMIT. The proxy can pin when it sees the session-level function, and releasing the lock does not end the pinned client session. The transaction-level variant is exempt from pinning and releases at transaction end. Both try forms return false if the key is already held by another session. Preserve session locks for work that must remain protected across commits. Run schedulers, migrations, or leader election that need these locks on a direct database connection so they leave the proxy's pooled backends available.

While a lock is held, run this read-only query from a separate database monitoring connection to identify advisory lock holders or waiters. It observes PostgreSQL lock state, so correlate with the proxy logs and pinned gauge to attribute a pin.

SELECT a.pid, a.application_name, a.state,
       age(clock_timestamp(), a.xact_start) AS xact_age,
       l.mode, l.granted, l.classid, l.objid, l.objsubid,
       CASE WHEN l.objsubid = 1 THEN (l.classid::bigint << 32) | l.objid::bigint END AS advisory_key,
       CASE WHEN l.objsubid = 2 THEN format('(%s, %s)', l.classid::int, l.objid::int) END AS advisory_key_pair
FROM pg_locks AS l
JOIN pg_stat_activity AS a USING (pid)
WHERE l.locktype = 'advisory'
  AND a.datname = current_database()
  AND a.backend_type = 'client backend'
ORDER BY l.granted, a.xact_start NULLS LAST, a.pid;

advisory_key shows a single bigint key, such as 721021, while advisory_key_pair shows locks taken with two integer keys. The decoding was tested on PostgreSQL 16 with positive, negative, large, and two-integer keys.

PostgreSQL advisory lock semantics.

Other statements that pin

Beyond the three cases above, AWS lists these PostgreSQL triggers:

  • Any statement whose text is larger than 16 KB. This applies to every engine. Large ORM-generated IN (...) lists can hit this without any SET.
  • nextval() and setval() on sequences. Test the application's normal insert path, including identity or serial defaults, in the same staging harness.
  • Creating temporary tables, sequences, or views.
  • Declaring cursors.
  • LISTEN on a notification channel.
  • Loading a library module such as auto_explain.

AWS PostgreSQL pinning triggers.

Validate the change at comparable load

Canary one change at a time and allow the old application pool connections to drain. Compare pinned share, borrowed backends against available capacity, and borrow latency after the churn settles. Hold traffic and concurrency roughly constant. Check application behavior too, including timeouts, transaction outcomes, and any locks or settings the code relied on. A lower pinned count caused by fewer connected clients does not establish better reuse.

Quick reference: cause and fix

CauseFix
Session SET for timeouts, search_path, or other settings.Use SET LOCAL inside an explicit transaction, or use the proxy initialization query for defaults every connection needs. set_config(..., true) still pins.
SQL PREPARE, EXECUTE, or DEALLOCATE.Use the driver's protocol-level prepared statements (Parse/Bind).
DISCARD ALL as the pool reset query.Remove it from the pool's release or reset hook.
PostgreSQL JDBC driver 42.2.x or older.Upgrade to 42.7.x or newer.
Spark JDBC writer isolation SET.Review the writer's isolationLevel setting.
Session advisory locks.Use pg_try_advisory_xact_lock, or run lock-holding jobs on a direct connection.
Statements over 16 KB.Batch or parameterize large IN lists.
Long transactions or sessions idle in transaction.End the transaction before remote calls or other application work.
Pool fragmentation from per-worker application_name.Use one application_name per service.

If borrow latency stays high after pinning falls, WalStack’s AWS RDS and Aurora PostgreSQL performance review can compare the proxy metrics with application pool behavior and database waits.