Elffuss BraidHub

kikocis/java-driver public

e8155ea1ae8d · 12.3 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
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#### Dynamic resizing
103
104If core != max, the pool will resize automatically to adjust to the
105current activity on the host.
106
107When activity goes up and there are *n* connections with n < max, the driver
108will add a connection when the number of concurrent requests is more than
109(n - 1) * 128 + [PoolingOptions.setNewConnectionThreshold][nct]
110(in layman's terms, when all but the last connection are full and the last
111connection is above the threshold).
112
113When activity goes down, the driver will "trash" connections if the maximum
114number of requests in a 10 second time period can be satisfied by less than
115the number of connections opened. Trashed connections are kept open but do
116not accept new requests. After a given timeout (defined by
117[PoolingOptions.setIdleTimeoutSeconds][sits]), trashed connections are closed
118and removed. If during that idle period activity increases again, those
119connections will be resurrected back into the active pool and reused. The
120main intent of that is to not constantly recreate connections if activity
121changes quickly over an interval.
122
123#### Simultaneous requests per connection
124
125[PoolingOptions.setMaxRequestsPerConnection][mrpc] allows you to
126throttle the number of concurrent requests per connection.
127
128With protocol v2, there is no reason to throttle. It is set to 128 (the
129max) and you should not change it.
130
131With protocol v3, it is set to 1024 for `LOCAL` hosts, and 256 for
132`REMOTE` hosts. These low defaults were chosen so that the default
133configuration for protocol v2 and v3 allow the same total number of
134simultaneous requests (to avoid bad surprises when clients migrate from
135v2 to v3). You can raise this threshold, or even set it to the max:
136
137```java
138poolingOptions
139 .setMaxRequestsPerConnection(HostDistance.LOCAL, 32768)
140 .setMaxRequestsPerConnection(HostDistance.REMOTE, 2000);
141```
142
143Just keep in mind that high values will give clients more bandwidth and
144therefore put more pressure on your cluster. This might require some
145tuning, especially if you have many clients.
146
147#### Heartbeat
148
149If connections stay idle for too long, they might be dropped by
150intermediate network devices (routers, firewalls...). Normally, TCP
151keepalive should take care of this; but tweaking low-level keepalive
152settings might be impractical in some environments.
153
154The driver provides application-side keepalive in the form of a
155connection heartbeat: when a connection has been idle for a given amount
156of time, the driver will simulate activity by writing a dummy request to
157it.
158
159This feature is enabled by default. The default heartbeat interval is 30
160seconds, it can be customized with the following method:
161
162```java
163poolingOptions.setHeartbeatIntervalSeconds(60);
164```
165
166If it gets changed at runtime, only connections created after that will
167use the new interval. Most users will want to do this at startup.
168
169The heartbeat interval should be set higher than
170[SocketOptions.readTimeoutMillis][rtm]:
171the read timeout is the maximum time that the driver waits for a regular
172query to complete, therefore the connection should not be considered
173idle before it has elapsed.
174
175To disable heartbeat, set the interval to 0.
176
177Implementation note: the dummy request sent by heartbeat is an
178[OPTIONS](https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v3.spec#L278)
179message.
180
181
182#### Acquisition timeout
183
184When the driver tries to send a request to a host, it will first try to
185acquire a connection from this host's pool. If the pool is busy (i.e.
186all connections are already handling their maximum number of in flight
187requests), the client thread will block for a while, until a connection
188becomes available (note that this will block even if you're using the
189asynchronous API, like [Session.executeAsync][exec_async]).
190
191The time that the driver blocks is controlled by
192[PoolingOptions.setPoolTimeoutMillis][ptm]. If there is still no connection
193available after this timeout, the driver will try the next host.
194
195For some applications, blocking is not acceptable, and it is preferable
196to fail fast if the request cannot be fulfilled. If that's your case,
197set the pool timeout to 0. If all hosts are busy, you will get a
198[NoHostAvailableException][nhae] (if you look at the exception's details, you
199will see a `java.util.concurrent.TimeoutException` for each host).
200
201
202### Monitoring and tuning the pool
203
204The easiest way to monitor pool usage is with [Session.getState][get_state]. Here's
205a simple example that will print the number of open connections, active
206requests, and maximum capacity for each host, every 5 seconds:
207
208```java
209final LoadBalancingPolicy loadBalancingPolicy =
210 cluster.getConfiguration().getPolicies().getLoadBalancingPolicy();
211final PoolingOptions poolingOptions =
212cluster.getConfiguration().getPoolingOptions();
213
214ScheduledExecutorService scheduled =
215Executors.newScheduledThreadPool(1);
216scheduled.scheduleAtFixedRate(new Runnable() {
217 @Override
218 public void run() {
219 Session.State state = session.getState();
220 for (Host host : state.getConnectedHosts()) {
221 HostDistance distance = loadBalancingPolicy.distance(host);
222 int connections = state.getOpenConnections(host);
223 int inFlightQueries = state.getInFlightQueries(host);
224 System.out.printf("%s connections=%d, current load=%d, max
225load=%d%n",
226 host, connections, inFlightQueries,
227 connections *
228poolingOptions.getMaxRequestsPerConnection(distance));
229 }
230 }
231}, 5, 5, TimeUnit.SECONDS);
232```
233
234In real life, you'll probably want something more sophisticated, like
235exposing a JMX MBean or sending the data to your favorite monitoring
236tool.
237
238If you find that the current load stays close or equal to the maximum
239load at all time, it's a sign that your connection pools are saturated
240and you should raise the max connections per host, or max requests per
241connection (protocol v3).
242
243If you're using protocol v2 and the load is often less than core * 128,
244your pools are underused and you could get away with less core
245connections.
246
247#### Tuning protocol v3 for very high throughputs
248
249As mentioned above, the default pool size for protocol v3 is core = max
250= 1. This means all requests to a given node will share a single
251connection, and therefore a single Netty I/O thread.
252
253There is a corner case where this I/O thread can max out its CPU core
254and become a bottleneck in the driver; in our benchmarks, this happened
255with a single-node cluster and a high throughput (approximately 80K
256requests / second).
257
258It's unlikely that you'll run into this issue: in most real-world
259deployments, the driver connects to more than one node, so the load will
260spread across more I/O threads. However if you suspect that you
261experience the issue, here's what to look out for:
262
263* the driver throughput plateaus but the process does not appear to
264 max out any system resource (in particular, overall CPU usage is well
265 below 100%);
266* one of the driver's I/O threads maxes out its CPU core. You can see
267 that with a profiler, or OS-level tools like `pidstat -tu` on Linux.
268 I/O threads are called `<cluster_name>-nio-worker-<n>`, unless you're
269 injecting your own `EventLoopGroup` with `NettyOptions`.
270
271The solution is to add more connections per node. To ensure that
272additional connections get created before you run into the bottleneck,
273either:
274
275* set core = max;
276* keep core = 1, but adjust [maxRequestsPerConnection][mrpc] and
277 [newConnectionThreshold][nct] so that enough connections are added by
278 the time you reach the bottleneck.
279
280[result_set_future]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/ResultSetFuture.html
281[pooling_options]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html
282[lbp]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/LoadBalancingPolicy.html
283[nct]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setNewConnectionThreshold-com.datastax.driver.core.HostDistance-int-
284[mrpc]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setMaxRequestsPerConnection-com.datastax.driver.core.HostDistance-int-
285[sits]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setIdleTimeoutSeconds-int-
286[rtm]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SocketOptions.html#getReadTimeoutMillis--
287[exec_async]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html#executeAsync-com.datastax.driver.core.Statement-
288[ptm]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setPoolTimeoutMillis-int-
289[nhae]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/NoHostAvailableException.html
290[get_state]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html#getState--