Elffuss BraidHub

kikocis/java-driver public

307a50ac64a5 · 12.6 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
191The size of that queue is controlled by [PoolingOptions.setMaxQueueSize][smqs].
192If the queue has already reached its limit, further attempts to acquire a
193connection will be rejected immediately: the driver will move on and try to
194acquire a connection from the next host's pool. The limit can be set to 0 to
195disable queueing entirely.
196
197If all hosts are busy with a full queue, the request will fail with a
198[NoHostAvailableException][nhae]. If you inspect the map returns by this
199exception's [getErrors] method, you will see a [BusyPoolException] for
200each host.
201
202
203### Monitoring and tuning the pool
204
205The easiest way to monitor pool usage is with [Session.getState][get_state]. Here's
206a simple example that will print the number of open connections, active
207requests, and maximum capacity for each host, every 5 seconds:
208
209```java
210final LoadBalancingPolicy loadBalancingPolicy =
211 cluster.getConfiguration().getPolicies().getLoadBalancingPolicy();
212final PoolingOptions poolingOptions =
213cluster.getConfiguration().getPoolingOptions();
214
215ScheduledExecutorService scheduled =
216Executors.newScheduledThreadPool(1);
217scheduled.scheduleAtFixedRate(new Runnable() {
218 @Override
219 public void run() {
220 Session.State state = session.getState();
221 for (Host host : state.getConnectedHosts()) {
222 HostDistance distance = loadBalancingPolicy.distance(host);
223 int connections = state.getOpenConnections(host);
224 int inFlightQueries = state.getInFlightQueries(host);
225 System.out.printf("%s connections=%d, current load=%d, max
226load=%d%n",
227 host, connections, inFlightQueries,
228 connections *
229poolingOptions.getMaxRequestsPerConnection(distance));
230 }
231 }
232}, 5, 5, TimeUnit.SECONDS);
233```
234
235In real life, you'll probably want something more sophisticated, like
236exposing a JMX MBean or sending the data to your favorite monitoring
237tool.
238
239If you find that the current load stays close or equal to the maximum
240load at all time, it's a sign that your connection pools are saturated
241and you should raise the max connections per host, or max requests per
242connection (protocol v3).
243
244If you're using protocol v2 and the load is often less than core * 128,
245your pools are underused and you could get away with less core
246connections.
247
248#### Tuning protocol v3 for very high throughputs
249
250As mentioned above, the default pool size for protocol v3 is core = max
251= 1. This means all requests to a given node will share a single
252connection, and therefore a single Netty I/O thread.
253
254There is a corner case where this I/O thread can max out its CPU core
255and become a bottleneck in the driver; in our benchmarks, this happened
256with a single-node cluster and a high throughput (approximately 80K
257requests / second).
258
259It's unlikely that you'll run into this issue: in most real-world
260deployments, the driver connects to more than one node, so the load will
261spread across more I/O threads. However if you suspect that you
262experience the issue, here's what to look out for:
263
264* the driver throughput plateaus but the process does not appear to
265 max out any system resource (in particular, overall CPU usage is well
266 below 100%);
267* one of the driver's I/O threads maxes out its CPU core. You can see
268 that with a profiler, or OS-level tools like `pidstat -tu` on Linux.
269 I/O threads are called `<cluster_name>-nio-worker-<n>`, unless you're
270 injecting your own `EventLoopGroup` with `NettyOptions`.
271
272The solution is to add more connections per node. To ensure that
273additional connections get created before you run into the bottleneck,
274either:
275
276* set core = max;
277* keep core = 1, but adjust [maxRequestsPerConnection][mrpc] and
278 [newConnectionThreshold][nct] so that enough connections are added by
279 the time you reach the bottleneck.
280
281[result_set_future]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/ResultSetFuture.html
282[pooling_options]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html
283[lbp]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/LoadBalancingPolicy.html
284[nct]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setNewConnectionThreshold-com.datastax.driver.core.HostDistance-int-
285[mrpc]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setMaxRequestsPerConnection-com.datastax.driver.core.HostDistance-int-
286[sits]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setIdleTimeoutSeconds-int-
287[rtm]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SocketOptions.html#getReadTimeoutMillis--
288[smqs]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setMaxQueueSize-int-
289[nhae]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/NoHostAvailableException.html
290[getErrors]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/NoHostAvailableException.html#getErrors--
291[get_state]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html#getState--
292[BusyPoolException]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/BusyPoolException.html