2

I have been trying out aws lambda with node+knex and have the same issue as this question : AWS Lambda with Knex JS and RDS Postgres

Here is my code for handler.js:

const knex = require('knex')({
  client: 'pg',
  connection: {...},
});
reports = []
async function run() {
  ///running some codes
  foo.query().insert ()
  bar.query().insert()
  knex.client.destroy();
  return reports
}

module.exports.testing123 = async event => {
  const results = await run()  
  return results
}

The first time running the function will always work fine but if I try to invoke it again it will return error:

2020-09-20T20:14:09.251Z    4ca734a3-a780-44e3-a881-eebdc27effb0    ERROR   Invoke Error    {"errorType":"Error","errorMessage":"Unable to acquire a connection","stack":["Error: Unable to acquire a connection","    at Client_PG.acquireConnection (/var/task/node_modules/knex/lib/client.js:340:30)","    at Runner.ensureConnection (/var/task/node_modules/knex/lib/runner.js:248:8)","    at Runner.run (/var/task/node_modules/knex/lib/runner.js:27:12)","    at Builder.Target.then (/var/task/node_modules/knex/lib/interface.js:15:43)","    at processTicksAndRejections (internal/process/task_queues.js:97:5)"]}

removing the 'knex.client.destroy()' line will fix this but I dont think that is the right solution as we should always destroy after using the connection.

deploying the code again also will run fine for the first time

Amirul Iqram
  • 313
  • 1
  • 3
  • 13

1 Answers1

3

Anything defined outside of the handler being exported is persisted on the lambda instance that is provisioned. So what's happening is that the instance is starting with the knex connection, but is being destroyed on the first request. You aren't creating a new connection to knex on each new request to your lambda in this case.

If you want to connect and destroy per request, then you need to instantiate knex inside of the function.

Elbert Bae
  • 205
  • 3
  • 11