Elffuss BraidHub

kikocis/java-driver public

c98c3588aecb · 8.2 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
22Version 2.0.x of the driver uses version 1 of the binary protocol when
23connecting to Cassandra 1.2, and version 2 when connecting to Cassandra
242.0 or higher. In both cases, that gives you **128 stream ids per
25connection**.
26
27Because the number of stream ids per connection is limited, we use a
28pool with multiple connections to each host. **For each `Session`
29object, there is one connection pool per connected host**. The number of
30connections per pool depends on the configuration, this will be
31described in the next section.
32
33```ditaa
34+-------+1 n+-------+1 n+----+1 n+----------+1 128+-------+
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
80Note: the setters always enforce core <= max, which can get annoying
81when you try to set both values at once.
82[JAVA-662](https://datastax-oss.atlassian.net/browse/JAVA-662) will
83address this issue.
84
85[PoolingOptions.setMaxSimultaneousRequestsPerConnectionThreshold][msrpct]
86has a slightly misleading name: it does not limit the number of requests per
87connection, but only determines the threshold that triggers the creation
88of a new connection when the pool is not at its maximum capacity. In
89general, you shouldn't have to change its default value.
90
91
92#### Heartbeat
93
94If connections stay idle for too long, they might be dropped by
95intermediate network devices (routers, firewalls...). Normally, TCP
96keepalive should take care of this; but tweaking low-level keepalive
97settings might be impractical in some environments.
98
99The driver provides application-side keepalive in the form of a
100connection heartbeat: when a connection has been idle for a given amount
101of time, the driver will simulate activity by writing a dummy request to
102it.
103
104This feature is enabled by default. The default heartbeat interval is 30
105seconds, it can be customized with the following method:
106
107```java
108poolingOptions.setHeartbeatIntervalSeconds(60);
109```
110
111If it gets changed at runtime, only connections created after that will
112use the new interval. Most users will want to do this at startup.
113
114The heartbeat interval should be set higher than
115[SocketOptions.readTimeoutMillis][rtm]:
116the read timeout is the maximum time that the driver waits for a regular
117query to complete, therefore the connection should not be considered
118idle before it has elapsed.
119
120To disable heartbeat, set the interval to 0.
121
122Implementation note: the dummy request sent by heartbeat is an
123[OPTIONS](https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v3.spec#L278)
124message.
125
126
127#### Acquisition timeout
128
129When the driver tries to send a request to a host, it will first try to
130acquire a connection from this host's pool. If the pool is busy (i.e.
131all connections are already handling their maximum number of in flight
132requests), the client thread will block for a while, until a connection
133becomes available (note that this will block even if you're using the
134asynchronous API, like [Session.executeAsync][exec_async]).
135
136The time that the driver blocks is controlled by
137[PoolingOptions.setPoolTimeoutMillis][ptm]. If there is still no connection
138available after this timeout, the driver will try the next host.
139
140For some applications, blocking is not acceptable, and it is preferable
141to fail fast if the request cannot be fulfilled. If that's your case,
142set the pool timeout to 0. If all hosts are busy, you will get a
143[NoHostAvailableException][nhae] (if you look at the exception's details, you
144will see a `java.util.concurrent.TimeoutException` for each host).
145
146
147### Monitoring and tuning the pool
148
149The easiest way to monitor pool usage is with [Session.getState][get_state]. Here's
150a simple example that will print the number of open connections, active
151requests, and maximum capacity for each host, every 5 seconds:
152
153```java
154ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(1);
155scheduled.scheduleAtFixedRate(new Runnable() {
156 @Override
157 public void run() {
158 Session.State state = session.getState();
159 for (Host host : state.getConnectedHosts()) {
160 int connections = state.getOpenConnections(host);
161 int inFlightQueries = state.getInFlightQueries(host);
162 System.out.printf("%s connections=%d current load=%d max load=%d%n",
163 host, connections, inFlightQueries, connections * 128);
164 }
165 }
166}, 5, 5, TimeUnit.SECONDS);
167```
168
169In real life, you'll probably want something more sophisticated, like
170exposing a JMX MBean or sending the data to your favorite monitoring
171tool.
172
173If you find that the current load stays close or equal to the maximum
174load at all time, it's a sign that your connection pools are saturated
175and you should raise the max connections per host. On the other hand, if
176the load is often less than core * 128, your pools are underused and you
177could get away with less core connections.
178
179[result_set_future]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/ResultSetFuture.html
180[pooling_options]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/PoolingOptions.html
181[lbp]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/policies/LoadBalancingPolicy.html
182[msrpct]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/PoolingOptions.html#setMaxSimultaneousRequestsPerConnectionThreshold(com.datastax.driver.core.HostDistance,%20int)
183[rtm]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/SocketOptions.html#getReadTimeoutMillis()
184[exec_async]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/Session.html#executeAsync(com.datastax.driver.core.Statement)
185[ptm]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/PoolingOptions.html#setPoolTimeoutMillis(int)
186[nhae]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/exceptions/NoHostAvailableException.html
187[get_state]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/Session.html#getState()