Home:ALL Converter>Should I close an RDS Proxy connection inside an AWS Lambda function?

Should I close an RDS Proxy connection inside an AWS Lambda function?

Ask Time:2021-12-12T01:09:48         Author:Ahmad Nabil

Json Formatter

I'm using Lambda with RDS Proxy to be able to reuse DB connections to a MySQL database.

Should I close the connection after executing my queries or leave it open for the RDS Proxy to handle?

And if I should close the connection, then what's the point of using an RDS Proxy in the first place?

Here's an example of my lambda function:

const mysql = require("mysql2/promise")

const config = {
  host: process.env.RDS_HOST, // RDS Proxy endpoint here
  user: process.env.RDS_USER,
  database: process.env.RDS_DATABASE,
  password: process.env.RDS_PASSWORD,
  ssl: "Amazon RDS"
}

exports.handler = async (event) => {
  let connection

  try {
    connection = await mysql.createConnection(config)
    console.log(`Connected to db. ConnectionId: ${connection.threadId}`)

    // Do some queries
  } catch (err) {
    return handleError(err)
  } finally {
    if (connection) await connection.end() // Should I close the connection here?
  }

  return response(200, "Success")
}

EDIT: Beware that initializing the connection outside the handler (global scope) will make the lambda function retain the value of the connection variable between invocations in the same execution environment which will result in the following error Can't add new command when connection is in closed state when calling the lambda function multiple times in a short period of time because the connection is already closed in the first invocation, so I'd better suggest defining the connection inside the handler not outside.

Author:Ahmad Nabil,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/70317250/should-i-close-an-rds-proxy-connection-inside-an-aws-lambda-function
yy