CodeJournal Blog Header

How to Fix Database Connection Pool Exhaustion in Express.js Applications

Fix Database Pool Exhaustion

Table of Contents

Database connection pool exhaustion occurs when an Express.js application has used all the database connections available in its pool, leaving new queries waiting for an available connection. Users may experience slow API responses, timeout errors, or failed requests even when the Express server itself is still running.

A connection pool is designed to reuse a limited number of database connections instead of opening a new connection for every request. However, that approach only works when connections are reused correctly and returned to the pool after each operation.

Common causes include unreleased database clients, slow queries, excessive concurrent requests, creating multiple pools, and configuring more connections than the database can support. Fixing the problem requires identifying which of these conditions is affecting the application.

Why Does Database Connection Pool Exhaustion Happen in Express.js?

Imagine an Express.js application with a PostgreSQL pool configured to allow ten connections. If ten requests check out connections and keep them occupied, an eleventh request must wait until one becomes available.

The problem becomes more serious when requests hold connections longer than necessary. A slow query, an unfinished transaction, or code that forgets to release a client can prevent other requests from accessing the database.

The database may also enforce its own connection limit. PostgreSQL’s max_connections setting controls the maximum number of concurrent connections the server accepts. Increasing that limit consumes additional server resources, so it should not be treated as an unlimited solution. PostgreSQL documents this behavior in its connection settings.

Common causes developers should investigate

  • Connection leaks: A checked-out client is never returned to the pool.
  • Slow database queries: Connections remain occupied while expensive queries execute.
  • Multiple pool instances: The application creates a separate pool for every request or module initialization.
  • Excessive concurrency: Too many requests or parallel database operations compete for a limited number of connections.
  • Long-running transactions: A transaction remains open while application code performs unrelated work.
  • Incorrect pool sizing: The combined connection limits across application instances exceed database capacity.

Step 1: Create One Reusable Connection Pool

One of the most common mistakes is creating a new database pool inside an Express route or request handler. Every new pool manages its own connections, which can quickly increase the total number of connections reaching the database.

Instead, create the pool once when the application starts and import that shared instance wherever database access is required.

For PostgreSQL using node-postgres, create a file such as db.js:

const { Pool } = require("pg");

const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
  max: 10,
  idleTimeoutMillis: 30000,
  connectionTimeoutMillis: 5000
});

pool.on("error", (error) => {
  console.error("Unexpected idle database client error:", error);
});

module.exports = pool;

// Then reuse the same pool in your routes:

const express = require("express");
const pool = require("./db");
const router = express.Router();

router.get("/users", async (req, res, next) => {
  try {
    const result = await pool.query(
      "SELECT id, name, email FROM users"
    );
    res.json(result.rows);
  } catch (error) {
    next(error);
  }
});

module.exports = router;

This example uses a single shared pool rather than creating new pools for individual requests. The values shown are starting configuration examples, not universal production settings. Choose limits according to your database capacity and deployment size.

The node-postgres pool documentation explains the available configuration options and pool lifecycle.

Step 2: Release Checked-Out Connections Correctly

A connection leak occurs when application code checks out a database client but fails to release it. This is particularly common when developers use pool.connect() for transactions or multiple related queries.

Consider this problematic example:

const client = await pool.connect();

const result = await client.query(

  “SELECT * FROM orders”

);

return result.rows;

The code obtains a client but never returns it to the pool. Repeated requests can eventually occupy every available connection.

Use try…finally to guarantee that the client is released, including when a query fails:

const client = await pool.connect();

try {
  const result = await client.query(
    "SELECT * FROM orders"
  );
  return result.rows;
} finally {
  client.release();
}

// For an Express route, send the response inside the try block and let the finally block release the connection:

router.get("/orders", async (req, res, next) => {
  let client;
  try {
    client = await pool.connect();
    const result = await client.query(
      "SELECT id, total FROM orders"
    );
    res.json(result.rows);
  } catch (error) {
    next(error);
  } finally {
    if (client) client.release();
  }
});

For a single independent query, pool.query() is usually simpler because the pool handles checking out and returning the client automatically. Use pool.connect() when you need a dedicated client, such as for a transaction.

