worqcloud
← Back to the journal

The app scaled. The database stopped accepting connections.

The app scaled. The database stopped accepting connections.

An illustrative checkout incident shows how per-worker pools multiply during scale-out, how to investigate the queue, and how to test a bounded connection plan.

App scaled. Database full? Connection limits. Application towers send connections toward occupied ports in a shared database.
More application capacity can exhaust shared connection slots; the limit here is connections, not database storage. View full size ↗

The application grew; the dependency did not

A checkout API adds replicas during a promotion. The new instances become ready, application CPU looks comfortable, and the autoscaling chart suggests the platform has responded correctly. Yet customers see slower requests and database connection errors. Adding application capacity has increased pressure on the dependency every replica shares.

This is an illustrative case study, not a customer incident. The service, observations, connection counts, and investigation sequence are constructed to explain a real failure mode. There are no measured latency improvements or claimed savings. The application uses Node.js workers, node-postgres pools, and a PostgreSQL database; the proxy discussion uses Amazon RDS Proxy as a documented example.

The reader problem is specific: how do you investigate connection pressure when scale-out appears to make a service less reliable? The answer is not automatically a larger database, a smaller pool, or a proxy. First distinguish exhausted connection slots, a local pool queue, and slow database work. Each produces a different corrective action.

Set the scene before interpreting the graph

The fictional service normally runs three application replicas, each with two Node.js worker processes. Each worker creates one pool with a maximum of ten connections. During the promotion, the replica count reaches twelve. The database is configured with a 200-connection ceiling for this exercise, and other applications can use another twenty connections.

Those values are assumptions, not recommended production settings. Pool limits are per process, not automatically shared across the deployment. Actual pools may open connections only as work requires them. The node-postgres Pool API documents lazy connection creation, so multiplying the limits describes potential exposure rather than proving that every slot is occupied.

The team also wants to preserve thirty connections of operational headroom. That planning reserve is separate from PostgreSQL’s configured reserved-slot mechanisms. Identify real management access rules for your deployment rather than assuming this arithmetic reserves privileged access in the server.

Case fixture · connection exposure
Normal: 3 replicas × 2 workers × pool max 10 = 60
Burst: 12 replicas × 2 workers × pool max 10 = 240
Other workloads: up to 20 connections
Database ceiling in this scenario: 200
Planning reserve: 30
Burst exposure: 240 + 20 = 260

Illustrative upper bounds, not captured monitoring data. One pool per worker is assumed; separate jobs, migrations, sidecars and overlapping deployments must be counted too.

Reconstruct the failure in order

The case begins with rising traffic, followed by application scale-out. Connection acquisition starts taking longer, then some attempts fail. This ordering makes connection demand a plausible suspect; it does not establish the cause on its own. The team keeps the timeline together instead of treating the autoscaler and database as unrelated dashboards.

For each affected request, separate time spent waiting to borrow a local pool client, establishing a database connection, executing a query, and waiting elsewhere. A request can time out while the database has free slots if the local pool is exhausted by long-running work. It can also fail because the server refuses a new connection even when another worker’s pool has idle clients.

Inspect what changed besides replica count: deployment overlap, worker count, pool settings, a new background job, slower queries, or connection leaks. A coincident scale event can reveal an existing defect. Correlating the exact error, request stage, and configuration revision is more useful than assuming the largest chart change is the root cause.

A diagnostic ladder separates local pool waiting, server connection admission, and query execution.
An editorial investigation sequence. The stages are different failure boundaries, not measured timings. View full size ↗

Collect evidence at both ends of the connection

At the application, capture pool totals, idle clients, waiting requests, acquisition failures, and request duration. The node-postgres API exposes totalCount, idleCount, and waitingCount. Keep the labels scoped to process and replica so aggregation does not hide one saturated worker behind several quiet workers.

At the database, compare connection use with the configured ceiling and inspect active sessions, idle sessions, long transactions, and relevant waits. Use the database’s authorized monitoring views and provider metrics; record the observation time and deployment state. A high session count is a starting point, not proof that all sessions are doing useful work.

The team should be able to answer two questions with evidence: are connections being refused or are clients waiting locally, and what is keeping existing connections occupied? If query execution or locking is the dominant problem, shrinking a pool without addressing that work may only move the queue.

Sample · inspect one worker’s local pool
const snapshot = {
  total: pool.totalCount,
  idle: pool.idleCount,
  waiting: pool.waitingCount,
};
// Export through your approved metrics pipeline,
// labeled by service, replica and worker.

The variable pool is the existing pg.Pool for one process. These counters do not measure server-wide active queries or proxy backend usage. Avoid logging query text, credentials or customer records as a shortcut.

Budget for the largest deployment you can actually run

Twelve replicas are not necessarily the largest footprint. In this case, a rollout can temporarily add three more, giving a peak of fifteen. The connection budget must include that overlap, both worker processes, other workloads, and the planned operational headroom. Ignoring rollout surge can make a configuration look safe only between deployments.

With 200 total slots, thirty held aside in the planning model, and twenty allocated to other work, the application has a modeled budget of 150. Dividing by fifteen replicas and two workers gives five connections per worker as an arithmetic ceiling. This is not evidence that five is a good operational target.

The team chooses four as a candidate to test, leaving additional room under the allocation. At twelve replicas that exposes 96 application connections; with the other twenty, the total is 116. During a fifteen-replica rollout, the total is 140. These are designed bounds. Whether the application meets its latency target at that setting still requires a representative load test.

