I have a AWS Lambda function written in node.js that utilizes the mysql npm library. I am having a hard time understanding how connections work in a serverless environment. Should I close the connection at the end of my function, connection.end ? Should I have a pool of connections rather than just one? I guess what I am looking for is best practices for handling db connections in a serverless infrastructure.
I am appreciate any response. Thank you! :)
Melwin D'Almeida
Connection to the database is a one time operation. Therefore you can put it outside the handler function. All other query operations should be put in the handler function and exported.
var mysql = require('mysql'); var connection = mysql.createConnection({ host:'localhost', user:'me', password:'secret', database:'my_db' }); connection.connect(); // Here you put all the sql query operations you are performing exports.handler = function(event, context, callback) { connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) { if (error) throw error; console.log('The solution is: ', results[0].solution); }); };