Elffuss BraidHub

kikocis/java-driver public

a542c0877cae · 9.7 KiBRenderedRawPermalink
1## Connection pooling
2
3### Basics
4
5The driver communicates with Cassandra over TCP, using the Cassandra
6binary protocol. This protocol is asynchronous, which allows each TCP
7connection to handle multiple simultaneous requests:
8
9* when a query gets executed, a *stream id* gets assigned to it. It is a
10 unique identifier for the current connection;
11* the driver writes a request containing the stream id and the query on
12 the connection, and then proceeds without waiting for the response (if
13 you're using the asynchronous API, this is when the driver will send you
14 back a [ResultSetFuture][result_set_future]).
15 Once the request has been written to the
16 connection, we say that it is *in flight*;
17* at some point, Cassandra will send back a response on the connection.
18 This response also contains the stream id, which allows the driver to
19 trigger a callback that will complete the corresponding query (this is
20 the point where your `ResultSetFuture` will get completed).
21
22To increase the number of concurrent requests, we use a pool of
23connections to each host. **For each `Session` object, there is one
24connection pool per connected host**.
25
26The number of connections per pool is configurable (this will be
27described in the next section). The number of stream ids depends on the
28[native protocol version](../native_protocol/):
29
30* protocol v2 or below: 128 stream ids per connection.
31* protocol v3 or above: up to 32768 stream ids per connection.
32
33```ditaa
34+-------+1 n+-------+1 n+----+1 n+----------+1 128/32K+-------+
35|Cluster+-----+Session+-----+Pool+-----+Connection+-----------+Request+
36+-------+ +-------+ +----+ +----------+ +-------+
37```
38
39### Configuring the connection pool
40
41Connections pools are configured with a [PoolingOptions][pooling_options] object, which
42is global to a `Cluster` instance. You can pass that object when
43building the cluster:
44
45```java
46PoolingOptions poolingOptions = new PoolingOptions();
47// customize options...
48
49Cluster cluster = Cluster.builder()
50 .withContactPoints("127.0.0.1")
51 .withPoolingOptions(poolingOptions)
52 .build();
53```
54
55Most options can also be changed at runtime. If you don't have a
56reference to the `PoolingOptions` instance, here's how you can get it:
57
58```java
59PoolingOptions poolingOptions = cluster.getConfiguration().getPoolingOptions();
60// customize options...
61```
62
63#### Pool size
64
65Connection pools have a variable size, which gets adjusted automatically
66depending on the current load. There will always be at least a *core*
67number of connections, and at most a *max* number. These values can be
68configured independently by host *distance* (the distance is determined
69by your [LoadBalancingPolicy][lbp], and will generally indicate whether a
70host is in the same datacenter or not).
71
72```java
73poolingOptions
74 .setCoreConnectionsPerHost(HostDistance.LOCAL, 4)
75 .setMaxConnectionsPerHost( HostDistance.LOCAL, 10)
76 .setCoreConnectionsPerHost(HostDistance.REMOTE, 2)
77 .setMaxConnectionsPerHost( HostDistance.REMOTE, 4);
78```
79
80For convenience, core and max can be set simultaneously:
81
82```java
83poolingOptions
84 .setConnectionsPerHost(HostDistance.LOCAL, 4, 10)
85 .setConnectionsPerHost(HostDistance.REMOTE, 2, 4);
86```
87
88The default settings are:
89
90* protocol v2:
91 * `LOCAL` hosts: core = 2, max = 8
92 * `REMOTE` hosts: core = 1, max = 2
93* protocol v3:
94 * `LOCAL` hosts: core = max = 1
95 * `REMOTE` hosts: core = max = 1
96
97[PoolingOptions.setNewConnectionThreshold][nct] determines the threshold
98that triggers the creation of a new connection when the pool is not at
99its maximum capacity. In general, you shouldn't need to change its
100default value.
101
102#### Simultaneous requests per connection
103
104[PoolingOptions.setMaxRequestsPerConnection][mrpc] allows you to
105throttle the number of concurrent requests per connection.
106
107With protocol v2, there is no reason to throttle. It is set to 128 (the
108max) and you should not change it.
109
110With protocol v3, it is set to 1024 for `LOCAL` hosts, and 256 for
111`REMOTE` hosts. These low defaults were chosen so that the default
112configuration for protocol v2 and v3 allow the same total number of
113simultaneous requests (to avoid bad surprises when clients migrate from
114v2 to v3). You can raise this threshold, or even set it to the max:
115
116```java
117poolingOptions
118 .setMaxRequestsPerConnection(HostDistance.LOCAL, 32768)
119 .setMaxRequestsPerConnection(HostDistance.REMOTE, 2000);
120```
121
122Just keep in mind that high values will give clients more bandwidth and
123therefore put more pressure on your cluster. This might require some
124tuning, especially if you have many clients.
125
126#### Heartbeat
127
128If connections stay idle for too long, they might be dropped by
129intermediate network devices (routers, firewalls...). Normally, TCP
130keepalive should take care of this; but tweaking low-level keepalive
131settings might be impractical in some environments.
132
133The driver provides application-side keepalive in the form of a
134connection heartbeat: when a connection has been idle for a given amount
135of time, the driver will simulate activity by writing a dummy request to
136it.
137
138This feature is enabled by default. The default heartbeat interval is 30
139seconds, it can be customized with the following method:
140
141```java
142poolingOptions.setHeartbeatIntervalSeconds(60);
143```
144
145If it gets changed at runtime, only connections created after that will
146use the new interval. Most users will want to do this at startup.
147
148The heartbeat interval should be set higher than
149[SocketOptions.readTimeoutMillis][rtm]:
150the read timeout is the maximum time that the driver waits for a regular
151query to complete, therefore the connection should not be considered
152idle before it has elapsed.
153
154To disable heartbeat, set the interval to 0.
155
156Implementation note: the dummy request sent by heartbeat is an
157[OPTIONS](https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v3.spec#L278)
158message.
159
160
161#### Acquisition timeout
162
163When the driver tries to send a request to a host, it will first try to
164acquire a connection from this host's pool. If the pool is busy (i.e.
165all connections are already handling their maximum number of in flight
166requests), the client thread will block for a while, until a connection
167becomes available (note that this will block even if you're using the
168asynchronous API, like [Session.executeAsync][exec_async]).
169
170The time that the driver blocks is controlled by
171[PoolingOptions.setPoolTimeoutMillis][ptm]. If there is still no connection
172available after this timeout, the driver will try the next host.
173
174For some applications, blocking is not acceptable, and it is preferable
175to fail fast if the request cannot be fulfilled. If that's your case,
176set the pool timeout to 0. If all hosts are busy, you will get a
177[NoHostAvailableException][nhae] (if you look at the exception's details, you
178will see a `java.util.concurrent.TimeoutException` for each host).
179
180
181### Monitoring and tuning the pool
182
183The easiest way to monitor pool usage is with [Session.getState][get_state]. Here's
184a simple example that will print the number of open connections, active
185requests, and maximum capacity for each host, every 5 seconds:
186
187```java
188final LoadBalancingPolicy loadBalancingPolicy =
189 cluster.getConfiguration().getPolicies().getLoadBalancingPolicy();
190final PoolingOptions poolingOptions =
191cluster.getConfiguration().getPoolingOptions();
192
193ScheduledExecutorService scheduled =
194Executors.newScheduledThreadPool(1);
195scheduled.scheduleAtFixedRate(new Runnable() {
196 @Override
197 public void run() {
198 Session.State state = session.getState();
199 for (Host host : state.getConnectedHosts()) {
200 HostDistance distance = loadBalancingPolicy.distance(host);
201 int connections = state.getOpenConnections(host);
202 int inFlightQueries = state.getInFlightQueries(host);
203 System.out.printf("%s connections=%d, current load=%d, max
204load=%d%n",
205 host, connections, inFlightQueries,
206 connections *
207poolingOptions.getMaxRequestsPerConnection(distance));
208 }
209 }
210}, 5, 5, TimeUnit.SECONDS);
211```
212
213In real life, you'll probably want something more sophisticated, like
214exposing a JMX MBean or sending the data to your favorite monitoring
215tool.
216
217If you find that the current load stays close or equal to the maximum
218load at all time, it's a sign that your connection pools are saturated
219and you should raise the max connections per host, or max requests per
220connection (protocol v3).
221
222If you're using protocol v2 and the load is often less than core * 128,
223your pools are underused and you could get away with less core
224connections.
225
226[result_set_future]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/ResultSetFuture.html
227[pooling_options]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/PoolingOptions.html
228[lbp]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/policies/LoadBalancingPolicy.html
229[nct]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/PoolingOptions.html#setNewConnectionThreshold(com.datastax.driver.core.HostDistance,%20int)
230[mrpc]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/PoolingOptions.html#setMaxRequestsPerConnection(com.datastax.driver.core.HostDistance,%20int)
231[rtm]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/SocketOptions.html#getReadTimeoutMillis()
232[exec_async]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Session.html#executeAsync(com.datastax.driver.core.Statement)
233[ptm]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/PoolingOptions.html#setPoolTimeoutMillis(int)
234[nhae]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/exceptions/NoHostAvailableException.html
235[get_state]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Session.html#getState()