Step 3: Keep Database Transactions Short

Transactions can exhaust a connection pool when they remain open longer than necessary. A common mistake is performing external API calls, file operations, or lengthy business logic between BEGIN and COMMIT.

For example, an application might start a transaction, update an order, call a payment service, and then wait several seconds before committing. During that period, the database connection remains occupied.

Keep the transaction focused on database operations:

const client = await pool.connect();

try {
  await client.query("BEGIN");

  await client.query(
    "UPDATE orders SET status = $1 WHERE id = $2",
    ["processing", orderId]
  );

  await client.query(
    "INSERT INTO order_logs (order_id, action) VALUES ($1, $2)",
    [orderId, "Order processing started"]
  );

  await client.query("COMMIT");
} catch (error) {
  await client.query("ROLLBACK");
  throw error;
} finally {
  client.release();
}

In production code, handle rollback failures carefully so they do not hide the original error. Also avoid holding a transaction open while waiting for user input or unrelated network requests.

NOT SURE WHAT TO DO NEXT?

Let’s Figure It Out.

Tell us what you’re working on and we’ll help you identify the right next step.

Talk to an Expert

Step 4: Optimize Slow Queries That Hold Connections

A connection pool can be configured correctly and still become exhausted if database queries take too long. When a query occupies a connection for an extended period, fewer connections remain available for other requests.

Start by identifying slow queries. In PostgreSQL, tools such as EXPLAIN ANALYZE help developers inspect query execution plans and understand where database time is being spent. Use it carefully because it executes the query being analyzed.

Common improvements include:

  • Adding indexes for columns frequently used in filters and joins.
  • Selecting only the columns an endpoint actually needs.
  • Avoiding unnecessary queries inside loops.
  • Using pagination instead of returning an entire large table.
  • Reviewing joins and filtering conditions.
  • Checking whether database locks are delaying queries.

For example, fetching every order for a user may return far more data than an API page needs. A paginated query reduces the amount of work:

const result = await pool.query(
  `SELECT id, total, created_at
   FROM orders
   WHERE user_id = $1
   ORDER BY created_at DESC
   LIMIT $2 OFFSET $3`,
  [userId, 20, 0]
);

Use parameterized queries, as shown above, rather than inserting user input directly into SQL strings.

Slow database operations can also contribute to slow Express.js API responses. If your application has both symptoms, investigate query duration and connection wait time separately. See How to Fix Slow Express.js API Responses Caused by Blocking Operations for the related API performance issue.

Step 5: Configure Pool Size and Timeouts Carefully

Increasing the pool size may help when the database has spare capacity and requests are waiting because the application pool is too small. However, setting an unnecessarily high value can overload the database.

For example, if an application runs four server instances and each instance has a pool maximum of 20, the application may open up to 80 pooled database connections. Other services, background workers, monitoring tools, and administrative sessions may need connections too.

Calculate the total possible connections before changing the pool limit:

Total application connections = pool maximum per instance × number of instances

Then reserve capacity for other database clients and operational needs.

For PostgreSQL with node-postgres, important settings include:

  • max: Maximum number of clients in the pool.
  • idleTimeoutMillis: How long an idle client can remain in the pool before being closed.
  • connectionTimeoutMillis: How long the pool waits when establishing a new connection.

A connection timeout prevents requests from waiting indefinitely when the pool cannot establish a connection. It does not fix a connection leak or make slow queries faster.

Do not copy a pool size from another application without considering database limits, query duration, application replicas, and workload concurrency.

Step 6: Control Excessive Concurrent Database Requests

A large number of simultaneous queries can exhaust a pool even when every connection is released correctly.

For example, an endpoint that loads a user’s profile and then launches hundreds of database queries through an unrestricted Promise.all() can create a sudden demand spike. The pool may queue the excess requests, increasing response times.

Limit concurrency for large workloads. Process records in manageable batches, use pagination, or introduce a concurrency limiter rather than starting every query at once.

Also consider applying request-level limits to expensive endpoints. A queue or background job system can be more appropriate for bulk imports, report generation, and other tasks that do not need to finish during the HTTP request.

Step 7: Monitor Pool Usage and Find the Bottleneck

