首页 > 解决方案 > Sync two Mongodb Databases and have the client connect to the closest one

问题描述

I am using mongodb as a database for my game servers. When I started them, they were bound to just one region, I used the free tier of Mongodb Atlas in that region, India, and it worked perfectly with around 20ms of latency even on high load.

Now when I'm trying to scale up my servers and reach other regions like US-East, the latency jumps up to 500ms.

Is there a way I could open up two mongodb servers on both my India and US instances, which would always be in complete sync with each other, while the game server process would just use localhost to connect to the specific replica. I'm using pyMongo.

The players have no connection with the database, it's the game server process that manages it

标签: mongodbpymongo

解决方案


Is there a way I could open up two mongodb servers on both my India and US instances, which would always be in complete sync with each other, while the game server process would just use localhost to connect to the specific replica.

Assuming you are using a replica set, I believe the closest you can come to achieving the stated requirement for reads is by:

  1. Performing all writes with the write concern w=(# of nodes in the deployment), if you have two servers then use w=2.
  2. Performing reads with read preference=nearest and read concern=majority.

I say "closest" because I suspect read concern=majority on a secondary could return stale data even with w=(# of nodes in deployment), since I imagine the majority commit point would necessarily lag behind the point when each secondary commits each document. To guarantee that you are reading current data you must read from the primary.

Note that such a setup has (at least) two additional major drawbacks:

  1. If any of the servers becomes unavailable, your application ceases to be able to write any data to the database.
  2. Each write will wait for all servers in the deployment to store it, hence all writes will be slow.

Achieving the same requirement for reads and writes is not physically possible. (You essentially want to be able to write a document in, say, India in 20ms and have it be "instantly" available in US, i.e. be able to retrieve it in US 20 ms later, but it takes a minimum of 500 ms for data to travel from India to US.)


推荐阅读