| 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 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 | |
| 22 | You 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 |
| 25 | not ignored by the [load balancing policy](../load_balancing)). |
| 26 | |
| 27 | The number of connections per pool is configurable (this will be |
| 28 | described 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 | |
| 42 | Connections pools are configured with a [PoolingOptions][pooling_options] object, which |
| 43 | is global to a `Cluster` instance. You can pass that object when |
| 44 | building the cluster: |
| 45 | |
| 46 | ```java |
| 47 | PoolingOptions poolingOptions = new PoolingOptions(); |
| 48 | // customize options... |
| 49 | |
| 50 | Cluster cluster = Cluster.builder() |
| 51 | .withContactPoints("127.0.0.1") |
| 52 | .withPoolingOptions(poolingOptions) |
| 53 | .build(); |
| 54 | ``` |
| 55 | |
| 56 | Most options can also be changed at runtime. If you don't have a |
| 57 | reference to the `PoolingOptions` instance, here's how you can get it: |
| 58 | |
| 59 | ```java |
| 60 | PoolingOptions poolingOptions = cluster.getConfiguration().getPoolingOptions(); |
| 61 | // customize options... |
| 62 | ``` |
| 63 | |
| 64 | #### Pool size |
| 65 | |
| 66 | Connection pools have a variable size, which gets adjusted automatically |
| 67 | depending on the current load. There will always be at least a *core* |
| 68 | number of connections, and at most a *max* number. These values can be |
| 69 | configured independently by host *distance* (the distance is determined |
| 70 | by your [LoadBalancingPolicy][lbp], and will generally indicate whether a |
| 71 | host is in the same datacenter or not). |
| 72 | |
| 73 | ```java |
| 74 | poolingOptions |
| 75 | .setCoreConnectionsPerHost(HostDistance.LOCAL, 4) |
| 76 | .setMaxConnectionsPerHost( HostDistance.LOCAL, 10) |
| 77 | .setCoreConnectionsPerHost(HostDistance.REMOTE, 2) |
| 78 | .setMaxConnectionsPerHost( HostDistance.REMOTE, 4); |
| 79 | ``` |
| 80 | |
| 81 | For convenience, core and max can be set simultaneously: |
| 82 | |
| 83 | ```java |
| 84 | poolingOptions |
| 85 | .setConnectionsPerHost(HostDistance.LOCAL, 4, 10) |
| 86 | .setConnectionsPerHost(HostDistance.REMOTE, 2, 4); |
| 87 | ``` |
| 88 | |
| 89 | The 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 |
| 99 | that triggers the creation of a new connection when the pool is not at |
| 100 | its maximum capacity. In general, you shouldn't need to change its |
| 101 | default value. |
| 102 | |
| 103 | #### Dynamic resizing |
| 104 | |
| 105 | If core != max, the pool will resize automatically to adjust to the |
| 106 | current activity on the host. |
| 107 | |
| 108 | When activity goes up and there are *n* connections with n < max, the driver |
| 109 | will 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 |
| 112 | connection is above the threshold). |
| 113 | |
| 114 | When activity goes down, the driver will "trash" connections if the maximum |
| 115 | number of requests in a 10 second time period can be satisfied by less than |
| 116 | the number of connections opened. Trashed connections are kept open but do |
| 117 | not accept new requests. After a given timeout (defined by |
| 118 | [PoolingOptions.setIdleTimeoutSeconds][sits]), trashed connections are closed |
| 119 | and removed. If during that idle period activity increases again, those |
| 120 | connections will be resurrected back into the active pool and reused. The |
| 121 | main intent of that is to not constantly recreate connections if activity |
| 122 | changes quickly over an interval. |
| 123 | |
| 124 | #### Simultaneous requests per connection |
| 125 | |
| 126 | [PoolingOptions.setMaxRequestsPerConnection][mrpc] allows you to |
| 127 | throttle the number of concurrent requests per connection. |
| 128 | |
| 129 | With protocol v2, there is no reason to throttle. It is set to 128 (the |
| 130 | max) and you should not change it. |
| 131 | |
| 132 | With 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 |
| 134 | configuration for protocol v2 and v3 allow the same total number of |
| 135 | simultaneous requests (to avoid bad surprises when clients migrate from |
| 136 | v2 to v3). You can raise this threshold, or even set it to the max: |
| 137 | |
| 138 | ```java |
| 139 | poolingOptions |
| 140 | .setMaxRequestsPerConnection(HostDistance.LOCAL, 32768) |
| 141 | .setMaxRequestsPerConnection(HostDistance.REMOTE, 2000); |
| 142 | ``` |
| 143 | |
| 144 | Just keep in mind that high values will give clients more bandwidth and |
| 145 | therefore put more pressure on your cluster. This might require some |
| 146 | tuning, especially if you have many clients. |
| 147 | |
| 148 | #### Heartbeat |
| 149 | |
| 150 | If connections stay idle for too long, they might be dropped by |
| 151 | intermediate network devices (routers, firewalls...). Normally, TCP |
| 152 | keepalive should take care of this; but tweaking low-level keepalive |
| 153 | settings might be impractical in some environments. |
| 154 | |
| 155 | The driver provides application-side keepalive in the form of a |
| 156 | connection heartbeat: when a connection has been idle for a given amount |
| 157 | of time, the driver will simulate activity by writing a dummy request to |
| 158 | it. |
| 159 | |
| 160 | This feature is enabled by default. The default heartbeat interval is 30 |
| 161 | seconds, it can be customized with the following method: |
| 162 | |
| 163 | ```java |
| 164 | poolingOptions.setHeartbeatIntervalSeconds(60); |
| 165 | ``` |
| 166 | |
| 167 | If it gets changed at runtime, only connections created after that will |
| 168 | use the new interval. Most users will want to do this at startup. |
| 169 | |
| 170 | The heartbeat interval should be set higher than |
| 171 | [SocketOptions.readTimeoutMillis][rtm]: |
| 172 | the read timeout is the maximum time that the driver waits for a regular |
| 173 | query to complete, therefore the connection should not be considered |
| 174 | idle before it has elapsed. |
| 175 | |
| 176 | To disable heartbeat, set the interval to 0. |
| 177 | |
| 178 | Implementation note: the dummy request sent by heartbeat is an |
| 179 | [OPTIONS](https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v3.spec#L278) |
| 180 | message. |
| 181 | |
| 182 | |
| 183 | #### Acquisition queue |
| 184 | |
| 185 | When the driver tries to send a request to a host, it will first try to |
| 186 | acquire a connection from this host's pool. If the pool is busy (i.e. |
| 187 | all connections are already handling their maximum number of in flight |
| 188 | requests), the acquisition attempt gets enqueued until a connection becomes |
| 189 | available again. |
| 190 | |
| 191 | Two 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 | |
| 199 | If the attempt is rejected, the driver will move to the next host in the [query plan](../load_balancing/#query-plan), |
| 200 | and try to acquire a connection again. |
| 201 | |
| 202 | If 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 |
| 204 | exception's [getErrors] method, you will see a [BusyPoolException] for |
| 205 | each host. |
| 206 | |
| 207 | |
| 208 | ### Monitoring and tuning the pool |
| 209 | |
| 210 | The easiest way to monitor pool usage is with [Session.getState][get_state]. Here's |
| 211 | a simple example that will print the number of open connections, active |
| 212 | requests, and maximum capacity for each host, every 5 seconds: |
| 213 | |
| 214 | ```java |
| 215 | final LoadBalancingPolicy loadBalancingPolicy = |
| 216 | cluster.getConfiguration().getPolicies().getLoadBalancingPolicy(); |
| 217 | final PoolingOptions poolingOptions = |
| 218 | cluster.getConfiguration().getPoolingOptions(); |
| 219 | |
| 220 | ScheduledExecutorService scheduled = |
| 221 | Executors.newScheduledThreadPool(1); |
| 222 | scheduled.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 |
| 231 | load=%d%n", |
| 232 | host, connections, inFlightQueries, |
| 233 | connections * |
| 234 | poolingOptions.getMaxRequestsPerConnection(distance)); |
| 235 | } |
| 236 | } |
| 237 | }, 5, 5, TimeUnit.SECONDS); |
| 238 | ``` |
| 239 | |
| 240 | In real life, you'll probably want something more sophisticated, like |
| 241 | exposing a JMX MBean or sending the data to your favorite monitoring |
| 242 | tool. |
| 243 | |
| 244 | If you find that the current load stays close or equal to the maximum |
| 245 | load at all time, it's a sign that your connection pools are saturated |
| 246 | and you should raise the max connections per host, or max requests per |
| 247 | connection (protocol v3). |
| 248 | |
| 249 | If you're using protocol v2 and the load is often less than core * 128, |
| 250 | your pools are underused and you could get away with less core |
| 251 | connections. |
| 252 | |
| 253 | #### Tuning protocol v3 for very high throughputs |
| 254 | |
| 255 | As 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 |
| 257 | connection, and therefore a single Netty I/O thread. |
| 258 | |
| 259 | There is a corner case where this I/O thread can max out its CPU core |
| 260 | and become a bottleneck in the driver; in our benchmarks, this happened |
| 261 | with a single-node cluster and a high throughput (approximately 80K |
| 262 | requests / second). |
| 263 | |
| 264 | It's unlikely that you'll run into this issue: in most real-world |
| 265 | deployments, the driver connects to more than one node, so the load will |
| 266 | spread across more I/O threads. However if you suspect that you |
| 267 | experience 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 | |
| 277 | The solution is to add more connections per node. To ensure that |
| 278 | additional connections get created before you run into the bottleneck, |
| 279 | either: |
| 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 |