'MongoDB Atlas very slow connection on hot reload

I have been working on a React application that would connect to MongoDB Atlas with Mongoose. Using nodemon and webpack for hot reloading it would reconnect to Mongo within milliseconds every time there was a reload. It was working nicely like this for months, then suddenly began taking 20+ seconds to connect on every reload - which has significantly increased dev time.

I cannot figure out what caused this to start happening and how to fix it. Any advice would be greatly appreciated.

Note: My IP Address has already been whitelisted.

const db = "mongodb+srv://<username>:<password>@cluster0-omitted.mongodb.net/<dbname>?retryWrites=true&w=majority"

const connectDB = async () => {
  try {
    console.log('Attempting to connect to MongoDB...');
    await mongoose.connect(db, {
      useNewUrlParser: true,
      useCreateIndex: true,
      useFindAndModify: false,
      useUnifiedTopology: true,
    });
    console.log('MongoDB connected...');
  } catch (err) {
    console.log(err.message);
    process.exit(1); // Exit process with failure
  }
};


Solution 1:[1]

As ridiculous as it sounds, reboot your router. Or more technically, you have a problem with DNS and rebooting can resolve it.

I had a similar problem after a power failure at home. When the NAS came back not all Docker containers came back up, including my pihole. DNS seemed fine elsewhere so I didn't notice, but MongoDB Atlas specifically took 20 seconds to connect. After starting the Pihole docker container, it now connects in 600ms, which is much closer to normal.

Solution 2:[2]

I don't know if this helps you out but have you tried to change IP allowed list to all and try it again. I had the same issue where I had assigned my network IP to allowed list. After changing it to allow all IP in MongoDB dashboard it seems to have solved the problem.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DOOManiac
Solution 2 Atharva Malji