Elffuss BraidHub

kikocis/java-driver public

3.1.x · 13.0 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 on 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
22You don't need to manage connections yourself. You simply interact with a `Session` object, which takes care of it.
23
24**For each `Session`, there is one connection pool per connected host** (a host is connected when it is up and
25not ignored by the [load balancing policy](../load_balancing)).
26
27The number of connections per pool is configurable (this will be
28described in the next section). The number of stream ids depends on the
29[native protocol version](../native_protocol/):
30
31* protocol v2 or below: 128 stream ids per connection.
32* protocol v3 or above: up to 32768 stream ids per connection.
33
34```ditaa
35+-------+1 n+-------+1 n+----+1 n+----------+1 128/32K+-------+
36|Cluster+-----+Session+-----+Pool+-----+Connection+-----------+Request+
37+-------+ +-------+ +----+ +----------+ +-------+
38```
39
40### Configuring the connection pool
41
42Connections pools are configured with a [PoolingOptions][pooling_options] object, which
43is global to a `Cluster` instance. You can pass that object when
44building the cluster:
45
46```java
47PoolingOptions poolingOptions = new PoolingOptions();
48// customize options...
49
50Cluster cluster = Cluster.builder()
51 .withContactPoints("127.0.0.1")
52 .withPoolingOptions(poolingOptions)
53 .build();
54```
55
56Most options can also be changed at runtime. If you don't have a
57reference to the `PoolingOptions` instance, here's how you can get it:
58
59```java
60PoolingOptions poolingOptions = cluster.getConfiguration().getPoolingOptions();
61// customize options...
62```
63
64#### Pool size
65
66Connection pools have a variable size, which gets adjusted automatically
67depending on the current load. There will always be at least a *core*
68number of connections, and at most a *max* number. These values can be
69configured independently by host *distance* (the distance is determined
70by your [LoadBalancingPolicy][lbp], and will generally indicate whether a
71host is in the same datacenter or not).
72
73```java
74poolingOptions
75 .setCoreConnectionsPerHost(HostDistance.LOCAL, 4)
76 .setMaxConnectionsPerHost( HostDistance.LOCAL, 10)
77 .setCoreConnectionsPerHost(HostDistance.REMOTE, 2)
78 .setMaxConnectionsPerHost( HostDistance.REMOTE, 4);
79```
80
81For convenience, core and max can be set simultaneously:
82
83```java
84poolingOptions
85 .setConnectionsPerHost(HostDistance.LOCAL, 4, 10)
86 .setConnectionsPerHost(HostDistance.REMOTE, 2, 4);
87```
88
89The default settings are:
90
91* protocol v2:
92 * `LOCAL` hosts: core = 2, max = 8
93 * `REMOTE` hosts: core = 1, max = 2
94* protocol v3:
95 * `LOCAL` hosts: core = max = 1
96 * `REMOTE` hosts: core = max = 1
97
98[PoolingOptions.setNewConnectionThreshold][nct] determines the threshold
99that triggers the creation of a new connection when the pool is not at
100its maximum capacity. In general, you shouldn't need to change its
101default value.
102
103#### Dynamic resizing
104
105If core != max, the pool will resize automatically to adjust to the
106current activity on the host.
107
108When activity goes up and there are *n* connections with n < max, the driver
109will add a connection when the number of concurrent requests is more than
110(n - 1) * 128 + [PoolingOptions.setNewConnectionThreshold][nct]
111(in layman's terms, when all but the last connection are full and the last
112connection is above the threshold).
113
114When activity goes down, the driver will "trash" connections if the maximum
115number of requests in a 10 second time period can be satisfied by less than
116the number of connections opened. Trashed connections are kept open but do
117not accept new requests. After a given timeout (defined by
118[PoolingOptions.setIdleTimeoutSeconds][sits]), trashed connections are closed
119and removed. If during that idle period activity increases again, those
120connections will be resurrected back into the active pool and reused. The
121main intent of that is to not constantly recreate connections if activity
122changes quickly over an interval.
123
124#### Simultaneous requests per connection
125
126[PoolingOptions.setMaxRequestsPerConnection][mrpc] allows you to
127throttle the number of concurrent requests per connection.
128
129With protocol v2, there is no reason to throttle. It is set to 128 (the
130max) and you should not change it.
131
132With protocol v3, it is set to 1024 for `LOCAL` hosts, and 256 for
133`REMOTE` hosts. These low defaults were chosen so that the default
134configuration for protocol v2 and v3 allow the same total number of
135simultaneous requests (to avoid bad surprises when clients migrate from
136v2 to v3). You can raise this threshold, or even set it to the max:
137
138```java
139poolingOptions
140 .setMaxRequestsPerConnection(HostDistance.LOCAL, 32768)
141 .setMaxRequestsPerConnection(HostDistance.REMOTE, 2000);
142```
143
144Just keep in mind that high values will give clients more bandwidth and
145therefore put more pressure on your cluster. This might require some
146tuning, especially if you have many clients.
147
148#### Heartbeat
149
150If connections stay idle for too long, they might be dropped by
151intermediate network devices (routers, firewalls...). Normally, TCP
152keepalive should take care of this; but tweaking low-level keepalive
153settings might be impractical in some environments.
154
155The driver provides application-side keepalive in the form of a
156connection heartbeat: when a connection has been idle for a given amount
157of time, the driver will simulate activity by writing a dummy request to
158it.
159
160This feature is enabled by default. The default heartbeat interval is 30
161seconds, it can be customized with the following method:
162
163```java
164poolingOptions.setHeartbeatIntervalSeconds(60);
165```
166
167If it gets changed at runtime, only connections created after that will
168use the new interval. Most users will want to do this at startup.
169
170The heartbeat interval should be set higher than
171[SocketOptions.readTimeoutMillis][rtm]:
172the read timeout is the maximum time that the driver waits for a regular
173query to complete, therefore the connection should not be considered
174idle before it has elapsed.
175
176To disable heartbeat, set the interval to 0.
177
178Implementation note: the dummy request sent by heartbeat is an
179[OPTIONS](https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v3.spec#L278)
180message.
181
182
183#### Acquisition queue
184
185When the driver tries to send a request to a host, it will first try to
186acquire a connection from this host's pool. If the pool is busy (i.e.
187all connections are already handling their maximum number of in flight
188requests), the acquisition attempt gets enqueued until a connection becomes
189available again.
190
191Two options control that queue: a maximum size ([PoolingOptions.setMaxQueueSize][smqs]) and a timeout
192([PoolingOptions.setPoolTimeoutMillis][sptm]).
193
194* if either option is set to zero, the attempt is rejected immediately;
195* else if more than `maxQueueSize` requests are already waiting for a connection, the attempt is also rejected;
196* otherwise, the attempt is enqueued; if a connection becomes available before `poolTimeoutMillis` has elapsed,
197 then the attempt succeeds, otherwise it is rejected.
198
199If the attempt is rejected, the driver will move to the next host in the [query plan](../load_balancing/#query-plan),
200and try to acquire a connection again.
201
202If all hosts are busy with a full queue, the request will fail with a
203[NoHostAvailableException][nhae]. If you inspect the map returns by this
204exception's [getErrors] method, you will see a [BusyPoolException] for
205each host.
206
207
208### Monitoring and tuning the pool
209
210The easiest way to monitor pool usage is with [Session.getState][get_state]. Here's
211a simple example that will print the number of open connections, active
212requests, and maximum capacity for each host, every 5 seconds:
213
214```java
215final LoadBalancingPolicy loadBalancingPolicy =
216 cluster.getConfiguration().getPolicies().getLoadBalancingPolicy();
217final PoolingOptions poolingOptions =
218cluster.getConfiguration().getPoolingOptions();
219
220ScheduledExecutorService scheduled =
221Executors.newScheduledThreadPool(1);
222scheduled.scheduleAtFixedRate(new Runnable() {
223 @Override
224 public void run() {
225 Session.State state = session.getState();
226 for (Host host : state.getConnectedHosts()) {
227 HostDistance distance = loadBalancingPolicy.distance(host);
228 int connections = state.getOpenConnections(host);
229 int inFlightQueries = state.getInFlightQueries(host);
230 System.out.printf("%s connections=%d, current load=%d, max
231load=%d%n",
232 host, connections, inFlightQueries,
233 connections *
234poolingOptions.getMaxRequestsPerConnection(distance));
235 }
236 }
237}, 5, 5, TimeUnit.SECONDS);
238```
239
240In real life, you'll probably want something more sophisticated, like
241exposing a JMX MBean or sending the data to your favorite monitoring
242tool.
243
244If you find that the current load stays close or equal to the maximum
245load at all time, it's a sign that your connection pools are saturated
246and you should raise the max connections per host, or max requests per
247connection (protocol v3).
248
249If you're using protocol v2 and the load is often less than core * 128,
250your pools are underused and you could get away with less core
251connections.
252
253#### Tuning protocol v3 for very high throughputs
254
255As mentioned above, the default pool size for protocol v3 is core = max
256= 1. This means all requests to a given node will share a single
257connection, and therefore a single Netty I/O thread.
258
259There is a corner case where this I/O thread can max out its CPU core
260and become a bottleneck in the driver; in our benchmarks, this happened
261with a single-node cluster and a high throughput (approximately 80K
262requests / second).
263
264It's unlikely that you'll run into this issue: in most real-world
265deployments, the driver connects to more than one node, so the load will
266spread across more I/O threads. However if you suspect that you
267experience the issue, here's what to look out for:
268
269* the driver throughput plateaus but the process does not appear to
270 max out any system resource (in particular, overall CPU usage is well
271 below 100%);
272* one of the driver's I/O threads maxes out its CPU core. You can see
273 that with a profiler, or OS-level tools like `pidstat -tu` on Linux.
274 I/O threads are called `<cluster_name>-nio-worker-<n>`, unless you're
275 injecting your own `EventLoopGroup` with `NettyOptions`.
276
277The solution is to add more connections per node. To ensure that
278additional connections get created before you run into the bottleneck,
279either:
280
281* set core = max;
282* keep core = 1, but adjust [maxRequestsPerConnection][mrpc] and
283 [newConnectionThreshold][nct] so that enough connections are added by
284 the time you reach the bottleneck.
285
286[result_set_future]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/ResultSetFuture.html
287[pooling_options]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html
288[lbp]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/LoadBalancingPolicy.html
289[nct]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setNewConnectionThreshold-com.datastax.driver.core.HostDistance-int-
290[mrpc]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setMaxRequestsPerConnection-com.datastax.driver.core.HostDistance-int-
291[sits]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setIdleTimeoutSeconds-int-
292[rtm]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SocketOptions.html#getReadTimeoutMillis--
293[smqs]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setMaxQueueSize-int-
294[sptm]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setPoolTimeoutMillis-int-
295[nhae]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/NoHostAvailableException.html
296[getErrors]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/NoHostAvailableException.html#getErrors--
297[get_state]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html#getState--
298[BusyPoolException]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/BusyPoolException.html