Skip to content

Question: AWS Lambda + RDS Proxy and Pool class - Best practices? #3016

@ivrtaric

Description

@ivrtaric

Hello everyone,

What would be the best way to use the Pool object together with the RDS Proxy, i.e. to be able to run multiple queries concurrently (e.g. await Promise.all([ query1(), query2(), query3() ])) during a single request to the Lambda handler, but also to make sure the connections are correctly returned to the RDS Proxy pool after the request is processed?

All around the web the suggestion for using the Pool is - declare the pool variable outside the handler function, create the Pool instance on the first request, then have the subsequent requests reuse the pool, removing the need to connect to the DB every time the Lambda is invoked. However, if the Lambda is not invoked often, and/or requires as many connections as it can get (with some reasonable upper limit), it would seem proper to return those connections to the RDS Proxy as soon as the processing is finished, instead of keeping those connections reserved for the Lambda lifetime, and only returning them after the Lambda is shut down.

I was thinking about something similar to this:

export default const handler = async (event) => {
  let pool: Pool | undefined = undefined;
  let client: PoolClient | undefined = undefined;

  try {
    pool = new Pool({ ...config });
    client = await pool.connect();

    const [value1, value2, value3] = await Promise.all([
      client.query(query1),
      client.query(query2),
      client.query(query3)
    ]);

    // Do something with values
    return retValue;
  } catch (e) {
    // Error handling
  } finally {
    await client?.release();
    await pool?.end();
  }
};

Does this type of Pool usage make sense, or is there some other (better?) way of doing this?

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