ServerlessArchitecture#04 AWS Lambda Cold Starts#PART-2 Keeping Connections Alive in WAY Different
To summarize, the blog Use-Cases are:
- Imagine that you need to connect to resources like Database Clients or Feature Flag Clients where you create a connection every time -- Seems simple --Yah!!!-- but in FaaS we need to think on a major scale.
- Imagine that this same code runs for 1,000,000 users, per second - What would happen then !!!
- The golden rule - take advantage of the global state of your Lambdas and initialize your connections once
Imagine that you need to connect to resources like Database Clients or Feature Flag Clients where you create a connection every time. You create a code that will look like this:
const mysql = require('mysql')
module.exports.myhandler = function (event, context, cb) {
const conn = mysql.createConnection({
// mysql connection info
});
conn.query("SELECT * FROM items", (error, results) => {
if (error) {
cb(error, null)
} else {
cb(null, results)
}
})
}
You can see that every time this function is executed, it will connect to a MySQL DB and then query something for us. Seems straightforward and looks like there’s no problem, but in FaaS we need to think on a major scale.
Imagine that this same code runs for 1,000,000 users, per second. This will absolutely crash our MySQL DB since we create a DB connection per user.
To solve this problem, thankfully, AWS Lambda provides a global state that will be executed just once and keep the state while the Lambda is alive.
- For DB connections, we can create a connection pool and
- re-use that same connection for all the concurrent Lambdas.
Our code should now look like:
module.exports.myhandler = function (event, context, cb) {
conn.query("SELECT * FROM items", (error, results) => {
if (error) {
cb(error, null)
} else {
cb(null, results)
}
})
}