Recently I was working with serverless application created in NodeJs which was deployed to AWS Lambda. This app is connecting to MySQL database which was deployed to RDS. While I was testing in local machine it worked very well.

After deployed it stopped working. After struggling for half a day I was able to finally make it working. In this blog I am going to mention what it takes to make it working.
Different Security Group is the First Solution
This is really strange, if your Amazon RDS and AWS Lambda function shares the security group it will never connect. Not sure why it’s this way, but to solve the problem.
- Create New Security Group and assign it to your Lambda function.
- Create Other Security Group and assign it your RDS
- Allow MySQL connection in RDS Security Group
To allow MySQL connection, add inbound rules. Select MYSQL/Aurora fromType and allow it from 0.0.0.0/0
Allow VPC Access to Lambda Function
- Go to Roles page in IAM consle.
- Create new role and add policy AWSLambdaVPCAccessExecutionRole
- Assign this role to your Lambda function
Use Connection Pool in Your Code
While using serverless you have to be careful about asynchronous operations. Connection to MySQL is also asynchronous operations. If you do not handle it properly, lambda function will give you timeout as it’s expecting callback function to return result but because it’s async operations it will take time. So you have to explicitly let it know that, there is async operation so wait for it.
So for that create connection pool.
var mysql = require(‘mysql’);
var pool = mysql.createPool({
user : ‘username’,
password : “password”,
database: ‘database’,
host : ‘rds_end_point’
});
Now wait to get connection from the pool.
pool.getConnection((err, connection) => {
connection.query(‘SQL’,function(err, rows, fields) {
const response = {
statusCode: 200,
headers: {
“Access-Control-Allow-Origin” : “*” // Required for CORS support to work
},
body: JSON.stringify({
success: true,
rows: rows
})
};
connection.release();
callback(null, response);
});
})
As you can see in above code we are waiting for getting connection. Once we have the connection we query the database and get the result. After that we invoke the callback and release the connection so it can be used for next requests.







