Testing PostgreSQL connection exhaustion and admin access

Testing PostgreSQL connection exhaustion and admin access

Testing PostgreSQL connection exhaustion and admin access

The application reports “too many connections,” yet the database process is still running. Retries then leave even more requests backed up at the entrance. The first question is not how much free memory the dedicated server has, but whether ordinary connection slots are exhausted, whether an administrative entry point remains available, and which sessions can be safely terminated. This article reproduces that sequence in an isolated test instance on Debian 13, without changing production database settings or exposing a public network listener.

1. Define the connection budget and acceptance criteria

max_connections sets the maximum number of connections; it is not a recommended concurrency level. Even an idle connection occupies a slot. Additional application replicas, background jobs, and connection pools all increase total connection demand. Build the budget by adding up “instance count × per-instance pool limit” for each component, then allow for batch jobs, monitoring, and administrative access. Looking at a single service’s configuration is not enough.

superuser_reserved_connections reserves connection slots for superusers. This test uses a total limit of 20, reserves 3 slots for superusers, and sets the additional role-based reserve to 0, leaving 17 slots available to ordinary connections. These numbers keep the exercise small; they are not production configuration recommendations.

Reserved connections preserve some diagnostic access, but they do not replace application-side connection pool limits. Do not give business applications superuser credentials, or they may exhaust the administrative entry point as well.

There are three acceptance criteria: an ordinary account is rejected once it reaches the limit; an administrative account can still inspect sessions; and the ordinary account can reconnect after the test connections are released. A single error message does not prove that the full recovery sequence works.

2. Create an isolated instance accessible only locally

Install the PostgreSQL server and client tools provided by the distribution. Run the following commands in the same Bash session, using a dedicated, non-root local test account. That account should not own any production data directory. pg_config must resolve to the server tools directory for this installation; first verify that the version and path match.

set -euo pipefail
PGBIN="$(pg_config --bindir)"
test -x "$PGBIN/initdb"
test -x "$PGBIN/pg_ctl"

LAB="$(mktemp -d /tmp/pg-slots.XXXXXX)"
chmod 700 "$LAB"
mkdir "$LAB/socket"

"$PGBIN/initdb" -D "$LAB/data" -U lab_admin \
  --auth-local=trust --auth-host=reject >/dev/null

cat >>"$LAB/data/postgresql.conf" <<EOF
listen_addresses = ''
unix_socket_directories = '$LAB/socket'
unix_socket_permissions = 0700
max_connections = 20
superuser_reserved_connections = 3
reserved_connections = 0
EOF

"$PGBIN/pg_ctl" -D "$LAB/data" \
  -l "$LAB/server.log" -w start

export PGHOST="$LAB/socket"
export PGDATABASE=postgres
export PGCONNECT_TIMEOUT=5
export PGAPPNAME=slots-lab

"$PGBIN/psql" -X -U lab_admin -v ON_ERROR_STOP=1 \
  -c "CREATE ROLE lab_client LOGIN CONNECTION LIMIT -1;"
"$PGBIN/psql" -X -U lab_admin -v ON_ERROR_STOP=1 \
  -c "CREATE DATABASE slots_lab OWNER lab_client;"
export PGDATABASE=slots_lab

The trust method is used only for this isolated experiment: the socket path is protected by private directory permissions, and the instance does not listen on TCP. It does not verify the identity of individual processes running under the same local account, so do not move it into a shared directory or use it as a production authentication configuration.

If startup fails, read $LAB/server.log first. Do not delete lock files belonging to a production instance. If reserved_connections is reported as unrecognized, the tool version does not match this article’s environment. Stop and check the installation rather than blindly removing the parameter and continuing.

3. Fill the ordinary slots and verify administrative access

First query the effective settings, then start 17 ordinary connections. Each connection only waits; it does not read or write application data. The 90-second interval holds slots for the experiment and is not a recommended service timeout.

"$PGBIN/psql" -X -U lab_admin -c "
SELECT name, setting
FROM pg_settings
WHERE name IN (
  'max_connections',
  'superuser_reserved_connections',
  'reserved_connections'
)
ORDER BY name;"

pids=()
for i in $(seq 1 17); do
  "$PGBIN/psql" -X -U lab_client -v ON_ERROR_STOP=1 \
    -c "SELECT pg_sleep(90);" >"$LAB/client-$i.log" 2>&1 &
  pids+=("$!")
done

