Elffuss BraidHub

kikocis/java-driver public

bb936e89652f · 13.4 KiBRenderedRawPermalink
1## Speculative query execution
2
3Sometimes a Cassandra node might be experiencing difficulties (ex: long
4GC pause) and take longer than usual to reply. Queries sent to that node
5will experience bad latency.
6
7One thing we can do to improve that is pre-emptively start a second
8execution of the query against another node, before the first node has
9replied or errored out. If that second node replies faster, we can send
10the response back to the client (we also cancel the first query):
11
12```ditaa
13client 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
33Or the first node could reply just after the second execution was
34started. In this case, we cancel the second execution. In other words,
35whichever node replies faster "wins" and completes the client query:
36
37```ditaa
38client 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
58Speculative executions are **disabled** by default. The following
59sections cover the practical details and how to enable them.
60
61### Query idempotence
62
63One important aspect to consider is whether queries are idempotent, i.e.
64whether they can be applied multiple times without changing the result
65beyond the initial application. **If a query is not idempotent, the
66driver will never schedule speculative executions for it**, because
67there is no way to guarantee that only one node will apply the mutation.
68
69As of Cassandra 2.1.4, the only queries that are *not* idempotent are:
70
71* counter operations;
72* prepending or appending to a list column;
73* using non-idempotent CQL functions, like `now()` or `uuid()`.
74
75In the driver, this is determined by
76[Statement#isIdempotent()][isIdempotent]. Unfortunately, the driver
77doesn't parse query strings, so in most cases it has no information
78about what the query actually does. Therefore:
79
80* **`Statement#isIdempotent()` is only computed automatically for
81 statements built with [QueryBuilder][QueryBuilder]**.
82 Note that the driver takes a rather conservative approach with uses
83 of `fcall()` or `raw()`: whenever they appear in a value to be
84 inserted in the database (like the values of an `Insert` or the
85 right-hand side of an assignment in an `Update`), the statement
86 will be considered non-idempotent by default. If you know that your
87 CQL functions or expressions are safe, force idempotence to `true`
88 on the statement manually (see below);
89* **for all other types of statements, it defaults to `false`.** You'll
90 need to set it manually, with one of the mechanism described below.
91
92You can override the value on each statement:
93
94```java
95Statement s = new SimpleStatement("SELECT * FROM users WHERE id = 1");
96s.setIdempotent(true);
97```
98
99Note that this will also work for built statements (and override the
100computed value).
101
102Additionally, if you know for a fact that your application does not use
103any of the non-idempotent CQL queries listed above, you can change the
104default cluster-wide:
105
106```java
107// Make all statements idempotent by default:
108cluster.getConfiguration().getQueryOptions().setDefaultIdempotence(true);
109```
110
111[isIdempotent]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/Statement.html#isIdempotent()
112[QueryBuilder]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/querybuilder/QueryBuilder.html
113
114### Enabling speculative executions
115
116Speculative executions are controlled by an instance of
117[SpeculativeExecutionPolicy][sep] provided when initializing the
118`Cluster`. This policy defines the threshold after which a new
119speculative execution will be triggered.
120
121[sep]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/policies/SpeculativeExecutionPolicy.html
122
123Two implementations are provided with the driver:
124
125#### [ConstantSpeculativeExecutionPolicy][csep]
126
127This simple policy uses a constant threshold:
128
129```java
130Cluster cluster = Cluster.builder()
131 .addContactPoint("127.0.0.1")
132 .withSpeculativeExecutionPolicy(
133 new ConstantSpeculativeExecutionPolicy(
134 500, // delay before a new execution is launched
135 2 // maximum number of executions
136 ))
137 .build();
138```
139
140Given the above configuration, an idempotent query would be handled this
141way:
142
143* start the initial execution at t0;
144* if no response has been received at t0 + 500 milliseconds, start a
145 speculative execution on another node;
146* if no response has been received at t0 + 1000 milliseconds, start
147 another speculative execution on a third node.
148
149[csep]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/policies/ConstantSpeculativeExecutionPolicy.html
150
151#### [PercentileSpeculativeExecutionPolicy][psep]
152
153This policy sets the threshold at a given latency percentile for the
154current host, based on recent statistics.
155
156**As of 2.0.10, this class is provided as a beta preview: it hasn't been
157extensively tested yet, and the API is still subject to change.**
158
159First and foremost, make sure that the [HdrHistogram][hdr] library (used
160under the hood to collect latencies) is in your classpath. It's defined
161as an optional dependency in the driver's POM, so you'll need to
162explicitly depend on it:
163
164```xml
165<dependency>
166 <groupId>org.hdrhistogram</groupId>
167 <artifactId>HdrHistogram</artifactId>
168 <version>2.1.4</version>
169</dependency>
170```
171
172Then create an instance of [PerHostPercentileTracker][phpt] that will collect
173latency statistics for your `Cluster`:
174
175```java
176// There are more options than shown here, please refer to the API docs
177// for more information
178PerHostPercentileTracker tracker = PerHostPercentileTracker
179 .builderWithHighestTrackableLatencyMillis(15000)
180 .build();
181```
182
183Create an instance of the policy with the tracker, and pass it to your
184cluster:
185
186```java
187PercentileSpeculativeExecutionPolicy policy =
188 new PercentileSpeculativeExecutionPolicy(
189 tracker,
190 99.0, // percentile
191 2); // maximum number of executions
192
193Cluster cluster = Cluster.builder()
194 .addContactPoint("127.0.0.1")
195 .withSpeculativeExecutionPolicy(policy)
196 .build();
197```
198
199Finally, don't forget to register your tracker with the cluster (the
200policy does not do this itself):
201
202```java
203cluster.register(tracker);
204```
205
206Note that `PerHostPercentileTracker` may also be used with a slow query
207logger (see the [Logging](../logging/) section). In that case, you would
208create a single tracker object and share it with both components.
209
210[psep]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/policies/PercentileSpeculativeExecutionPolicy.html
211[hdr]: http://hdrhistogram.github.io/HdrHistogram/
212[phpt]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/PerHostPercentileTracker.html
213
214#### Using your own
215
216As with all policies, you are free to provide your own by implementing
217`SpeculativeExecutionPolicy`.
218
219### How speculative executions affect retries
220
221Regardless of speculative executions, the driver has a retry mechanism:
222
223* on an internal error, it will try the next host;
224* when the consistency level could not be reached (`unavailable` error
225 or read or write timeout), it will delegate the decision to
226 [RetryPolicy][retry_policy], which might trigger a retry on the same
227 host.
228
229Turning speculative executions on doesn't change this behavior. Each
230parallel execution will trigger retries independently:
231
232```ditaa
233client driver exec1 exec2
234--+----------------+--------------+------+---
235 | execute(query) |
236 |--------------->|
237 | | query host1
238 | |------------->|
239 | | |
240 | | unavailable |
241 | |<-------------|
242 | |
243 | |retry at lower CL
244 | |------------->|
245 | | |
246 | | query host2
247 | |-------------------->|
248 | | | |
249 | | server error |
250 | |<--------------------|
251 | | |
252 | | retry on host3
253 | |-------------------->|
254 | | | |
255 | | host1 replies| |
256 | |<-------------| |
257 | complete | |
258 |<---------------| |
259 | | cancel |
260 | |-------------------->|
261```
262
263The only impact is that all executions of the same query always share
264the same query plan, so each host will be used by at most one execution.
265
266[retry_policy]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/policies/RetryPolicy.html
267
268### Tuning and practical details
269
270The goal of speculative executions is to improve overall latency (the
271time between `execute(query)` and `complete` in the diagrams above) at
272high percentiles. On the flipside, they cause the driver to send more
273individual requests, so throughput will not necessarily improve.
274
275You can monitor how many speculative executions were triggered with the
276`speculative-executions` metric (exposed in the Java API as
277[cluster.getMetrics().getErrors().getSpeculativeExecutions()][se_metric]).
278It should only be a few percents of the total number of requests
279([cluster.getMetrics().getRequestsTimer().getCount()][request_metric]).
280
281[se_metric]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/Metrics.Errors.html#getSpeculativeExecutions()
282[request_metric]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/Metrics.html#getRequestsTimer()
283
284#### Stream id exhaustion
285
286One side-effect of speculative executions is that many requests are
287cancelled, which can lead to a phenomenon called *stream id exhaustion*:
288each TCP connection can handle multiple simultaneous requests,
289identified by a unique number called *stream id*. When a request gets
290cancelled, we can't reuse its stream id immediately because we might
291still receive a response from the server later. If this happens often,
292the number of available stream ids diminishes over time, and when it
293goes below a given threshold we close the connection and create a new
294one. If requests are often cancelled, so will see connections being
295recycled at a high rate.
296
297One way to detect this is to monitor open connections per host
298([Session.getState().getOpenConnections(host)][session_state]) against
299TCP connections at the OS level. If open connections stay constant but
300you see many TCP connections in closing states, you might be running
301into this issue. Try raising the speculative execution threshold.
302
303This problem is more likely to happen with version 2 of the native
304protocol, because each TCP connection only has 128 stream ids. With
305version 3 (driver 2.1.2 or above with Cassandra 2.1 or above), there are
30632K stream ids per connection, so higher cancellation rates can be
307sustained. If you're unsure of which native protocol version you're
308using, you can check with
309[cluster.getConfiguration().getProtocolOptions().getProtocolVersion()][protocol_version].
310
311[session_state]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/Session.State.html
312[protocol_version]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/ProtocolOptions.html#getProtocolVersion()
313
314#### Request ordering and client timestamps
315
316Another issue that might arise is that you get unintuitive results
317because of request ordering. Suppose you run the following query with
318speculative executions enabled:
319
320 insert into my_table (k, v) values (1, 1);
321
322The first execution is a bit too slow, so a second execution gets
323triggered. Finally, the first execution completes, so the client code
324gets back an acknowledgement, and the second execution is cancelled.
325However, cancelling only means that the driver stops waiting for the
326server's response, the request could still be "on the wire"; let's
327assume that this is the case.
328
329Now you run the following query, which completes successfully:
330
331 delete from my_table where k = 1;
332
333But now the second execution of the first query finally reaches its
334target node, which applies the mutation. The row that you've just
335deleted is back!
336
337The workaround is to use a timestamp with your queries:
338
339 insert into my_table (k, v) values (1, 1) USING TIMESTAMP 1432764000;
340
341If you're using native protocol v3, you can also enable client-side
342timestamps to have this done automatically; see
343[this blog post](http://www.datastax.com/dev/blog/java-driver-2-1-2-native-protocol-v3)
344for more information.