Elffuss BraidHub

kikocis/java-driver public

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