count=0
for attempt in $(seq 1 50); do
  count="$("$PGBIN/psql" -X -U lab_admin -Atc "
    SELECT count(*) FROM pg_stat_activity
    WHERE datname = 'slots_lab'
      AND usename = 'lab_client'
      AND backend_type = 'client backend';")"
  [ "$count" = 17 ] && break
  sleep 0.1
done
test "$count" = 17

if "$PGBIN/psql" -X -U lab_client -v ON_ERROR_STOP=1 \
  -c "SELECT 1;" >"$LAB/rejected.log" 2>&1; then
  printf '%s\n' 'Unexpected connection success' >&2
  exit 1
fi

"$PGBIN/psql" -X -U lab_admin -v ON_ERROR_STOP=1 -c "
SELECT usename, state, wait_event_type, wait_event, count(*)
FROM pg_stat_activity
WHERE datname = 'slots_lab'
GROUP BY usename, state, wait_event_type, wait_event
ORDER BY usename, state;"

Inspect rejected.log. The expected result is a rejection related to reserved connection slots, not an authentication failure, an incorrect path, or a nonexistent database. The administrative query must succeed to establish that this test actually verified the reserved entry point.

Sessions running pg_sleep generally appear as active, with a wait event. This does not mean they are continuously consuming CPU. Production troubleshooting should likewise consider session state, transaction start time, and wait events together. Do not terminate a session simply because it is active.

4. Release targeted connections and verify recovery

This experiment terminates only client sessions for the specified database and test role. It does not broadly evict “all idle connections.” Continue in the same Bash session used in the previous section:

"$PGBIN/psql" -X -U lab_admin -v ON_ERROR_STOP=1 -c "
SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE datname = 'slots_lab'
  AND usename = 'lab_client'
  AND backend_type = 'client backend'
  AND pid <> pg_backend_pid();"

for pid in "${pids[@]}"; do
  wait "$pid" || true
done

"$PGBIN/psql" -X -U lab_client -v ON_ERROR_STOP=1 \
  -c "SELECT current_user, current_database(), 1 AS recovered;"

"$PGBIN/pg_ctl" -D "$LAB/data" -m fast -w stop

Terminated clients may return a nonzero exit status, so failures are tolerated only for these known test processes. The new connection used for acceptance testing must still exit successfully. A successful return from the termination function does not prove that the application has recovered; open a separate ordinary connection and run a query.

Production sessions may hold uncommitted transactions. Forced termination rolls those transactions back and may trigger application retries. First limit incoming requests or pause the problematic job, identify which application or task owns the sessions, and then decide whether to cancel the query or terminate the connection. Do not copy the experiment’s bulk termination criteria into production.

5. Turn the test results into connection management rules

Keep four kinds of evidence: the settings query, the rejection log, the session count, and the recovery query. Record the order in which the steps were run. Testing rejection after the slot-holding sessions have finished normally can lead to the false conclusion that “connections are still being accepted.” Confirm that all 17 sessions are still occupying their slots when the rejection test runs.

On the application side, check the paths that return connections to the pool, exception-handling branches, and the maximum wait for a pooled connection. If too many pooled connections remain idle for long periods, adjust pool capacity. If slow transactions occupy all connections, address transaction duration. If the connection count keeps rising without falling, investigate leaks first rather than immediately raising the database limit.

Before scaling out, also check the sum of the pool limits across all replicas. Adding memory to the dedicated server does not automatically fix connection leaks, and raising max_connections does not give additional concurrently executing queries computational resources for free.

After stopping the test instance, copy the evidence you need to a controlled directory. Then manually verify the $LAB path before removing the experiment’s files. The final deliverable is not a higher connection setting, but a repeatably verified boundary: administrators can still connect when ordinary requests are limited, and connections recover after the problematic sessions are released.

Frequently asked questions

Does increasing max_connections fix connection exhaustion?

Not by itself. Count connections across application replicas, background jobs, and pools first, then investigate leaks and long-held sessions. Assess any higher limit against memory and concurrent execution capacity.

Should applications use reserved admin connections?

No. Applications should use ordinary roles, while admin reserves remain available for diagnosis and recovery. Explicitly test that controlled administrative access still works when ordinary slots are exhausted.

AMD EPYC 7543P dedicated server,from $445.3/month

Turn workload plans into a server configuration

Choose 128 GB or 256 GB of DDR4-3200 ECC RDIMM with the AMD EPYC 7543P. Check the configuration page for available options.