title: AWS Lambda with Knex JS and RDS Postgres
body: <p>I have been doing some research and I'm not able to find a good answer about using Knex JS within a Lambda function:</p>
  
  <p><a href="https://github.com/tgriesser/knex/issues/1875" rel="noreferrer">How do I use Knex with AWS Lambda? #1875</a></p>
  
  <p><a href="https://medium.com/@zpnk/how-to-serverless-url-shortener-with-apex-and-aws-lambda-5cc78535410a" rel="noreferrer">Serverless URL Shortener with Apex and AWS Lambda</a></p>
  
  <p><a href="https://stackoverflow.com/questions/41927000/use-promise-all-in-aws-lambda">Use Promise.all() in AWS lambda</a></p>
  
  <p>Here is what I have in my index.js:</p>
  
  <pre><code>const knex = require('knex')({
    client: 'pg',
    connection: {...},
  });
  
  exports.handler = (event, context, callback) =&gt; {
    console.log('event received: ', event);
    console.log('knex connection: ', knex);
  
    knex('goals')
      .then((goals) =&gt; {
        console.log('received goals: ', goals);
        knex.client.destroy();
        return callback(null, goals);
      })
      .catch((err) =&gt; {
        console.log('error occurred: ', err);
        knex.client.destroy();
        return callback(err);
      });
  };
  </code></pre>
  
  <p>I am able to connect and execute my code fine locally, but I'm running into an interesting error when it's deployed to AWS - the first call is always successful, but anything after fails. I think this is related to the knex client being destroyed, but then trying to be used again on the next call. If I re-upload my index.js, it goes back to working for one call, and then failing.</p>
  
  <p>I believe this can be resolved somehow using promises but this my first time working with Lambda so I'm not familiar with how it's managing the connection to RDS on subsequent calls. Thanks in advance for any suggestions!</p>