| 1 | ## Speculative query execution |
| 2 | |
| 3 | Sometimes a Cassandra node might be experiencing difficulties (ex: long |
| 4 | GC pause) and take longer than usual to reply. Queries sent to that node |
| 5 | will experience bad latency. |
| 6 | |
| 7 | One thing we can do to improve that is pre-emptively start a second |
| 8 | execution of the query against another node, before the first node has |
| 9 | replied or errored out. If that second node replies faster, we can send |
| 10 | the response back to the client (we also cancel the first query): |
| 11 | |
| 12 | ```ditaa |
| 13 | client driver exec1 exec2 |
| 14 | --+----------------+--------------+------+--- |
| 15 | | execute(query) | |
| 16 | |--------------->| |
| 17 | | | query host1 |
| 18 | | |------------->| |
| 19 | | | | |
| 20 | | | | |
| 21 | | | query host2 |
| 22 | | |-------------------->| |
| 23 | | | | | |
| 24 | | | | | |
| 25 | | | host2 replies | |
| 26 | | |<--------------------| |
| 27 | | complete | | |
| 28 | |<---------------| | |
| 29 | | | cancel | |
| 30 | | |------------->| |
| 31 | ``` |
| 32 | |
| 33 | Or the first node could reply just after the second execution was |
| 34 | started. In this case, we cancel the second execution. In other words, |
| 35 | whichever node replies faster "wins" and completes the client query: |
| 36 | |
| 37 | ```ditaa |
| 38 | client driver exec1 exec2 |
| 39 | --+----------------+--------------+------+--- |
| 40 | | execute(query) | |
| 41 | |--------------->| |
| 42 | | | query host1 |
| 43 | | |------------->| |
| 44 | | | | |
| 45 | | | | |
| 46 | | | query host2 |
| 47 | | |-------------------->| |
| 48 | | | | | |
| 49 | | | | | |
| 50 | | | host1 replies| | |
| 51 | | |<-------------| | |
| 52 | | complete | | |
| 53 | |<---------------| | |
| 54 | | | cancel | |
| 55 | | |-------------------->| |
| 56 | ``` |
| 57 | |
| 58 | Speculative executions are **disabled** by default. The following |
| 59 | sections cover the practical details and how to enable them. |
| 60 | |
| 61 | ### Query idempotence |
| 62 | |
| 63 | If a query is [not idempotent](../idempotence/), the driver will never schedule speculative executions for it, because |
| 64 | there is no way to guarantee that only one node will apply the mutation. |
| 65 | |
| 66 | ### Enabling speculative executions |
| 67 | |
| 68 | Speculative executions are controlled by an instance of |
| 69 | [SpeculativeExecutionPolicy][sep] provided when initializing the |
| 70 | `Cluster`. This policy defines the threshold after which a new |
| 71 | speculative execution will be triggered. |
| 72 | |
| 73 | [sep]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/SpeculativeExecutionPolicy.html |
| 74 | |
| 75 | Two implementations are provided with the driver: |
| 76 | |
| 77 | #### [ConstantSpeculativeExecutionPolicy][csep] |
| 78 | |
| 79 | This simple policy uses a constant threshold: |
| 80 | |
| 81 | ```java |
| 82 | Cluster cluster = Cluster.builder() |
| 83 | .addContactPoint("127.0.0.1") |
| 84 | .withSpeculativeExecutionPolicy( |
| 85 | new ConstantSpeculativeExecutionPolicy( |
| 86 | 500, // delay before a new execution is launched |
| 87 | 2 // maximum number of executions |
| 88 | )) |
| 89 | .build(); |
| 90 | ``` |
| 91 | |
| 92 | Given the above configuration, an idempotent query would be handled this |
| 93 | way: |
| 94 | |
| 95 | * start the initial execution at t0; |
| 96 | * if no response has been received at t0 + 500 milliseconds, start a |
| 97 | speculative execution on another node; |
| 98 | * if no response has been received at t0 + 1000 milliseconds, start |
| 99 | another speculative execution on a third node. |
| 100 | |
| 101 | [csep]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/ConstantSpeculativeExecutionPolicy.html |
| 102 | |
| 103 | #### [PercentileSpeculativeExecutionPolicy][psep] |
| 104 | |
| 105 | This policy sets the threshold at a given latency percentile for the |
| 106 | current host, based on recent statistics. |
| 107 | |
| 108 | **As of 2.1.6, this class is provided as a beta preview: it hasn't been |
| 109 | extensively tested yet, and the API is still subject to change.** |
| 110 | |
| 111 | First and foremost, make sure that the [HdrHistogram][hdr] library (used |
| 112 | under the hood to collect latencies) is in your classpath. It's defined |
| 113 | as an optional dependency in the driver's POM, so you'll need to |
| 114 | explicitly depend on it: |
| 115 | |
| 116 | ```xml |
| 117 | <dependency> |
| 118 | <groupId>org.hdrhistogram</groupId> |
| 119 | <artifactId>HdrHistogram</artifactId> |
| 120 | <version>2.1.9</version> |
| 121 | </dependency> |
| 122 | ``` |
| 123 | |
| 124 | Then create an instance of [PerHostPercentileTracker][phpt] that will collect |
| 125 | latency statistics for your `Cluster`: |
| 126 | |
| 127 | ```java |
| 128 | // There are more options than shown here, please refer to the API docs |
| 129 | // for more information |
| 130 | PerHostPercentileTracker tracker = PerHostPercentileTracker |
| 131 | .builderWithHighestTrackableLatencyMillis(15000) |
| 132 | .build(); |
| 133 | ``` |
| 134 | |
| 135 | Create an instance of the policy with the tracker, and pass it to your |
| 136 | cluster: |
| 137 | |
| 138 | ```java |
| 139 | PercentileSpeculativeExecutionPolicy policy = |
| 140 | new PercentileSpeculativeExecutionPolicy( |
| 141 | tracker, |
| 142 | 99.0, // percentile |
| 143 | 2); // maximum number of executions |
| 144 | |
| 145 | Cluster cluster = Cluster.builder() |
| 146 | .addContactPoint("127.0.0.1") |
| 147 | .withSpeculativeExecutionPolicy(policy) |
| 148 | .build(); |
| 149 | ``` |
| 150 | |
| 151 | Finally, don't forget to register your tracker with the cluster (the |
| 152 | policy does not do this itself): |
| 153 | |
| 154 | ```java |
| 155 | cluster.register(tracker); |
| 156 | ``` |
| 157 | |
| 158 | Note that `PerHostPercentileTracker` may also be used with a slow query |
| 159 | logger (see the [Logging](../logging/) section). In that case, you would |
| 160 | create a single tracker object and share it with both components. |
| 161 | |
| 162 | [psep]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/PercentileSpeculativeExecutionPolicy.html |
| 163 | [hdr]: http://hdrhistogram.github.io/HdrHistogram/ |
| 164 | [phpt]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PerHostPercentileTracker.html |
| 165 | |
| 166 | #### Using your own |
| 167 | |
| 168 | As with all policies, you are free to provide your own by implementing |
| 169 | `SpeculativeExecutionPolicy`. |
| 170 | |
| 171 | ### How speculative executions affect retries |
| 172 | |
| 173 | Turning speculative executions on doesn't change the driver's [retry](../retries/) behavior. Each |
| 174 | parallel execution will trigger retries independently: |
| 175 | |
| 176 | ```ditaa |
| 177 | client driver exec1 exec2 |
| 178 | --+----------------+--------------+------+--- |
| 179 | | execute(query) | |
| 180 | |--------------->| |
| 181 | | | query host1 |
| 182 | | |------------->| |
| 183 | | | | |
| 184 | | | unavailable | |
| 185 | | |<-------------| |
| 186 | | | |
| 187 | | |retry at lower CL |
| 188 | | |------------->| |
| 189 | | | | |
| 190 | | | query host2 |
| 191 | | |-------------------->| |
| 192 | | | | | |
| 193 | | | server error | |
| 194 | | |<--------------------| |
| 195 | | | | |
| 196 | | | retry on host3 |
| 197 | | |-------------------->| |
| 198 | | | | | |
| 199 | | | host1 replies| | |
| 200 | | |<-------------| | |
| 201 | | complete | | |
| 202 | |<---------------| | |
| 203 | | | cancel | |
| 204 | | |-------------------->| |
| 205 | ``` |
| 206 | |
| 207 | The only impact is that all executions of the same query always share |
| 208 | the same query plan, so each host will be used by at most one execution. |
| 209 | |
| 210 | [retry_policy]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/RetryPolicy.html |
| 211 | |
| 212 | ### Tuning and practical details |
| 213 | |
| 214 | The goal of speculative executions is to improve overall latency (the |
| 215 | time between `execute(query)` and `complete` in the diagrams above) at |
| 216 | high percentiles. On the flipside, they cause the driver to send more |
| 217 | individual requests, so throughput will not necessarily improve. |
| 218 | |
| 219 | You can monitor how many speculative executions were triggered with the |
| 220 | `speculative-executions` metric (exposed in the Java API as |
| 221 | [cluster.getMetrics().getErrors().getSpeculativeExecutions()][se_metric]). |
| 222 | It should only be a few percents of the total number of requests |
| 223 | ([cluster.getMetrics().getRequestsTimer().getCount()][request_metric]). |
| 224 | |
| 225 | [se_metric]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Metrics.Errors.html#getSpeculativeExecutions-- |
| 226 | [request_metric]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Metrics.html#getRequestsTimer-- |
| 227 | |
| 228 | #### Stream id exhaustion |
| 229 | |
| 230 | One side-effect of speculative executions is that many requests are |
| 231 | cancelled, which can lead to a phenomenon called *stream id exhaustion*: |
| 232 | each TCP connection can handle multiple simultaneous requests, |
| 233 | identified by a unique number called *stream id*. When a request gets |
| 234 | cancelled, we can't reuse its stream id immediately because we might |
| 235 | still receive a response from the server later. If this happens often, |
| 236 | the number of available stream ids diminishes over time, and when it |
| 237 | goes below a given threshold we close the connection and create a new |
| 238 | one. If requests are often cancelled, so will see connections being |
| 239 | recycled at a high rate. |
| 240 | |
| 241 | One way to detect this is to monitor open connections per host |
| 242 | ([Session.getState().getOpenConnections(host)][session_state]) against |
| 243 | TCP connections at the OS level. If open connections stay constant but |
| 244 | you see many TCP connections in closing states, you might be running |
| 245 | into this issue. Try raising the speculative execution threshold. |
| 246 | |
| 247 | This problem is more likely to happen with version 2 of the native |
| 248 | protocol, because each TCP connection only has 128 stream ids. With |
| 249 | version 3 (driver 2.1.2 or above with Cassandra 2.1 or above), there are |
| 250 | 32K stream ids per connection, so higher cancellation rates can be |
| 251 | sustained. If you're unsure of which native protocol version you're |
| 252 | using, you can check with |
| 253 | [cluster.getConfiguration().getProtocolOptions().getProtocolVersion()][protocol_version]. |
| 254 | |
| 255 | [session_state]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.State.html |
| 256 | [protocol_version]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/ProtocolOptions.html#getProtocolVersion-- |
| 257 | |
| 258 | #### Request ordering and client timestamps |
| 259 | |
| 260 | Another issue that might arise is that you get unintuitive results |
| 261 | because of request ordering. Suppose you run the following query with |
| 262 | speculative executions enabled: |
| 263 | |
| 264 | insert into my_table (k, v) values (1, 1); |
| 265 | |
| 266 | The first execution is a bit too slow, so a second execution gets |
| 267 | triggered. Finally, the first execution completes, so the client code |
| 268 | gets back an acknowledgement, and the second execution is cancelled. |
| 269 | However, cancelling only means that the driver stops waiting for the |
| 270 | server's response, the request could still be "on the wire"; let's |
| 271 | assume that this is the case. |
| 272 | |
| 273 | Now you run the following query, which completes successfully: |
| 274 | |
| 275 | delete from my_table where k = 1; |
| 276 | |
| 277 | But now the second execution of the first query finally reaches its |
| 278 | target node, which applies the mutation. The row that you've just |
| 279 | deleted is back! |
| 280 | |
| 281 | The workaround is to use a timestamp with your queries: |
| 282 | |
| 283 | insert into my_table (k, v) values (1, 1) USING TIMESTAMP 1432764000; |
| 284 | |
| 285 | If you're using native protocol v3, you can also enable [client-side |
| 286 | timestamps](../query_timestamps/#client-side-generation) to have this done |
| 287 | automatically. |