Share external database connection between events in serverless

I’m creating a app that connects to an external database (postgres), using node-postgres lib.

I created the connection outside the events, but the same connection is not used when the event is called again, as show in the image (prisma_test database):

this is the file the connection is made from:


const newPool = async () => {
  const pool = new Pool({
    user: "postgres",
    host: "localhost",
    database: "prisma_test",
    password: "postgres",
    port: 5432,
  });

  return await pool.connect();
};

exports = {
  query: async function (text, params) {
    const connection = await newPool();
    return await connection.query(text, params);
  },
};

and the call in server.js

image

I tried to store the connection object in fdk local storage, but it didn’t work.

How should I share this connection between any event?

Regards,

Felipi Lima Matozinho

1 Like

Hey Felipi,
So the problem you are facing is that, you are creating a connection pool and trying to re-use the a connection from the pool for each of the events. But each of the new invocation of events, seems to create a new connection rather than using already created connection from pool.
The reason for the happening is, each of the events are triggered independent and in a separate instance. Hence, during each invocation a new connection pool is created and a connection object is assigned from the pool. So, we would recommend to use a single connection for each of the event handler.

2 Likes

Hi @Chandiramouli_Ramach, thanks for explain!

I will use a single connection per event.

This topic was automatically closed 6 days after the last reply. New replies are no longer allowed.