Read-after-write Consistency in MongoDB
In this article, I will describe how to achieve read-after-write consistency in MongoDB. The problem what we want to solve is:
- A collection maintains profiles.
- After we insert a new profile, we want to retrieve the top 20 ordered by some criteria in the same function.
- We find the newest profile is always not been found.
Our MongoDB client's configuration is almost default with a connection string,
We want to make the query always comes from the primary, so we try to assign a session-level read preference to
primary. The official manual shows the collection-level preference can overwrite the client-level one.
However, it does not work.
After consulting the MongoDB solution architect, we find the default read concern is
local which doesn't guarantee the operation order. Thus, the solution is not only changing the read concern to
majority but also changing the write concern to
Then, the problem is resolved.
By the way, the solution is a little complicated than MySQL does. If we use MySQL as one primary and two replicas, we can switch the read operation from a replica to the primary to ensure read-after-write consistency. On the other hand, MongoDB is designed to face the scene of large-volume data, he has to do more to balance the efficiency and functionality. Thus, in addition to configuring the read preference, using read concern and write concern are also essential.