Skip to content

pg connection pool is creating more connections than allowed #3476

Closed as not planned
@dieperdev

Description

@dieperdev

Issue

When I use a connection pool with pg, it creates more connections than allowed.

Details

Node Bun Version: Bun v1.2.10
Postgres Version: v17.5 (docker)
pgbouncer Version: v1.24.0 (running on the same server as postgres)
pg Version: ^8.16.0

Code:

Creating the pool:

// src/lib/db.ts
import "dotenv/config";
import { Pool } from "pg";
import type { PoolConfig } from "pg";

const config: PoolConfig = {
  connectionString: process.env.PG_URL,
  max: 3,
  min: 1,
  allowExitOnIdle: false,
};

const pool = new Pool(config);

export default pool;

The pool is used in multiple routes (different files) like this for the API

// src/index.ts
import { Hono } from "hono";
import pool from "./lib/db";

const app = new Hono();

app.get('/', (c) => {
  const response = await pool.query('select * from users where id = $1::integer;', [1])
  return c.json(response.rows[0])
})

// The other routes are imported and this runs on one file
Bun.serve({
  fetch: app.fetch,
  port: 3000
})
console.log('running backend')

Additional details

The connection url uses a role named "backend". I start the server using bun src/index.js. When the server is started, running select * from pg_stat_activity where usename = 'backend'; in psql shows that multiple connections are created (~one for each route).

The connections that the query returns increases when more routes are added to the server. When the server is shut down, the connections still appear in pg_stat_activity. The postgres server is also behind pgbouncer (using session mode), so it's possible that it might be interfering.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions