[Fixed] Why does the first connection/request to MongoDB Atlas database taking so long?


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:'));


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.

Leave a Reply

(*) Required, Your email will not be published