Elffuss BraidHub

kikocis/java-driver public

1663c57e5b30 · 11.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
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.4</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
173Regardless of speculative executions, the driver has a retry mechanism:
174
175* on an internal error, it will try the next host;
176* when the consistency level could not be reached (`unavailable` error
177 or read or write timeout), it will delegate the decision to
178 [RetryPolicy][retry_policy], which might trigger a retry on the same
179 host.
180
181Turning speculative executions on doesn't change this behavior. Each
182parallel execution will trigger retries independently:
183
184```ditaa
185client driver exec1 exec2
186--+----------------+--------------+------+---
187 | execute(query) |
188 |--------------->|
189 | | query host1
190 | |------------->|
191 | | |
192 | | unavailable |
193 | |<-------------|
194 | |
195 | |retry at lower CL
196 | |------------->|
197 | | |
198 | | query host2
199 | |-------------------->|
200 | | | |
201 | | server error |
202 | |<--------------------|
203 | | |
204 | | retry on host3
205 | |-------------------->|
206 | | | |
207 | | host1 replies| |
208 | |<-------------| |
209 | complete | |
210 |<---------------| |
211 | | cancel |
212 | |-------------------->|
213```
214
215The only impact is that all executions of the same query always share
216the same query plan, so each host will be used by at most one execution.
217
218[retry_policy]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/RetryPolicy.html
219
220### Tuning and practical details
221
222The goal of speculative executions is to improve overall latency (the
223time between `execute(query)` and `complete` in the diagrams above) at
224high percentiles. On the flipside, they cause the driver to send more
225individual requests, so throughput will not necessarily improve.
226
227You can monitor how many speculative executions were triggered with the
228`speculative-executions` metric (exposed in the Java API as
229[cluster.getMetrics().getErrors().getSpeculativeExecutions()][se_metric]).
230It should only be a few percents of the total number of requests
231([cluster.getMetrics().getRequestsTimer().getCount()][request_metric]).
232
233[se_metric]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Metrics.Errors.html#getSpeculativeExecutions--
234[request_metric]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Metrics.html#getRequestsTimer--
235
236#### Stream id exhaustion
237
238One side-effect of speculative executions is that many requests are
239cancelled, which can lead to a phenomenon called *stream id exhaustion*:
240each TCP connection can handle multiple simultaneous requests,
241identified by a unique number called *stream id*. When a request gets
242cancelled, we can't reuse its stream id immediately because we might
243still receive a response from the server later. If this happens often,
244the number of available stream ids diminishes over time, and when it
245goes below a given threshold we close the connection and create a new
246one. If requests are often cancelled, so will see connections being
247recycled at a high rate.
248
249One way to detect this is to monitor open connections per host
250([Session.getState().getOpenConnections(host)][session_state]) against
251TCP connections at the OS level. If open connections stay constant but
252you see many TCP connections in closing states, you might be running
253into this issue. Try raising the speculative execution threshold.
254
255This problem is more likely to happen with version 2 of the native
256protocol, because each TCP connection only has 128 stream ids. With
257version 3 (driver 2.1.2 or above with Cassandra 2.1 or above), there are
25832K stream ids per connection, so higher cancellation rates can be
259sustained. If you're unsure of which native protocol version you're
260using, you can check with
261[cluster.getConfiguration().getProtocolOptions().getProtocolVersion()][protocol_version].
262
263[session_state]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.State.html
264[protocol_version]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/ProtocolOptions.html#getProtocolVersion--
265
266#### Request ordering and client timestamps
267
268Another issue that might arise is that you get unintuitive results
269because of request ordering. Suppose you run the following query with
270speculative executions enabled:
271
272 insert into my_table (k, v) values (1, 1);
273
274The first execution is a bit too slow, so a second execution gets
275triggered. Finally, the first execution completes, so the client code
276gets back an acknowledgement, and the second execution is cancelled.
277However, cancelling only means that the driver stops waiting for the
278server's response, the request could still be "on the wire"; let's
279assume that this is the case.
280
281Now you run the following query, which completes successfully:
282
283 delete from my_table where k = 1;
284
285But now the second execution of the first query finally reaches its
286target node, which applies the mutation. The row that you've just
287deleted is back!
288
289The workaround is to use a timestamp with your queries:
290
291 insert into my_table (k, v) values (1, 1) USING TIMESTAMP 1432764000;
292
293If you're using native protocol v3, you can also enable [client-side
294timestamps](../query_timestamps/#client-side-generation) to have this done
295automatically.