| 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 | Version 2.0.x of the driver uses version 1 of the binary protocol when |
| 23 | connecting to Cassandra 1.2, and version 2 when connecting to Cassandra |
| 24 | 2.0 or higher. In both cases, that gives you **128 stream ids per |
| 25 | connection**. |
| 26 | |
| 27 | Because the number of stream ids per connection is limited, we use a |
| 28 | pool with multiple connections to each host. **For each `Session` |
| 29 | object, there is one connection pool per connected host**. The number of |
| 30 | connections per pool depends on the configuration, this will be |
| 31 | described 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 | |
| 41 | Connections pools are configured with a [PoolingOptions][pooling_options] object, which |
| 42 | is global to a `Cluster` instance. You can pass that object when |
| 43 | building the cluster: |
| 44 | |
| 45 | ```java |
| 46 | PoolingOptions poolingOptions = new PoolingOptions(); |
| 47 | // customize options... |
| 48 | |
| 49 | Cluster cluster = Cluster.builder() |
| 50 | .withContactPoints("127.0.0.1") |
| 51 | .withPoolingOptions(poolingOptions) |
| 52 | .build(); |
| 53 | ``` |
| 54 | |
| 55 | Most options can also be changed at runtime. If you don't have a |
| 56 | reference to the `PoolingOptions` instance, here's how you can get it: |
| 57 | |
| 58 | ```java |
| 59 | PoolingOptions poolingOptions = cluster.getConfiguration().getPoolingOptions(); |
| 60 | // customize options... |
| 61 | ``` |
| 62 | |
| 63 | #### Pool size |
| 64 | |
| 65 | Connection pools have a variable size, which gets adjusted automatically |
| 66 | depending on the current load. There will always be at least a *core* |
| 67 | number of connections, and at most a *max* number. These values can be |
| 68 | configured independently by host *distance* (the distance is determined |
| 69 | by your [LoadBalancingPolicy][lbp], and will generally indicate whether a |
| 70 | host is in the same datacenter or not). |
| 71 | |
| 72 | ```java |
| 73 | poolingOptions |
| 74 | .setCoreConnectionsPerHost(HostDistance.LOCAL, 4) |
| 75 | .setMaxConnectionsPerHost( HostDistance.LOCAL, 10) |
| 76 | .setCoreConnectionsPerHost(HostDistance.REMOTE, 2) |
| 77 | .setMaxConnectionsPerHost( HostDistance.REMOTE, 4); |
| 78 | ``` |
| 79 | |
| 80 | For convenience, core and max can be set simultaneously: |
| 81 | |
| 82 | ```java |
| 83 | poolingOptions |
| 84 | .setConnectionsPerHost(HostDistance.LOCAL, 4, 10) |
| 85 | .setConnectionsPerHost(HostDistance.REMOTE, 2, 4); |
| 86 | ``` |
| 87 | |
| 88 | The default settings are: |
| 89 | |
| 90 | * `LOCAL` hosts: core = 2, max = 8 |
| 91 | * `REMOTE` hosts: core = 1, max = 2 |
| 92 | |
| 93 | #### Dynamic resizing |
| 94 | |
| 95 | If core != max, the pool will resize automatically to adjust to the |
| 96 | current activity on the host. |
| 97 | |
| 98 | When activity goes up and there are *n* connections with n < max, the driver |
| 99 | will add a connection when the number of concurrent requests is more than |
| 100 | (n - 1) * 128 + [PoolingOptions.setMaxSimultaneousRequestsPerConnectionThreshold][msrpct] |
| 101 | (in layman's terms, when all but the last connection are full and the last |
| 102 | connection is above the threshold). |
| 103 | |
| 104 | When activity goes down, the driver will "trash" connections if the maximum |
| 105 | number of requests in a 10 second time period can be satisfied by less than |
| 106 | the number of connections opened. Trashed connections are kept open but do |
| 107 | not accept new requests. After a given timeout (defined by |
| 108 | [PoolingOptions.setIdleTimeoutSeconds][sits]), trashed connections are closed |
| 109 | and removed. If during that idle period activity increases again, those |
| 110 | connections will be resurrected back into the active pool and reused. The |
| 111 | main intent of that is to not constantly recreate connections if activity |
| 112 | changes quickly over an interval. |
| 113 | |
| 114 | #### Heartbeat |
| 115 | |
| 116 | If connections stay idle for too long, they might be dropped by |
| 117 | intermediate network devices (routers, firewalls...). Normally, TCP |
| 118 | keepalive should take care of this; but tweaking low-level keepalive |
| 119 | settings might be impractical in some environments. |
| 120 | |
| 121 | The driver provides application-side keepalive in the form of a |
| 122 | connection heartbeat: when a connection has been idle for a given amount |
| 123 | of time, the driver will simulate activity by writing a dummy request to |
| 124 | it. |
| 125 | |
| 126 | This feature is enabled by default. The default heartbeat interval is 30 |
| 127 | seconds, it can be customized with the following method: |
| 128 | |
| 129 | ```java |
| 130 | poolingOptions.setHeartbeatIntervalSeconds(60); |
| 131 | ``` |
| 132 | |
| 133 | If it gets changed at runtime, only connections created after that will |
| 134 | use the new interval. Most users will want to do this at startup. |
| 135 | |
| 136 | The heartbeat interval should be set higher than |
| 137 | [SocketOptions.readTimeoutMillis][rtm]: |
| 138 | the read timeout is the maximum time that the driver waits for a regular |
| 139 | query to complete, therefore the connection should not be considered |
| 140 | idle before it has elapsed. |
| 141 | |
| 142 | To disable heartbeat, set the interval to 0. |
| 143 | |
| 144 | Implementation note: the dummy request sent by heartbeat is an |
| 145 | [OPTIONS](https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v3.spec#L278) |
| 146 | message. |
| 147 | |
| 148 | |
| 149 | #### Acquisition timeout |
| 150 | |
| 151 | When the driver tries to send a request to a host, it will first try to |
| 152 | acquire a connection from this host's pool. If the pool is busy (i.e. |
| 153 | all connections are already handling their maximum number of in flight |
| 154 | requests), the client thread will block for a while, until a connection |
| 155 | becomes available (note that this will block even if you're using the |
| 156 | asynchronous API, like [Session.executeAsync][exec_async]). |
| 157 | |
| 158 | The time that the driver blocks is controlled by |
| 159 | [PoolingOptions.setPoolTimeoutMillis][ptm]. If there is still no connection |
| 160 | available after this timeout, the driver will try the next host. |
| 161 | |
| 162 | For some applications, blocking is not acceptable, and it is preferable |
| 163 | to fail fast if the request cannot be fulfilled. If that's your case, |
| 164 | set the pool timeout to 0. If all hosts are busy, you will get a |
| 165 | [NoHostAvailableException][nhae] (if you look at the exception's details, you |
| 166 | will see a `java.util.concurrent.TimeoutException` for each host). |
| 167 | |
| 168 | |
| 169 | ### Monitoring and tuning the pool |
| 170 | |
| 171 | The easiest way to monitor pool usage is with [Session.getState][get_state]. Here's |
| 172 | a simple example that will print the number of open connections, active |
| 173 | requests, and maximum capacity for each host, every 5 seconds: |
| 174 | |
| 175 | ```java |
| 176 | ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(1); |
| 177 | scheduled.scheduleAtFixedRate(new Runnable() { |
| 178 | @Override |
| 179 | public void run() { |
| 180 | Session.State state = session.getState(); |
| 181 | for (Host host : state.getConnectedHosts()) { |
| 182 | int connections = state.getOpenConnections(host); |
| 183 | int inFlightQueries = state.getInFlightQueries(host); |
| 184 | System.out.printf("%s connections=%d current load=%d max load=%d%n", |
| 185 | host, connections, inFlightQueries, connections * 128); |
| 186 | } |
| 187 | } |
| 188 | }, 5, 5, TimeUnit.SECONDS); |
| 189 | ``` |
| 190 | |
| 191 | In real life, you'll probably want something more sophisticated, like |
| 192 | exposing a JMX MBean or sending the data to your favorite monitoring |
| 193 | tool. |
| 194 | |
| 195 | If you find that the current load stays close or equal to the maximum |
| 196 | load at all time, it's a sign that your connection pools are saturated |
| 197 | and you should raise the max connections per host. On the other hand, if |
| 198 | the load is often less than core * 128, your pools are underused and you |
| 199 | could get away with less core connections. |
| 200 | |
| 201 | [result_set_future]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/ResultSetFuture.html |
| 202 | [pooling_options]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/PoolingOptions.html |
| 203 | [lbp]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/policies/LoadBalancingPolicy.html |
| 204 | [msrpct]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/PoolingOptions.html#setMaxSimultaneousRequestsPerConnectionThreshold(com.datastax.driver.core.HostDistance,%20int) |
| 205 | [sits]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/PoolingOptions.html#setIdleTimeoutSeconds(int) |
| 206 | [rtm]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/SocketOptions.html#getReadTimeoutMillis() |
| 207 | [exec_async]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/Session.html#executeAsync(com.datastax.driver.core.Statement) |
| 208 | [ptm]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/PoolingOptions.html#setPoolTimeoutMillis(int) |
| 209 | [nhae]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/exceptions/NoHostAvailableException.html |
| 210 | [get_state]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/Session.html#getState() |