Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

4.x: Introduce exponential retry backoff policy #483

Open
wants to merge 1 commit into
base: scylla-4.x
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -190,6 +190,20 @@ public enum DefaultDriverOption implements DriverOption {
*/
RETRY_POLICY_CLASS("advanced.retry-policy.class"),

// BACKOFF_RETRY_POLICY is a collection of sub-properties
BACKOFF_RETRY_POLICY("advanced.backoff-retry-policy"),

/**
* The class of the backoff retry policy.
*
* <p>Value-type: {@link String}
*/
BACKOFF_RETRY_POLICY_CLASS("advanced.backoff-retry-policy.class"),

BACKOFF_RETRY_MAX_BACKOFF_MS("advanced.backoff-retry-policy.max-backoff-ms"),
BACKOFF_RETRY_BASE_BACKOFF_MS("advanced.backoff-retry-policy.base-backoff-ms"),
BACKOFF_RETRY_JITTER_RATIO("advanced.backoff-retry-policy.jitter-ratio"),

// SPECULATIVE_EXECUTION_POLICY is a collection of sub-properties
SPECULATIVE_EXECUTION_POLICY("advanced.speculative-execution-policy"),
/**
@@ -537,7 +551,6 @@ public enum DefaultDriverOption implements DriverOption {
* <p>Value-type: {@link java.time.Duration Duration}
*/
METRICS_NODE_CQL_MESSAGES_INTERVAL("advanced.metrics.node.cql-messages.refresh-interval"),

/**
* Whether or not to disable the Nagle algorithm.
*
Original file line number Diff line number Diff line change
@@ -281,6 +281,10 @@ protected static void fillWithDriverDefaults(OptionsMap map) {
map.put(TypedDriverOption.RECONNECTION_BASE_DELAY, Duration.ofSeconds(1));
map.put(TypedDriverOption.RECONNECTION_MAX_DELAY, Duration.ofSeconds(60));
map.put(TypedDriverOption.RETRY_POLICY_CLASS, "DefaultRetryPolicy");
map.put(TypedDriverOption.BACKOFF_RETRY_POLICY_CLASS, "NoBackoffPolicy");
map.put(TypedDriverOption.BACKOFF_RETRY_BASE_BACKOFF_MS, 100);
map.put(TypedDriverOption.BACKOFF_RETRY_MAX_BACKOFF_MS, 10000);
map.put(TypedDriverOption.BACKOFF_RETRY_JITTER_RATIO, 0.1);
map.put(TypedDriverOption.SPECULATIVE_EXECUTION_POLICY_CLASS, "NoSpeculativeExecutionPolicy");
map.put(TypedDriverOption.TIMESTAMP_GENERATOR_CLASS, "AtomicTimestampGenerator");
map.put(TypedDriverOption.TIMESTAMP_GENERATOR_DRIFT_WARNING_THRESHOLD, Duration.ofSeconds(1));
Original file line number Diff line number Diff line change
@@ -199,6 +199,20 @@ public String toString() {
/** The class of the retry policy. */
public static final TypedDriverOption<String> RETRY_POLICY_CLASS =
new TypedDriverOption<>(DefaultDriverOption.RETRY_POLICY_CLASS, GenericType.STRING);
/** The class of the retry policy. */
public static final TypedDriverOption<String> BACKOFF_RETRY_POLICY_CLASS =
new TypedDriverOption<>(DefaultDriverOption.BACKOFF_RETRY_POLICY_CLASS, GenericType.STRING);
/** The class of the retry policy. */
public static final TypedDriverOption<Integer> BACKOFF_RETRY_BASE_BACKOFF_MS =
new TypedDriverOption<>(
DefaultDriverOption.BACKOFF_RETRY_BASE_BACKOFF_MS, GenericType.INTEGER);
/** The class of the retry policy. */
public static final TypedDriverOption<Integer> BACKOFF_RETRY_MAX_BACKOFF_MS =
new TypedDriverOption<>(
DefaultDriverOption.BACKOFF_RETRY_MAX_BACKOFF_MS, GenericType.INTEGER);
/** The class of the retry policy. */
public static final TypedDriverOption<Double> BACKOFF_RETRY_JITTER_RATIO =
new TypedDriverOption<>(DefaultDriverOption.BACKOFF_RETRY_JITTER_RATIO, GenericType.DOUBLE);
Comment on lines +202 to +215
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Descriptions here look incorrect

/** The class of the speculative execution policy. */
public static final TypedDriverOption<String> SPECULATIVE_EXECUTION_POLICY_CLASS =
new TypedDriverOption<>(
Original file line number Diff line number Diff line change
@@ -27,6 +27,7 @@
import com.datastax.oss.driver.api.core.loadbalancing.LoadBalancingPolicy;
import com.datastax.oss.driver.api.core.metadata.NodeStateListener;
import com.datastax.oss.driver.api.core.metadata.schema.SchemaChangeListener;
import com.datastax.oss.driver.api.core.retry.BackoffRetryPolicy;
import com.datastax.oss.driver.api.core.retry.RetryPolicy;
import com.datastax.oss.driver.api.core.session.Session;
import com.datastax.oss.driver.api.core.session.throttling.RequestThrottler;
@@ -95,6 +96,26 @@ default RetryPolicy getRetryPolicy(@NonNull String profileName) {
return (policy != null) ? policy : getRetryPolicies().get(DriverExecutionProfile.DEFAULT_NAME);
}

/**
* @return The driver's retry policies, keyed by profile name; the returned map is guaranteed to
* never be {@code null} and to always contain an entry for the {@value
* DriverExecutionProfile#DEFAULT_NAME} profile.
*/
@NonNull
Map<String, BackoffRetryPolicy> getBackoffRetryPolicies();

/**
* @param profileName the profile name; never {@code null}.
* @return The driver's retry policy for the given profile; never {@code null}.
*/
@NonNull
default BackoffRetryPolicy getBackoffRetryPolicy(@NonNull String profileName) {
BackoffRetryPolicy policy = getBackoffRetryPolicies().get(profileName);
return (policy != null)
? policy
: getBackoffRetryPolicies().get(DriverExecutionProfile.DEFAULT_NAME);
}

/**
* @return The driver's speculative execution policies, keyed by profile name; the returned map is
* guaranteed to never be {@code null} and to always contain an entry for the {@value
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.datastax.oss.driver.api.core.retry;

import com.datastax.oss.driver.api.core.ConsistencyLevel;
import com.datastax.oss.driver.api.core.connection.ClosedConnectionException;
import com.datastax.oss.driver.api.core.connection.HeartbeatException;
import com.datastax.oss.driver.api.core.loadbalancing.LoadBalancingPolicy;
import com.datastax.oss.driver.api.core.servererrors.BootstrappingException;
import com.datastax.oss.driver.api.core.servererrors.CoordinatorException;
import com.datastax.oss.driver.api.core.servererrors.FunctionFailureException;
import com.datastax.oss.driver.api.core.servererrors.OverloadedException;
import com.datastax.oss.driver.api.core.servererrors.ProtocolError;
import com.datastax.oss.driver.api.core.servererrors.QueryValidationException;
import com.datastax.oss.driver.api.core.servererrors.ReadFailureException;
import com.datastax.oss.driver.api.core.servererrors.ReadTimeoutException;
import com.datastax.oss.driver.api.core.servererrors.ServerError;
import com.datastax.oss.driver.api.core.servererrors.TruncateException;
import com.datastax.oss.driver.api.core.servererrors.WriteFailureException;
import com.datastax.oss.driver.api.core.servererrors.WriteType;
import com.datastax.oss.driver.api.core.session.Request;
import edu.umd.cs.findbugs.annotations.NonNull;

/**
* Defines the behavior to adopt when a request fails.
*
* <p>For each request, the driver gets a "query plan" (a list of coordinators to try) from the
* {@link LoadBalancingPolicy}, and tries each node in sequence. This policy is invoked if the
* request to that node fails.
*
* <p>The methods of this interface are invoked on I/O threads, therefore <b>implementations should
* never block</b>. In particular, don't call {@link Thread#sleep(long)} to retry after a delay:
* this would prevent asynchronous processing of other requests, and very negatively impact
* throughput. If the application needs to back off and retry later, this should be implemented in
* client code, not in this policy.
*/
public interface BackoffRetryPolicy extends AutoCloseable {
/**
* Whether to retry when the server replied with a {@code READ_TIMEOUT} error; this indicates a
* <b>server-side</b> timeout during a read query, i.e. some replicas did not reply to the
* coordinator in time.
*
* @param request the request that timed out.
* @param cl the requested consistency level.
* @param blockFor the minimum number of replica acknowledgements/responses that were required to
* fulfill the operation.
* @param received the number of replica that had acknowledged/responded to the operation before
* it failed.
* @param dataPresent whether the actual data was amongst the received replica responses. See
* {@link ReadTimeoutException#wasDataPresent()}.
* @param retryCount how many times the retry policy has been invoked already for this request
* (not counting the current invocation).
*/
int onReadTimeoutBackoffMs(
@NonNull Request request,
@NonNull ConsistencyLevel cl,
int blockFor,
int received,
boolean dataPresent,
int retryCount,
RetryVerdict verdict);

/**
* Whether to retry when the server replied with a {@code WRITE_TIMEOUT} error; this indicates a
* <b>server-side</b> timeout during a write query, i.e. some replicas did not reply to the
* coordinator in time.
*
* <p>Note that this method will only be invoked for {@link Request#isIdempotent()} idempotent}
* requests: when a write times out, it is impossible to determine with 100% certainty whether the
* mutation was applied or not, so the write is never safe to retry; the driver will rethrow the
* error directly, without invoking the retry policy.
*
* @param request the request that timed out.
* @param cl the requested consistency level.
* @param writeType the type of the write for which the timeout was raised.
* @param blockFor the minimum number of replica acknowledgements/responses that were required to
* fulfill the operation.
* @param received the number of replica that had acknowledged/responded to the operation before
* it failed.
* @param retryCount how many times the retry policy has been invoked already for this request
* (not counting the current invocation).
*/
int onWriteTimeoutBackoffMs(
@NonNull Request request,
@NonNull ConsistencyLevel cl,
@NonNull WriteType writeType,
int blockFor,
int received,
int retryCount,
RetryVerdict verdict);

/**
* Whether to retry when the server replied with an {@code UNAVAILABLE} error; this indicates that
* the coordinator determined that there were not enough replicas alive to perform a query with
* the requested consistency level.
*
* @param request the request that timed out.
* @param cl the requested consistency level.
* @param required the number of replica acknowledgements/responses required to perform the
* operation (with its required consistency level).
* @param alive the number of replicas that were known to be alive by the coordinator node when it
* tried to execute the operation.
* @param retryCount how many times the retry policy has been invoked already for this request
* (not counting the current invocation).
*/
int onUnavailableBackoffMs(
@NonNull Request request,
@NonNull ConsistencyLevel cl,
int required,
int alive,
int retryCount,
RetryVerdict verdict);

/**
* Whether to retry when a request was aborted before we could get a response from the server.
*
* <p>This can happen in two cases: if the connection was closed due to an external event (this
* will manifest as a {@link ClosedConnectionException}, or {@link HeartbeatException} for a
* heartbeat failure); or if there was an unexpected error while decoding the response (this can
* only be a driver bug).
*
* <p>Note that this method will only be invoked for {@linkplain Request#isIdempotent()
* idempotent} requests: when execution was aborted before getting a response, it is impossible to
* determine with 100% certainty whether a mutation was applied or not, so a write is never safe
* to retry; the driver will rethrow the error directly, without invoking the retry policy.
*
* @param request the request that was aborted.
* @param error the error.
* @param retryCount how many times the retry policy has been invoked already for this request
* (not counting the current invocation).
*/
int onRequestAbortedBackoffMs(
@NonNull Request request, @NonNull Throwable error, int retryCount, RetryVerdict verdict);

/**
* Whether to retry when the server replied with a recoverable error (other than {@code
* READ_TIMEOUT}, {@code WRITE_TIMEOUT} or {@code UNAVAILABLE}).
*
* <p>This can happen for the following errors: {@link OverloadedException}, {@link ServerError},
* {@link TruncateException}, {@link ReadFailureException}, {@link WriteFailureException}.
*
* <p>The following errors are handled internally by the driver, and therefore will <b>never</b>
* be encountered in this method:
*
* <ul>
* <li>{@link BootstrappingException}: always retried on the next node;
* <li>{@link QueryValidationException} (and its subclasses), {@link FunctionFailureException}
* and {@link ProtocolError}: always rethrown.
* </ul>
*
* <p>Note that this method will only be invoked for {@link Request#isIdempotent()} idempotent}
* requests: when execution was aborted before getting a response, it is impossible to determine
* with 100% certainty whether a mutation was applied or not, so a write is never safe to retry;
* the driver will rethrow the error directly, without invoking the retry policy.
*
* @param request the request that failed.
* @param error the error.
* @param retryCount how many times the retry policy has been invoked already for this request
* (not counting the current invocation).
*/
int onErrorResponseBackoff(
@NonNull Request request,
@NonNull CoordinatorException error,
int retryCount,
RetryVerdict verdict);

/** Called when the cluster that this policy is associated with closes. */
@Override
void close();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.datastax.oss.driver.api.core.retry;

import java.time.Duration;

/**
* The verdict returned by a {@link RetryPolicy} determining what to do when a request failed. A
* verdict contains a {@link RetryDecision} indicating if a retry should be attempted at all and
* where, with what delay, and a method that allows the original request to be modified before the
* retry.
*/
public interface BackoffRetryVerdict extends RetryVerdict {

/** @return a delay that request needs to take before retrying. */
Duration getRetryBackoff();
}
Original file line number Diff line number Diff line change
@@ -38,6 +38,7 @@
import com.datastax.oss.driver.api.core.metadata.Node;
import com.datastax.oss.driver.api.core.metadata.NodeStateListener;
import com.datastax.oss.driver.api.core.metadata.schema.SchemaChangeListener;
import com.datastax.oss.driver.api.core.retry.BackoffRetryPolicy;
import com.datastax.oss.driver.api.core.retry.RetryPolicy;
import com.datastax.oss.driver.api.core.session.ProgrammaticArguments;
import com.datastax.oss.driver.api.core.session.throttling.RequestThrottler;
@@ -150,6 +151,8 @@ public class DefaultDriverContext implements InternalDriverContext {
new LazyReference<>("reconnectionPolicy", this::buildReconnectionPolicy, cycleDetector);
private final LazyReference<Map<String, RetryPolicy>> retryPoliciesRef =
new LazyReference<>("retryPolicies", this::buildRetryPolicies, cycleDetector);
private final LazyReference<Map<String, BackoffRetryPolicy>> backoffRetryPoliciesRef =
new LazyReference<>("backoffRetryPolicies", this::buildBackoffRetryPolicies, cycleDetector);
private final LazyReference<Map<String, SpeculativeExecutionPolicy>>
speculativeExecutionPoliciesRef =
new LazyReference<>(
@@ -367,6 +370,15 @@ protected Map<String, RetryPolicy> buildRetryPolicies() {
"com.datastax.oss.driver.internal.core.retry");
}

protected Map<String, BackoffRetryPolicy> buildBackoffRetryPolicies() {
return Reflection.buildFromConfigProfiles(
this,
DefaultDriverOption.BACKOFF_RETRY_POLICY_CLASS,
DefaultDriverOption.BACKOFF_RETRY_POLICY,
BackoffRetryPolicy.class,
"com.datastax.oss.driver.internal.core.retry");
}

protected Map<String, SpeculativeExecutionPolicy> buildSpeculativeExecutionPolicies() {
return Reflection.buildFromConfigProfiles(
this,
@@ -768,6 +780,12 @@ public Map<String, RetryPolicy> getRetryPolicies() {
return retryPoliciesRef.get();
}

@NonNull
@Override
public Map<String, BackoffRetryPolicy> getBackoffRetryPolicies() {
return backoffRetryPoliciesRef.get();
}

@NonNull
@Override
public Map<String, SpeculativeExecutionPolicy> getSpeculativeExecutionPolicies() {
Original file line number Diff line number Diff line change
@@ -46,6 +46,7 @@
import com.datastax.oss.driver.api.core.metadata.schema.ColumnMetadata;
import com.datastax.oss.driver.api.core.metadata.schema.RelationMetadata;
import com.datastax.oss.driver.api.core.metadata.token.Partitioner;
import com.datastax.oss.driver.api.core.retry.BackoffRetryPolicy;
import com.datastax.oss.driver.api.core.retry.RetryPolicy;
import com.datastax.oss.driver.api.core.servererrors.AlreadyExistsException;
import com.datastax.oss.driver.api.core.servererrors.BootstrappingException;
@@ -606,6 +607,11 @@ public static RetryPolicy resolveRetryPolicy(
return context.getRetryPolicy(executionProfile.getName());
}

public static BackoffRetryPolicy resolveBackoffRetryPolicy(
InternalDriverContext context, DriverExecutionProfile executionProfile) {
return context.getBackoffRetryPolicy(executionProfile.getName());
}

/**
* Use {@link #resolveSpeculativeExecutionPolicy(InternalDriverContext, DriverExecutionProfile)}
* instead.
Loading
Oops, something went wrong.
Loading
Oops, something went wrong.