Michael Du
Michael Du

Reputation: 729

How to persist sequelize connection with AWS Lambda functions (or speed up initial connection)?

I currently have an AWS Lambda function utilizing sequelize to connect/query from a MySQL database in RDS.

Everything works as intended, except that the first connection after a period of inactivity always takes at least 5 seconds to start up. Subsequent lambda calls are quick, so I suspect the connection is persisted and pooled.

It's a bit annoying, and so I'm wondering if I can optimize it to either connect faster, or configure lambda so that the connection is permanent.

"use strict"
var Sequelize = require('sequelize')

var database = 'participantData',
    host = 'hostname',
    username = 'username',
    password = 'blah'

var sequelize = new Sequelize(database, username, password, {
  host: host,
  dialect: 'mysql',
  logging: console.log('Query Logged')
})

var Resource = sequelize.define('resource', {
  program_name: { type: Sequelize.STRING },
  geocoded_address: { type: Sequelize.STRING }
})

exports.handler = function(event, context){
  Resource.findAll({
    //some filter
  })
    .then((res) => {
      context.succeed(JSON.stringify(res))
    })
    .catch(error => console.log(error))
}

Upvotes: 2

Views: 5272

Answers (1)

Jason Livesay
Jason Livesay

Reputation: 6377

No you cannot make connections in Lambda permanent because of the basic way it works. But you can optimize Lambda startup times, re-use, etc. See https://www.reddit.com/r/aws/comments/49l91l/lambda_functions_in_vpc_cold_boot_times_of_10/ and https://aws.amazon.com/blogs/compute/container-reuse-in-lambda/

My guess is you just need to send a request every once in awhile so it continues to reuse the container.

Upvotes: 6

Related Questions