Prathm More
Prathm More

Reputation: 1

MongoDB Multi-Region Replica with readPreference=nearest Still Redirecting to Primary Region

I am trying to reduce latency in my application by setting up a multi-region replica using MongoDB Atlas. Initially, my database was hosted in a single region (Mumbai: ap-south-1). To improve latency for users in the US, I created a replica in the US Ohio region (us-east-2).

Here's what I've done so far:

Configured a multi-region setup in MongoDB Atlas with the primary region in ap-south-1 and a replica in us-east-2. Updated my connection string to include readPreference=nearest to ensure queries are routed to the nearest replica. Created an API /db-location that fetches and logs the database info in JSON. I asked a US-based client to call this endpoint to verify if their requests are being routed to the us-east-2 replica. However, the output of /db-location still shows ap-south-1, indicating that requests are still being routed to the Mumbai region.

My Connection String:

mongodb+srv://<username>:<password>@cluster.example.mongodb.net/mydb?readPreference=nearest&retryWrites=true&w=majority

API Code to Check MongoDB Server Status:

// API to check MongoDB server status
app.get("/db-location", async (req, res) => {
  try {
    // Check if the MongoDB connection is ready
    if (!mongoose.connection.readyState) {
      return res.status(500).json({ error: "MongoDB connection is not established" });
    }

    // Access the admin interface and fetch server status
    const admin = mongoose.connection.db.admin();
    const serverStatus = await admin.serverStatus();

    res.status(200).json({
      serverStatus: serverStatus,
    });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});
  1. Why are requests from the US still being routed to ap-south-1 instead of us-east-2, even with readPreference=nearest?

  2. Is there a better way to verify that requests from the US are being directed to the nearest region (us-east-2)?

  3. Are there any additional configurations required in MongoDB Atlas or my application to achieve the desired behavior?

Any insights or suggestions would be greatly appreciated!

Upvotes: 0

Views: 41

Answers (1)

Wernfried Domscheit
Wernfried Domscheit

Reputation: 59563

Unless you set a different readPreference with Mongo.setReadPref it should work fine.

However, some commands can run only on the PRIMARY. Command db.serverStatus() return numbers for readPreferenceCounters, so I guess this commands reads data from all nodes and is not suitable to check which node was queried.

Maybe have a look at the explain plan, it may show on which node the query is running (I did not test). Or have a look at currentOp command. The most reliable check would be to have a look at the logfile of the MonogDB member. You can download them in Atlas.

Upvotes: 0

Related Questions