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?

Obaid Maroof
  • 1,523
  • 2
  • 19
  • 40

1 Answers1

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.

Community
  • 1
  • 1
Gergely Bacso
  • 14,243
  • 2
  • 44
  • 64
  • 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. – Obaid Maroof Feb 23 '16 at 11:09
  • You can temporarily enable trace log on org.hibernate . It is a bit verbose, but does the job. – Gergely Bacso Feb 23 '16 at 11:13
  • 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. – Markus W Mahlberg Feb 23 '16 at 13:09