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