4

I have got a small mongoDB cluster with 3 nodes (no sharding, only replication). Now the insertion to the primary node is propogating the new data to the secondary node as expected (basic replication). I am using java and hibernate.

Now what I want is to loadbalance the read requests among the whole replica set instead of primary node always being used to serve the data. Is there some way that I tell hibernate (through query string) about the available servers and somehow hibernate distributes the request (either randomly or in a systematic manner)? What would be the right way to achieve load balancing?

1 Answer 1

1

The setting you are looking for is called read-preference. If you take a look at the doc here, you will find:

hibernate.ogm.mongodb.read_preference

Specifies the ReadPreference to be applied when issuing reads against the MongoDB datastore. Possible settings are (values of the ReadPreferenceType enum): PRIMARY, PRIMARY_PREFERRED, SECONDARY, SECONDARY_PREFERRED and NEAREST.

What you would probably use in this case is SECONDARY_PREFERRED, which effectively means that read operation will by default routed to slave nodes, but hibernate will fall back to primary if that is the only available node left.

Sign up to request clarification or add additional context in comments.

3 Comments

Looks promising, gonna give it a try. Any idea how I could log the hostname for hibernate read operation? Just wanted to cross confirm that setting this property is actually reading the data from the secondary node.
You can temporarily enable trace log on org.hibernate . It is a bit verbose, but does the job.
What is missing here is that depending on the write concern reads from the secondaries do not necessarily return the same data as a read from a primary would. Replication only provides eventual consistency.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.