Reputation: 1
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.
mongodb+srv://<username>:<password>@cluster.example.mongodb.net/mydb?readPreference=nearest&retryWrites=true&w=majority
// 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 });
}
});
Why are requests from the US still being routed to ap-south-1 instead of us-east-2, even with readPreference=nearest?
Is there a better way to verify that requests from the US are being directed to the nearest region (us-east-2)?
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
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