title: Connection goes idle and disconnects Mongodb from AWS Lambda
body: <p>MongoDB idle problem is giving me nightmares. It fails without reason, it doesn't trigger disconnecting event or error. it just disconnects in the middle of API call.</p>
  <p>I have tried reading blogs and old questions as well and tried it all, still the situation doesn't help at all.</p>
  <p>This is my database connection code:</p>
  <pre><code>function connect () {
  
  return mongoose.connect(process.env.MONGO_DB_URI, {
      useNewUrlParser: true,
      reconnectTries: Number.MAX_VALUE,
      reconnectInterval: 1000,
      bufferMaxEntries: 0, // and MongoDB driver buffering
      bufferCommands: false, // Disable mongoose buffering
      ha: true, // Make sure the high availability checks are on
      haInterval: 10000 // Run every 10 seconds
    })
  }
  
  if (process.env.MONGO_DB_URI) {
    connect()
  }
  </code></pre>
  <p>with it I am also logging several events for the database.</p>
  <pre><code>db.on('connecting', () =&gt; {
    debug(`mongoose : connecting `)
  })
  
  db.on('connected', () =&gt; {
    debug(`mongoose : connected`)
  })
  db.on('open', () =&gt; {
    debug(`mongoose : open`)
  })
  db.on('disconnecting', () =&gt; {
    debug(`mongoose : disconnecting`)
  })
  db.on('disconnected', () =&gt; {
    debug(`mongoose : disconnected`)
  })
  db.on('close', () =&gt; {
    debug(`mongoose : close`)
  })
  db.on('reconnected', () =&gt; {
    debug(`mongoose : reconnected`)
  })
  db.on('error', (err) =&gt; {
    debug(`mongoose : error`, err)
  })
  db.on('all', () =&gt; {
    debug('mongoose: all')
  })
  db.on('fullsetup', () =&gt; {
    debug(`mongoose : fullsetup`)
  })
  </code></pre>
  <p>Also before API call I check for the database connection from a middleware.</p>
  <pre><code>app.use(async (req, res, next) =&gt; {
    log.info('Ready State: ' + mongoose.connection.readyState, {
      action: 'App.ConnectionCheck'
    })
    if (mongoose.connection.readyState !== 1) {
      log.info('try to reconnect', {
        action: 'App.ConnectionCheck'
      })
      await connect()
      next()
    } else if (mongoose.connection &amp;&amp; mongoose.connection.db) {
      await Promise.race([
        mongoose.connection.db.admin().ping(),
        new Promise((resolve, reject) =&gt; {
          setTimeout(() =&gt; {
            reject(new Error('Race condition failed'))
          }, 1000)
        })
      ]) 
      .then(async d =&gt; {
        log.info('ping successful: ', d)
        if (d.ok !== 1) {
          await connect()
        }
      })
      .catch(async e =&gt; {
        log.error('Ping Failed ', {
          error: e
        })
        await connect()
      })
      next()
    } else {
      next()
    }
  })
  </code></pre>
  <p>But still sometimes a call comes in, and first query is made, but i dont get a response back and my API times out.</p>
  <p>This is what my logs look like notice the time it takes to reconnect.</p>
  <pre><code>2020-08-10 16:30:55.465 (+05:00)        34c5812c-5446-4c0f-bddf-c4ca8a0117cb    INFO    ----------------- BODY END ------------
  2020-08-10 16:30:55.466 (+05:00)        34c5812c-5446-4c0f-bddf-c4ca8a0117cb    INFO    Mongoose: meetings.countDocuments({ appntId: '&lt;APP_ID_HERE&gt;', '$or': [ { deleted: true }, { createdAt: { '$gt': new Date(&quot;Mon, 10 Aug 2020 11:30:45 GMT&quot;) } {})
  Mon, 10 Aug 2020 11:30:55 GMT timify:db-handle:index mongoose : disconnected
  Mon, 10 Aug 2020 11:31:15 GMT timify:db-handle:index mongoose : connected
  Mon, 10 Aug 2020 11:31:15 GMT timify:db-handle:index mongoose : reconnected
  END RequestId: 34c5812c-5446-4c0f-bddf-c4ca8a0117cb
  END RequestId: 34c5812c-5446-4c0f-bddf-c4ca8a0117cb
  REPORT RequestId: 34c5812c-5446-4c0f-bddf-c4ca8a0117cb  Duration: 30030.13 ms   Billed Duration: 30000 ms       Memory Size: 10
  Max Memory Used: 172 MB
  </code></pre>
  <p><strong>Version</strong>:</p>
  <ul>
  <li>&quot;mongoose&quot;: &quot;^5.4.17&quot;</li>
  <li>&quot;nodejs&quot;: &quot;12.x&quot;</li>
  <li>&quot;mongodb-driver&quot;: &quot;3.1&quot;</li>
  </ul>
  <p>I have seen another post regarding this issue, but my environment is different and that question is back from 2016.</p>