INTERACTIVE CASE MODEL · WEBGL

How much connection exposure did scale-out add?

Choose a case snapshot or change the per-worker pool cap.

90 above the planned usable budget. Application pools expose 240 connections. Database ceiling: 200; planning reserve: 30; usable budget: 170.

Worked example · a ceiling is not a recommendation
Application allocation = 200 − 30 reserve − 20 other = 150
Arithmetic per-worker ceiling = floor(150 ÷ (15 × 2)) = 5
Candidate for testing: pool max 4
Burst exposure = 12 × 2 × 4 + 20 = 116
Rollout exposure = 15 × 2 × 4 + 20 = 140

All values are hypothetical. The candidate is deliberately below the calculated ceiling. A connection budget does not establish query throughput, database memory safety or a latency guarantee.

Fix pool ownership before tuning its size

Create one shared pool per worker process and reuse it across requests. Creating a pool inside a request handler can multiply connection managers instead of sharing a limit. Check job runners and separate database modules as well: one process can accidentally own several pools with the same default maximum.

Use pool.query for a simple standalone query where its lifecycle fits the operation. When explicitly checking out a client, release it in a finally block. A transaction needs its statements on the same checked-out client, with rollback handling when appropriate; do not spread a transaction across unrelated pool.query calls.

The sample is intentionally limited to a parameterized read and pool lifecycle. Its numeric timeouts are examples, not an end-to-end timeout policy. Application deadlines, database-side statement limits, cancellation, authentication, TLS and shutdown behavior need configuration appropriate to the deployment.

Sample · one pool per worker, bounded checkout
import pg from "pg";

export const pool = new pg.Pool({
  max: 4,
  connectionTimeoutMillis: 1500,
  idleTimeoutMillis: 10000,
  // Use your deployment’s approved connection and TLS configuration.
});

export async function readOrderStatus(orderId) {
  const client = await pool.connect();
  try {
    return await client.query(
      "SELECT status FROM orders WHERE id = $1",
      [orderId],
    );
  } finally {
    client.release();
  }
}

Illustrative ES module using the pg package. This is not a complete endpoint, migration or production configuration. Credentials are not embedded; configure approved pg connection settings externally. The checkout timeout does not impose a query execution deadline.

Bound the work waiting behind the pool

A bounded pool limits open clients; it does not necessarily bound all pending application work. If incoming requests keep accumulating, memory use and waiting time can still grow. Decide how much queued work the service can accept and what happens when that limit is reached.

For this checkout API, the team considers a bounded number of concurrent database operations and a request deadline. Work that cannot start in time should fail through a deliberate, observable response rather than wait indefinitely. The appropriate status and retry advice depend on the endpoint contract and whether any side effect may already have happened.

Do not automatically retry every acquisition or request timeout. Retrying into the same constrained dependency can increase pressure, and a timeout does not prove that an operation had no effect. This article’s mitigation is to control admission and investigate occupied connections; it does not replace a separate retry and idempotency design.

Evaluate a proxy as a separate change

An RDS Proxy can pool backend connections and, where session semantics allow, reuse them between client transactions. AWS distinguishes client connections from database connections and documents session pinning, where a session remains attached to a backend connection. That distinction matters when judging whether a proxy will help this workload.

Run the same workload through the proxy and inspect actual backend connection use, borrowing delay, transaction behavior and pinned sessions. Do not assume that every application connection becomes a fractional database connection. Long transactions or session behavior can reduce the opportunity to reuse a backend.

The proxy also has its own connection allocation and wait settings. AWS documents MaxConnectionsPercent and ConnectionBorrowTimeout, along with metrics for allowed backend connections and borrowing latency. Configure these against the real database budget. A proxy cannot make an expensive query cheap or remove the need to bound the work reaching the database.

A comparison shows direct per-process pools beside a proxy’s separate client and backend connection boundaries, with pinned sessions shown separately.
A proxy changes connection management. It does not guarantee a fixed multiplexing ratio or unlimited database throughput. View full size ↗

Test the failure boundary, not just the happy path

Use a representative non-production environment and synthetic orders. Compare the original configuration with the candidate pool and admission limits under the same offered workload. Include a rising load, a short burst, and a deployment overlap; otherwise the test can miss the condition that motivated the change.

Collect completed requests, errors, queue waiting, query duration, connection use, and database resource pressure. Keep acquisition and execution time separate. A smaller pool that reduces connections while causing unacceptable waiting has not solved the user-facing problem.

Introduce a slow query or controlled downstream delay and verify that waiting work remains bounded. Check shutdown and restart behavior too: old replicas should release clients as new replicas start. If evaluating a proxy, repeat with the actual transaction and session features the application uses. Report the environment and limitations with any results.

The outcome is a defensible operating plan

This case ends with a proposed configuration and acceptance criteria, not an invented recovery chart. The team has identified the potential connection multiplication, designed a lower per-worker pool limit, accounted for rollout overlap, and specified how it will test admission controls and an optional proxy.

A real deployment would proceed only after the controlled comparison meets the application’s agreed latency and error criteria. Roll out gradually, retain rollback settings, and watch the same signals used in the investigation. If waiting rises or database work becomes slower, pause and inspect the cause instead of raising several limits at once.

The lasting lesson is to scale the application with its shared dependencies in view. Count the processes that can open connections, protect operational access, and verify what holds connections. More application replicas are useful only when the full request path can support the work they introduce.

References & further reading

Explore more insights ↗