You cannot reliably fix connection pool exhaustion by looking only at HTTP response times. Monitor pool activity and database performance together.

The pg library exposes useful pool properties:

setInterval(() => {

  console.log({

    totalConnections: pool.totalCount,

    idleConnections: pool.idleCount,

    waitingRequests: pool.waitingCount

  });

}, 10000);

Interpret these values as follows:

  • totalCount: Number of clients currently in the pool.
  • idleCount: Number of clients available for reuse.
  • waitingCount: Number of requests waiting for a client.

If waitingCount repeatedly rises while idleCount remains zero, the pool is under pressure. Investigate query duration, connection leaks, and request concurrency before increasing max.

For PostgreSQL, also inspect active sessions and long-running queries. This helps distinguish an application pool that is too small from a database that is slow or already at its connection limit.

In production, send these measurements to a monitoring system rather than relying only on console output. Track connection wait time, query duration, timeout counts, and the number of active database sessions.

Step 8: Consider a Database Connection Pooler

When an application has many server instances, a separate connection pooler can help manage the number of connections reaching PostgreSQL.

PgBouncer is a lightweight connection pooler that sits between applications and PostgreSQL. It can reuse a smaller number of server-side connections for a larger number of client connections.

This is particularly useful when deploying multiple application instances or serverless functions that would otherwise create separate pools. However, transaction pooling changes some session-level behavior, so applications that rely on session state, temporary tables, or prepared statements must be configured and tested appropriately.

A pooler is not a substitute for fixing leaked connections, inefficient queries, or excessive concurrency. It addresses connection management at another layer.

Conclusion

To fix database connection pool exhaustion in Express.js applications, start by reusing a single pool, releasing checked-out clients in a finally block, and keeping transactions short. Next, identify slow queries, control excessive concurrency, and calculate the total connection demand across all application instances.

Monitor pool metrics such as total, idle, and waiting connections to confirm whether your changes solve the actual bottleneck. Increase pool limits only when the database has enough capacity to support them. For larger deployments, a connection pooler such as PgBouncer may provide an additional layer of control.

The goal is not simply to create more database connections. It is to make each connection available for reuse as quickly and safely as possible.

FAQs

What causes database connection pool exhaustion in Express.js?

It usually happens when all available connections are occupied and new database requests cannot obtain one. Common causes include failing to release checked-out clients, slow queries, long-running transactions, creating multiple pools, and sending too many concurrent queries.

How do I fix the “too many clients already” error in PostgreSQL?

First, inspect active database connections and identify which application or process is using them. Check for connection leaks, ensure your application reuses a shared pool, and verify that checked-out clients are released. Then compare the combined pool sizes across application instances with PostgreSQL’s connection limit. Increasing max_connections should be considered only after reviewing database resource capacity.

Does increasing the Express.js database pool size fix connection exhaustion?

Not necessarily. A larger pool can help if the current pool is undersized and the database has spare capacity. However, it can make the problem worse if slow queries or connection leaks are keeping clients occupied. Calculate total connections across all application instances before increasing the limit.

How can I detect a database connection leak in Node.js?

With node-postgres, monitor pool.totalCount, pool.idleCount, and pool.waitingCount. If connections remain checked out and waiting requests continue to increase, inspect code that uses pool.connect(). Make sure every acquired client is released in a finally block, including when queries or transactions fail.

 Can slow SQL queries cause connection pool timeout errors?

Yes. A slow query holds its connection for longer, reducing the number of connections available to other requests. If enough queries run slowly at the same time, requests may wait until the pool’s acquisition timeout is reached. Use query monitoring and PostgreSQL execution plans to identify and optimize expensive operations.

NEED HELP WITH THIS?

Let’s Talk About Your Business

Not sure which approach is right for your business? Get a free consultation with our team.

Get Free Consultation

Leave a Reply

Your email address will not be published. Required fields are marked *

NOT SURE WHAT TO DO NEXT?

Let's Figure It Out.

Tell us what you’re working on and we’ll help you identify the right next step.

NEED HELP WITH THIS?

Let's Talk About Your Business

Not sure which approach is right for your business? Get a free consultation with our team.