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")
const connection = mysql.createConnection({
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"
}).promise()
exports.handler = async (event, context) => {
try {
await connection.connect()
console.log(`Connected to db. ConnectionId: ${connection.threadId}`)
} catch (err) {
return handleError(err)
}
try {
// Do some queries
} catch (err) {
return handleError(err)
} finally {
await connection.end() // Should I close the connection here?
}
return response(200, "Success")
}
>Solution :
Should I close the connection after executing my queries or leave it open for the RDS Proxy to handle?
You should not leave database connections open regardless of if you use or don’t use a database proxy.
Connections are a limited and relatively expensive resource.
The rule of thumb is to open connections as late as possible & close DB connections as soon as possible. Connections that are not explicitly closed might not be added or returned to the pool. Closing database connections is being a good database client.
Keep DB resources tied up with many open connections & you’ll find yourself needing more vCPUs for your DB instance which then results in a higher RDS proxy price tag.
And if I should close the connection, then what’s the point of using an RDS Proxy in the first place?
The point is that your Amazon RDS Proxy instance maintains a pool of established connections to your RDS database instances for you – it sits between your application and your RDS database.
The proxy is not responsible for closing local connections that you make nor should it be.
It is responsible for helping by managing connection multiplexing automatically for applications that need it e.g. Lambda functions that frequently open and close database connections.
It’s even mentioned as an official reason to be using RDS proxy for in the docs:
Many applications, including those built on modern serverless architectures, can have a large number of open connections to the database server, and may open and close database connections at a high rate, exhausting database memory and compute resources.
Amazon RDS Proxy allows applications to pool and share connections established with the database, improving database efficiency and application scalability.