title: Does Google Cloud Functions reconnect to my MongoDB Client for each HTTP request?
body: <p>I am trying to migrate my Node/Express REST API to Google Cloud Functions, and was noticing some performance issues. I am receiving 404 errors on all my API routes while waiting for my Functions to "spin up" after a period of inactivity. I was curious if this was related to my implementation. Here is my Express serverless "server", written in Typescript (<code>index.ts</code>):</p>
  
  <pre><code>import * as functions from 'firebase-functions'
  import * as express from 'express'
  import { MyApi } from './server'
  
  const app: express.Application = MyApi.bootstrap().app
  
  export const myApp = functions.https.onRequest(app)
  </code></pre>
  
  <p>Next, here is <code>server.ts</code></p>
  
  <pre><code>import * as express from 'express'
  import * as mongodb from 'mongodb'
  
  require('dotenv').config({ path: '.env' })
  
  export class MyApi {
    app: express.Application = express()
    mongoDbUri: string = process.env.MONGO_URI
  
    static bootstrap(): MyApi {
      return new MyApi()
    }
  
    constructor() {
      this.connectToDb(this.mongoDbUri)
    }
  
    connectToDb(uri: string) {
      mongodb.MongoClient.connect(uri, (err, db) =&gt; {
        if (err) {
          this.handleNoDbError(err)
        }
        setApiRoutes(app: express.Application, db)
      })
    }
  }
  </code></pre>
  
  <p>I've stripped a lot of the redundant code for the sake of simplicity, but hopefully this is enough for you to get the idea. I am asking Functions to expose some API endpoints. First, I am using connection pooling to make a single Mongo connection, then I pass that connection (<code>db</code>) down to my routes. These route endpoints in turn make a <code>find()</code> request to my MongoDB Atlas database, and pass those results on to my app.</p>
  
  <p>I deployed a version of this code and it is functioning ok, in that it fetches results properly. However I am concerned about the slow performance and intermittent 404 errors (compared to a dedicated Node/Express server on Heroku, for example). </p>
  
  <p>I was wondering if my problems are related to the Mongo Client. Is it connecting to my database every time a request is made to Functions? Once my Functions wake up after inactivity, do they persist the same Mongo DB connection across all future requests? I'm new to serverless so I guess I'm confused about whether my Functions start up and stay up during execution, then "shut down" after going idle.</p>
  
  <p>Can supply live links if needed. </p>