1

I created a webapp using React, Nodejs and Mongodb as a database. I'm taking advantage of the free MongoDB Atlas database for now, so I created an account and a db there, then I connected it with my node/express server.

My app is working perfectly, I'm able to register/login a user and fetch data etc.. However, the first request takes always so long to finish. I deployed the app for free on Heroku for now. When I open the app and try to login, this first request takes about 20 seconds to finish and log in the user. After that, everything works fine and fast, so it's really only about that first start.

Since my app is working, I don't know what is the problem here. My only guess is that this issue specific to MongoDB Atlas and their free database.

This is the code I'm using for connecting to the db, it's pretty straightforward:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;


mongoose.connect(MONGODB_HOST, {
  useNewUrlParser: true, 
  useUnifiedTopology: true, 
  useFindAndModify: true,
  useCreateIndex: true });

const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
halfer
  • 19,824
  • 17
  • 99
  • 186
basilisk
  • 1,156
  • 1
  • 14
  • 34
  • Can you share the connection string replacing user, password and cluster ID? Should look like `mongodb+srv://user:pass@clusterID.mongodb.net/?options`. From my experience it could take 1 or 2 seconds, unless something is clinking – Minsky Nov 21 '20 at 10:17
  • @Minsky yes exactly. here is how my connection string looks like: "mongodb+srv://user:pass@clusterID.mongodb.net/dbname?retryWrites=true&w=majority" – basilisk Nov 21 '20 at 10:22
  • @Minsky I just copy pasted this from the mongoDB Atlas website when I created the db – basilisk Nov 21 '20 at 10:23
  • Try adding `family:4` to the options – Minsky Nov 21 '20 at 10:32
  • @Minsky thanks for the suggestion but it didn't work. It still needs ~ 30 seconds for the first request. What is confusing is that it works very fast after that first request. It's like a weird cold start eachtime. I have the feeling that the connection to mongodb atlas dissapear when I stop using the app for a long time! – basilisk Nov 21 '20 at 13:18

1 Answers1

3

Both Heroku and Atlas suspend free tier applications/clusters when they are not being used.

If you have large gaps between uses you either need to live with it or set up a periodic task to periodically poke the application to keep it running.

For Heroku see:

Once that is done, do something with the database from the action invoked by the pinger to keep Atlas running.

D. SM
  • 13,584
  • 3
  • 12
  • 21