node-postgres icon indicating copy to clipboard operation
node-postgres copied to clipboard

Potential memory leak in Pool

Open mschilde opened this issue 4 years ago • 11 comments

Hi,

I have a use case where I run quite a lot of batched queries against Postgres (thousands). I recently ran into memory issues on my worker machine and could trace the issue to an apparent memory leak somewhere in the connection pool.

So far it's just an observation, I didn't build a proper test case yet. But the memory issue went away when I switched from using a connection pool to single-use connections.

Did anyone notice this too? Seems like a recent issue IMO.

I'm using "pg": "^8.7.3" and "pg-native": "^3.0.1"

mschilde avatar Sep 26 '22 15:09 mschilde

I JUST met the similar issue & w/ some trouble shooting. I upgrade to pg ^8.7.1 version. (not invoke pg-native)

The test case is simple: express host a service which process a query sql & an update sql statement there. And use batch call the api (100 concurrent calls), the find memory leak from 40M+ -> 400M+ -> (finally back to 40M)

I use pool.query(...) method (which is recommended), I'll try pool.connect().query() later.

I used Chrome inspector to check, it looks there's an internal array pool._pendingQueue.PendingItem there, each item takes about 4M memory, since there's like 80+ items (I doubt this is the pending process item since I se the configure - max to 10 by default), it then easily take up to 400M memory then.

Here's the screenschot: image

Could anyone help to take a further research please?

Thanks. -Shadow

ShadowLei avatar Sep 27 '22 06:09 ShadowLei

I need self-contained script/file with reproduction case to investigate this. Otherwise there are too many factors involved to pin any memory leak down on pg itself.

brianc avatar Sep 27 '22 10:09 brianc

On it.

mschilde avatar Sep 27 '22 16:09 mschilde

hi @brianc It's no easy to repro. but I think I have the case to reproduce: https://github.com/ShadowLei/pg-test/

main branch. Check the ReadMe file please.

Must ensure we have enough data in DB (my production case had 200K+ data, here we need to prepare 20K+ data to repro) And don't use any index by default, I think which can let the db-connection | execution have a delay there to response & better repro. the issue. Then we run the test case (200 concurrent request, each w/ 4 sql operation), via my Chrome-Inspect tool I can see it took at max at 197M memory, compared to 200 concurrent req. I thinks there might be OOM issue.

Note if w/ a few data (1K test data) in database this issue won't happen, all things looks good.

Env: I used Mac (64G mem) as my local client test. For PGDB which based on AWS w/ v11.6 version, a small version | size.

Thanks. -Shadow

ShadowLei avatar Sep 30 '22 05:09 ShadowLei

Switched to latest version ^8.8.0 & had a try, there's not much memory taken by "PendingItems", but still lots of objects produced (the chrome inspector shows the total objects from 700+ raised up to 500K+)

ShadowLei avatar Oct 04 '22 15:10 ShadowLei

I'm running into this as well. Here's an easy way to reproduce it:

const postgres = await pool.connect()
function query(sql) { postgres.query(sql) }
setInterval(query, 5, sql)

Each call to postgres.query creates a "request" object, a "Result" object and a context / System object - none which are ever garbage collected.

Here's the work around I'm using that recycles clients on a recurring basis:

    let activeClient = await pool.connect()
    let standbyClient = await pool.connect()
    let previouslyActiveClient = null

    async function getActiveClient() {
        if (!activeClient) { activeClient = await pool.connect() }
        return activeClient
    }

    async function getStandbyClient() {
        if (!standbyClient) { standbyClient = await pool.connect() }
        return standbyClient
    }

    async function swapClients() {
        previouslyActiveClient = activeClient

        activeClient = standbyClient
        standbyClient = null
        standbyClient = await getStandbyClient()

      if (previouslyActiveClient) {
        previouslyActiveClient.release()
        previouslyActiveClient = null
      }
    }

    async function query(sql) {
        const client = await getActiveClient()
        return client.query(sql)
    }

    setInterval(swapClients, 5 * 60 * 1000) // refresh Postgres client every 5m

fleshins avatar Jan 02 '23 05:01 fleshins

I also noticed a small memory leak. It seems that the client coming from pool.connect() does not get GC, which slowly increase memory footprint.

image

ilijaNL avatar May 28 '23 08:05 ilijaNL

@ilijaNL Are you using pg-native?

charmander avatar May 29 '23 19:05 charmander

Nope

ilijaNL avatar May 29 '23 20:05 ilijaNL

const postgres = await pool.connect()
function query(sql) { postgres.query(sql) }
setInterval(query, 5, sql)

I haven’t looked into reproducing memory leaks lately, but note that this will grow the query queue forever if the timer fires faster than queries can come back (which is also potentially a compounding problem as the query queue eventually dequeues in O(n) time, since it’s shifting out of an array).

charmander avatar May 30 '23 06:05 charmander

I did some additional testing with this code:

const pool = new Pool({
    connectionString: connectionString,
    max: 20,
    // never disconnect
    idleTimeoutMillis: 0,
  });

  async function tx(item: number) {
    let client = await pool.connect();
    try {
      await client.query('BEGIN');
      // some unique query
      await pool.query(`SELECT ${item}`);
      await client.query('COMMIT');
    } catch (e) {
      await client.query('ROLLBACK');
      throw e;
    } finally {
      client.release();
    }
  }

  let i = 0;
  while (true) {
    // simulate n concurrent requests
    await Promise.all([tx(i++), tx(i++), tx(i++), tx(i++), tx(i++)]);

    // add small delay
    await new Promise((resolve) => setTimeout(resolve, 20));
  }

This produces following heap snapshot: image

Honestly I am not sure if node-postgres produces these or just that NodeJS is lazy with GC on those peaks.

ilijaNL avatar May 30 '23 07:05 ilijaNL