Why can’t read preference be ‘secondary’ in a transaction?

Hello guys.

I have a question regarding read preference in a transaction.

Why can’t read preference be secondary when executing a transaction?

I noticed in the documentation that it should be set the ‘primary’ read preference.

In my code I tried to run the transaction with read preference ‘secondary’ to see the result.

The result was the following exception:
com.mongodb.MongoClientException: Read preference in a transaction must be primary

Why does it happen ? Why does it always need to be ‘primary’ in a transaction?

Regards,
Caio

Hi @morcelicaio

In a replica set (i.e. a distributed system), things are eventually consistent, except in the primary. The transaction realistically doesn’t get replicated to the secondaries until it’s committed.

I noticed in the documentation that it should be set the ‘primary’ read preference.

Not really “should”, but “must” :slight_smile: Please see Read Preference Use Cases for more details and examples.

Best regards
Kevin

1 Like

Hi @kevinadi .

I understand that the primary node receives the writes and then replicates to the secondary nodes.

The documentation doesn’t say anything about transactions other than using read preference ‘primary’.

That’s why I had this doubt.

What is the reason for not being able to execute a transaction with read preference ‘secondary’ ?

regards,
Caio

This was a deliberate design decision (see SERVER-33580). I’m not privy to all the technical details regarding this decision, but if I have to guess, allowing multi-document transactions on secondaries would be difficult from causality point of view, would be of lower performance, for not much gain in functionality since all writes must go to the primary anyway :slight_smile:

Best regards
Kevin

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.