Elffuss BraidHub

kikocis/java-driver public

3.1.x · 11.0 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
63If a query is [not idempotent](../idempotence/), the driver will never schedule speculative executions for it, because
64there is no way to guarantee that only one node will apply the mutation.
65
66### Enabling speculative executions
67
68Speculative 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
71speculative execution will be triggered.
72
73[sep]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/SpeculativeExecutionPolicy.html
74
75Two implementations are provided with the driver:
76
77#### [ConstantSpeculativeExecutionPolicy][csep]
78
79This simple policy uses a constant threshold:
80
81```java
82Cluster 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
92Given the above configuration, an idempotent query would be handled this
93way:
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
105This policy sets the threshold at a given latency percentile for the
106current host, based on recent statistics.
107
108**As of 2.1.6, this class is provided as a beta preview: it hasn't been
109extensively tested yet, and the API is still subject to change.**
110
111First and foremost, make sure that the [HdrHistogram][hdr] library (used
112under the hood to collect latencies) is in your classpath. It's defined
113as an optional dependency in the driver's POM, so you'll need to
114explicitly 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
124Then create an instance of [PerHostPercentileTracker][phpt] that will collect
125latency 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
130PerHostPercentileTracker tracker = PerHostPercentileTracker
131 .builderWithHighestTrackableLatencyMillis(15000)
132 .build();
133```
134
135Create an instance of the policy with the tracker, and pass it to your
136cluster:
137
138```java
139PercentileSpeculativeExecutionPolicy policy =
140 new PercentileSpeculativeExecutionPolicy(
141 tracker,
142 99.0, // percentile
143 2); // maximum number of executions
144
145Cluster cluster = Cluster.builder()
146 .addContactPoint("127.0.0.1")
147 .withSpeculativeExecutionPolicy(policy)
148 .build();
149```
150
151Finally, don't forget to register your tracker with the cluster (the
152policy does not do this itself):
153
154```java
155cluster.register(tracker);
156```
157
158Note that `PerHostPercentileTracker` may also be used with a slow query
159logger (see the [Logging](../logging/) section). In that case, you would
160create 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
168As with all policies, you are free to provide your own by implementing
169`SpeculativeExecutionPolicy`.
170
171### How speculative executions affect retries
172
173Turning speculative executions on doesn't change the driver's [retry](../retries/) behavior. Each
174parallel execution will trigger retries independently:
175
176```ditaa
177client 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
207The only impact is that all executions of the same query always share
208the 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
214The goal of speculative executions is to improve overall latency (the
215time between `execute(query)` and `complete` in the diagrams above) at
216high percentiles. On the flipside, they cause the driver to send more
217individual requests, so throughput will not necessarily improve.
218
219You 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]).
222It 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
230One side-effect of speculative executions is that many requests are
231cancelled, which can lead to a phenomenon called *stream id exhaustion*:
232each TCP connection can handle multiple simultaneous requests,
233identified by a unique number called *stream id*. When a request gets
234cancelled, we can't reuse its stream id immediately because we might
235still receive a response from the server later. If this happens often,
236the number of available stream ids diminishes over time, and when it
237goes below a given threshold we close the connection and create a new
238one. If requests are often cancelled, so will see connections being
239recycled at a high rate.
240
241One way to detect this is to monitor open connections per host
242([Session.getState().getOpenConnections(host)][session_state]) against
243TCP connections at the OS level. If open connections stay constant but
244you see many TCP connections in closing states, you might be running
245into this issue. Try raising the speculative execution threshold.
246
247This problem is more likely to happen with version 2 of the native
248protocol, because each TCP connection only has 128 stream ids. With
249version 3 (driver 2.1.2 or above with Cassandra 2.1 or above), there are
25032K stream ids per connection, so higher cancellation rates can be
251sustained. If you're unsure of which native protocol version you're
252using, 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
260Another issue that might arise is that you get unintuitive results
261because of request ordering. Suppose you run the following query with
262speculative executions enabled:
263
264 insert into my_table (k, v) values (1, 1);
265
266The first execution is a bit too slow, so a second execution gets
267triggered. Finally, the first execution completes, so the client code
268gets back an acknowledgement, and the second execution is cancelled.
269However, cancelling only means that the driver stops waiting for the
270server's response, the request could still be "on the wire"; let's
271assume that this is the case.
272
273Now you run the following query, which completes successfully:
274
275 delete from my_table where k = 1;
276
277But now the second execution of the first query finally reaches its
278target node, which applies the mutation. The row that you've just
279deleted is back!
280
281The workaround is to use a timestamp with your queries:
282
283 insert into my_table (k, v) values (1, 1) USING TIMESTAMP 1432764000;
284
285If you're using native protocol v3, you can also enable [client-side
286timestamps](../query_timestamps/#client-side-generation) to have this done
287automatically.