Skip to content

Commit 590e6f0

Browse files
committed
DOCSP-47048: Configure replica set operations
1 parent 79722ed commit 590e6f0

File tree

3 files changed

+438
-0
lines changed

3 files changed

+438
-0
lines changed

source/connection.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ Connection Guide
1111
MongoClient Settings </connection/mongoclientsettings>
1212
Stable API </connection/stable-api>
1313
Network Compression </connection/network-compression>
14+
Operations on Replica Sets </connection/read-write-config>
1415
JNDI Datasource </connection/jndi>
1516
Connection Troubleshooting </connection/connection-troubleshooting>
1617
AWS Lambda <https://www.mongodb.com/docs/atlas/manage-connections-aws-lambda/>
Lines changed: 330 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,330 @@
1+
.. _java-configure-replica-sets:
2+
3+
====================================
4+
Configure Operations on Replica Sets
5+
====================================
6+
7+
.. facet::
8+
:name: genre
9+
:values: reference
10+
11+
.. meta::
12+
:keywords: customize, preferences, replica set, consistency
13+
14+
.. contents:: On this page
15+
:local:
16+
:backlinks: none
17+
:depth: 2
18+
:class: singlecol
19+
20+
Overview
21+
--------
22+
23+
In this guide, you can learn how to configure **write concern**, **read concern**,
24+
and **read preference** options to modify the way that the {+driver-short+} runs
25+
read and write operations on replica sets.
26+
27+
Read and Write Settings Precedence
28+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
29+
30+
You can set write concern, read concern, and read preference options at the following
31+
levels:
32+
33+
- Client, which sets the *default for all operation executions* unless overridden
34+
- Transaction
35+
- Database
36+
- Collection
37+
38+
This list also indicates the increasing order of precedence of the option settings. For
39+
example, if you set a read concern level for a transaction, it will override a read
40+
concern level inherited from the client.
41+
42+
Write concern, read concern, and read preference options allow you to customize the
43+
causal consistency and availability of the data in your replica sets. To see a full
44+
list of these options, see the following guides in the {+mdb-server+} manual:
45+
46+
- :manual:`Read Preference </core/read-preference/>`
47+
- :manual:`Read Concern </reference/read-concern/>`
48+
- :manual:`Write Concern </reference/write-concern/>`
49+
50+
.. _java-read-write-config:
51+
52+
Configure Read and Write Operations
53+
-----------------------------------
54+
55+
You can control how the driver routes read operations among replica set members
56+
by setting a read preference. You can also control how the driver waits for
57+
acknowledgment of read and write operations on a replica set by setting read and
58+
write concerns.
59+
60+
The following sections show how to configure these read and write settings
61+
at various levels.
62+
63+
.. _java-read-write-client:
64+
65+
Client Configuration
66+
~~~~~~~~~~~~~~~~~~~~
67+
68+
This example shows how to set the read preference, read concern, and
69+
write concern of a ``MongoClient`` instance by passing a ``MongoClientSettings``
70+
instance to the constructor. The code configures the following settings:
71+
72+
- ``secondary`` read preference: Read operations retrieve data from
73+
secondary replica set members.
74+
- ``LOCAL`` read concern: Read operations return the instance's most recent data
75+
without guaranteeing that the data has been written to a majority of the replica
76+
set members.
77+
- ``W2`` write concern: The primary replica set member and one secondary member
78+
must acknowledge the write operation.
79+
80+
.. literalinclude:: /includes/connect/ReplicaSets.java
81+
:language: java
82+
:dedent:
83+
:start-after: start-client-settings
84+
:end-before: end-client-settings
85+
86+
Alternatively, you can specify the read and write settings in the connection
87+
URI, which is passed as a parameter to the ``MongoClient`` constructor:
88+
89+
.. literalinclude:: /includes/connect/ReplicaSets.java
90+
:language: java
91+
:dedent:
92+
:start-after: start-client-settings-uri
93+
:end-before: end-client-settings-uri
94+
95+
.. _java-read-write-transaction:
96+
97+
Transaction Configuration
98+
~~~~~~~~~~~~~~~~~~~~~~~~~
99+
100+
This example shows how to set the read preference, read concern, and
101+
write concern of a transaction by passing a ``TransactionOptions``
102+
instance to the ``startTransaction()`` method. Transactions run within
103+
**sessions**, which are groupings of related read or write operations that you
104+
intend to run sequentially. Before applying the transaction options, create a
105+
``ClientSession`` instance to start a session.
106+
107+
.. tip::
108+
109+
To learn more about sessions, see :manual:`Server Sessions </reference/server-sessions/>`
110+
in the {+mdb-server+} manual.
111+
112+
The example configures the following settings:
113+
114+
- ``primary`` read preference: Read operations retrieve data from
115+
the primary replica set member.
116+
- ``MAJORITY`` read concern: Read operations return the instance's most recent data
117+
that has been written to a majority of replica set members.
118+
- ``W1`` write concern: The primary replica set member must acknowledge the
119+
write operation.
120+
121+
.. literalinclude:: /includes/connect/ReplicaSets.java
122+
:language: java
123+
:dedent:
124+
:start-after: start-transaction-settings
125+
:end-before: end-transaction-settings
126+
127+
.. _java-read-write-database:
128+
129+
Database Configuration
130+
~~~~~~~~~~~~~~~~~~~~~~
131+
132+
This example shows how to set the read preference, read concern, and
133+
write concern of a database called ``test_database`` by chaining setter
134+
methods to the ``getDatabase()`` method. The code configures the following
135+
settings:
136+
137+
- ``primaryPreferred`` read preference: Read operations retrieve data from
138+
the primary replica set member, or secondary members if the primary is unavailable.
139+
- ``AVAILABLE`` read concern: Read operations return the instance's most recent data
140+
without guaranteeing that the data has been written to a majority of the replica
141+
set members.
142+
- ``MAJORITY`` write concern: The majority of all replica set members
143+
must acknowledge the write operation.
144+
145+
.. literalinclude:: /includes/connect/ReplicaSets.java
146+
:language: java
147+
:dedent:
148+
:start-after: start-database-settings
149+
:end-before: end-database-settings
150+
151+
.. _java-read-write-collection:
152+
153+
Collection Configuration
154+
~~~~~~~~~~~~~~~~~~~~~~~~
155+
156+
This example shows how to set the read preference, read concern, and
157+
write concern of a collection called ``test_collection`` by chaining setter
158+
methods to the ``getCollection()`` method. The code configures the following
159+
settings:
160+
161+
- ``secondaryPreferred`` read preference: Read operations retrieve data from
162+
secondary replica set members, or the primary members if no secondary members are
163+
available.
164+
- ``AVAILABLE`` read concern: Read operations return the instance's most recent data
165+
without guaranteeing that the data has been written to a majority of the replica
166+
set members.
167+
- ``UNACKNOWLEDGED`` write concern: Replica set members do not need to acknowledge
168+
the write operation.
169+
170+
.. literalinclude:: /includes/connect/ReplicaSets.java
171+
:language: java
172+
:dedent:
173+
:start-after: start-collection-settings
174+
:end-before: end-collection-settings
175+
176+
.. _java-read-write-advanced:
177+
178+
Advanced Read Configurations
179+
----------------------------
180+
181+
The following sections describe ways to further customize how the {+driver-short+}
182+
routes read operations.
183+
184+
.. _java-sharded-clusters:
185+
186+
Sharded Clusters
187+
~~~~~~~~~~~~~~~~
188+
189+
You can specify a read preference when connecting to a sharded cluster.
190+
MongoDB uses sharding to distribute large amounts of data across
191+
multiple servers. A sharded cluster, or the set of nodes in a sharded deployment,
192+
includes the following components:
193+
194+
- **Shard**: A replica set that contains a subset of the sharded data.
195+
- **Mongos**: A query router that provides an interface between your
196+
application and the sharded cluster.
197+
- **Config servers**: Servers that store the cluster's configuration settings
198+
and metadata.
199+
200+
.. tip::
201+
202+
To learn more about sharded clusters, see :manual:`Sharding </sharding/>`
203+
in the {+mdb-server+} manual.
204+
205+
When reading from the replica set shards, mongos applies your specified read
206+
preference. The read preference is re-evaluated for each operation.
207+
208+
The following example shows how to connect to a sharded cluster and specify a
209+
``secondary`` read preference in your connection string:
210+
211+
.. literalinclude:: /includes/connect/ReplicaSets.java
212+
:language: java
213+
:dedent:
214+
:start-after: start-sharded-cluster-uri
215+
:end-before: end-sharded-cluster-uri
216+
217+
Load Balancing
218+
``````````````
219+
220+
If there is more than one mongos instance in the connection seed list, the
221+
{+driver-short+} uses **load balancing**. Load balancing allows the driver to
222+
distribute read and write requests across multiple servers, which avoids overwhelming
223+
one server in the sharded cluster and ensures optimal performance.
224+
225+
To distribute database requests, the {+driver-short+} determines the closest mongos
226+
by calculating which one has the lowest network round-trip time. Then, the driver
227+
determines the latency window by adding this mongos's average round-trip time to the
228+
``localThresholdMS`` value. The driver load balances data randomly across the mongos
229+
instances that fall within the latency window.
230+
231+
.. tip::
232+
233+
To learn more about load balancing, see :manual:`Sharded Cluster Balancer </core/sharding-balancer-administration/>`
234+
in the {+mdb-server+} manual.
235+
236+
.. _java-tag-sets:
237+
238+
Tag Sets
239+
~~~~~~~~
240+
241+
In {+mdb-server+}, you can apply key-value :manual:`tags
242+
</core/read-preference-tags/>` to replica set members
243+
according to any criteria you choose. You can then use those
244+
tags to target one or more members for a read operation.
245+
246+
By default, the {+driver-short+} ignores tags when choosing a member
247+
to read from. To instruct the {+driver-short+} to prefer certain tags,
248+
pass the tags as a list to your read preference setter method.
249+
250+
Suppose you are connected to a replica set that contains members hosted
251+
at multiple data centers across the United States. You want the driver to
252+
prefer reads from secondary replica set members in the following order:
253+
254+
1. Members from the New York data center, tagged with ``("dc", "ny")``
255+
#. Members from the San Francisco data center, tagged with ``("dc", "sf")``
256+
#. Any secondary members
257+
258+
This code example passes a list of tags representing the preceding replica
259+
set members to the ``ReadPreference.secondary()`` setter method. Then, the code
260+
passes the read preference information to the ``withReadPreference()`` method
261+
to set the read order on the database:
262+
263+
.. literalinclude:: /includes/connect/ReplicaSets.java
264+
:language: java
265+
:dedent:
266+
:start-after: start-tag-set
267+
:end-before: end-tag-set
268+
269+
.. _java-local-threshold:
270+
271+
Local Threshold
272+
~~~~~~~~~~~~~~~
273+
274+
If multiple replica set members match the read preference and tag sets that you specify,
275+
the {+driver-short+} reads from the nearest replica set members, chosen according to
276+
their ping time.
277+
278+
By default, the driver uses only members whose ping times are within 15 milliseconds
279+
of the nearest member for queries. To distribute reads among members with
280+
higher latencies, set the ``localThreshold`` option in a ``MongoClientSettings``
281+
instance or the ``localThresholdMS`` option in your connection URI.
282+
283+
The following example specifies a local threshold of 35 milliseconds. Select
284+
the :guilabel:`MongoClientSettings` or :guilabel:`Connection URI` tab to see
285+
corresponding code for each approach:
286+
287+
.. tabs::
288+
289+
.. tab:: MongoClientSettings
290+
:tabid: settings
291+
292+
.. literalinclude:: /includes/connect/ReplicaSets.java
293+
:language: rust
294+
:dedent:
295+
:start-after: start-local-threshold-settings
296+
:end-before: end-local-threshold-settings
297+
298+
299+
.. tab:: Connection URI
300+
:tabid: uri
301+
302+
.. literalinclude:: /includes/connect/ReplicaSets.java
303+
:language: rust
304+
:dedent:
305+
:start-after: start-local-threshold-uri
306+
:end-before: end-local-threshold-uri
307+
308+
In the preceding example, the {+driver-short+} distributes reads among matching members
309+
within 35 milliseconds of the closest member's ping time.
310+
311+
.. note::
312+
313+
The {+driver-short+} ignores the ``localThresholdMS`` option when communicating with a
314+
replica set through a ``mongos`` instance. In this case, use the
315+
:manual:`localThreshold </reference/program/mongos/#std-option-mongos.--localThreshold>`
316+
command-line option.
317+
318+
API Documentation
319+
-----------------
320+
321+
To learn more about any of the methods or types discussed in this
322+
guide, see the following API documentation:
323+
324+
- `MongoClient <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoClient.html>`__
325+
- `MongoClientSettings <{+api+}/apidocs/mongodb-driver-core/com/mongodb/MongoClientSettings.html>`__
326+
- `TransactionOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/TransactionOptions.html>`_
327+
- `startTransaction() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/ClientSession.html#startTransaction()>`_
328+
- `MongoDatabase <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoDatabase.html>`__
329+
- `MongoCollection <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html>`__
330+
- `TagSet <{+api+}/apidocs/mongodb-driver-core/com/mongodb/TagSet.html>`_

0 commit comments

Comments
 (0)