title: Should I close an RDS Proxy connection inside an AWS Lambda function?
body: <p>I'm using Lambda with RDS Proxy to be able to reuse DB connections to a MySQL database.</p>
  <p>Should I close the connection after executing my queries or leave it open for the RDS Proxy to handle?</p>
  <p>And if I should close the connection, then what's the point of using an RDS Proxy in the first place?</p>
  <p>Here's an example of my lambda function:</p>
  <pre class="lang-js prettyprint-override"><code>const mysql = require(&quot;mysql2/promise&quot;)
  
  exports.handler = async (event) =&gt; {
    let connection
  
    try {
      connection = await 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: &quot;Amazon RDS&quot;
      })
      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, &quot;Success&quot;)
  }
  </code></pre>
  <p><strong>EDIT:</strong> Beware that initializing the connection outside the handler (<a href="https://docs.aws.amazon.com/lambda/latest/operatorguide/global-scope.html" rel="nofollow noreferrer">global scope</a>) 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 <strong>Can't add new command when connection is in closed state</strong> 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.</p>