userver: Valkey/Redis
Loading...
Searching...
No Matches
Valkey/Redis

Quality: Platinum Tier.

The redis asynchronous driver provides an interface to work with Valkey or Redis standalone instances, as well as Valkey/Redis Sentinels and Clusters.

Take note that Valkey/Redis is not able to guarantee a strong consistency. It is possible for Valkey/Redis to lose writes that were acknowledged, and vice versa.

Main features

  • Convenient methods for Valkey/Redis commands returning proper C++ types
  • Support for bulk operations (MGET, MSET, etc). Driver splits data into smaller chunks if necessary to increase server responsiveness
  • Support for different strategies of choosing the most suitable server instance
  • Request timeouts management with transparent retries
  • TLS connections support
  • Deadline propagation
  • Cluster autotopology

Valkey/Redis Guarantees

Valkey/Redis is not a reliable database by design. In case of problems on the database side, partial or complete loss of data is possible. When a master migrates, the entire cluster may become unavailable for several tens of seconds. The specific latency value should be determined for each configuration separately (depending on the size of the database, server location, etc.).

Every command that is sent to the server has the potential to fail. Moreover, the client may receive error information (for example, a timeout), but the command on the server may succeed. Therefore, Valkey/Redis commands should be idempotent. If this is not possible for some reason, then care should be taken to ensure that incomplete groups of commands/resent commands do not leave the database in an inconsistent state.

A Valkey/Redis command has a timeout, a number of retries, and a global timeout. If a response is not received from the server within the timeout, then the same command is sent to another server in the cluster, and so on either until the limit on the number of repetitions is reached, or when the global timeout is reached. These settings can be changed via storages::redis::CommandControl.

Warning
For the above reasons, it is recommended to prefer PostgreSQL database over Valkey/Redis. However it is fine to use Valkey/Redis as a distributed cache.

Metrics

Metric name Description
redis.instances_count current number of Redis instances
redis.last_ping_ms last measured ping value
redis.is_ready 1 if connected and ready, 0 otherwise
redis.not_ready_ms milliseconds since last ready status
redis.reconnects reconnect counter
redis.session-time-ms milliseconds since connected to instance
redis.timings query timings
redis.errors counter of failed requests

See Retrieving Service Statistics and Metrics (Prometheus/Graphite/...) and Default Metrics Description for info on how to get the metrics.

Usage

To use Valkey or Redis you must add the component components::Redis and configure it according to the documentation. After that you can make requests via storages::redis::Client:

void RedisClientSampleUsage(storages::redis::Client& client) {
client.Rpush("sample_list", "a", {}).Get();
client.Rpush("sample_list", "b", {}).Get();
const auto length = client.Llen("sample_list", {}).Get();
EXPECT_EQ(length, 2);
}

Also see Valkey/Redis service for a complete example.

Optimistic transactions

Valkey 9.2 and newer support optimistic transactions with conditional EXEC. Pass storages::redis::ExecOptions to storages::redis::Transaction::Exec:

using storages::redis::ExecCondition;
const std::string expected_version = "1";
const std::string next_version = "2";
const std::string new_balance = "100";
auto transaction = client->Multi();
auto set = transaction->Set("{account}balance", new_balance);
auto version = transaction->Set("{account}version", next_version);
transaction
->Exec(
command_control,
{
ExecCondition::IfEq("{account}version", expected_version),
ExecCondition::Xx("{account}balance"),
}
)
.Get();
set.Get();
version.Get();

See the Valkey EXEC documentation for the supported conditions and the Valkey transaction documentation for their semantics.

If a condition fails, Exec().Get() and the subcommand requests throw storages::redis::TransactionAbortedException. Read the current values again before constructing a new transaction to retry. Server and transport errors retain their usual exception types.

Conditional transactions run on the master. Keys in commands and conditions must belong to the same shard, and to the same hash slot in cluster mode. An empty storages::redis::ExecOptions is equivalent to ordinary Exec and works with older servers. The conditions are consumed during Exec, so an initializer list can be passed directly.

To mock conditional transactions, override storages::redis::MockTransactionImplBase::Exec: return storages::redis::MockTransactionImplBase::ExecResult::kExecuted to execute the mocked subrequests, or storages::redis::MockTransactionImplBase::ExecResult::kAborted to report a transaction abort. The default mock rejects non-empty conditions so that they cannot be silently ignored.

Timeouts

Request timeout can be set for a single request via storages::redis::CommandControl argument.

Dynamic option REDIS_DEFAULT_COMMAND_CONTROL can be used to set default values.

To interrupt a request on the client side, you can use cancellation mechanism to cancel the task that executes the Redis request:

std::optional<std::string> RedisClientCancelRequest(storages::redis::Client& client) {
auto result = client.Get("foo", {});
// Throws redis::RequestCancelledException if Redis was not
// fast enough to answer
return result.Get();
}

Valkey/Redis driver does not guarantee that the cancelled request was not executed by the server.

Retries and retry budgets

The driver retries timeouts, I/O errors, closed connections, and the server errors LOADING, MASTERDOWN, READONLY, CLUSTERDOWN, and TRYAGAIN within the command's attempt limit and overall timeout. Other errors, including server OOM, local out-of-memory errors, protocol errors, invalid commands, and unknown server errors, are returned without retrying. NOSCRIPT is returned to the caller so that it can load the script before issuing another request.

The dynamic option REDIS_RETRY_BUDGET_SETTINGS controls a separate retry budget for each connection. It applies to reads, writes, requests with an explicit server ID, and MOVED/ASK redirects. The first attempt is allowed regardless of the remaining budget; further attempts require an available budget on the target connection. When a redirected request cannot be admitted, the original redirect error is returned to the caller.

Successful replies replenish the budget, and retryable errors decrease it. Nonretryable errors and redirects leave the budget unchanged. Disabling the budget does not enable retries for nonretryable errors. Applications issuing manual retries must set storages::redis::CommandControl::retry_counter.

Valkey/Redis Cluster Autotopology

Cluster autotopology makes it possible to do resharding of the cluster without Secdist changes and service restart.

With this feature entries in the Secdist are now treated not as a list of all the cluster hosts, but only as input points through which the service discowers the configuration of the entire cluster. Therefore, it is not recommended to delete instances that are listed in secdist from the cluster.

The cluster configuration is checked

  • at the start of the service
  • and periodically
  • and if a MOVED response is received from Valkey/Redis

If a change in the cluster topology was detected during the check (hashslot distribution change, master change, or new replicas discowered), then the internal representation of the topology is recreated, the new topology is gets ready (new connections may appear in it), and after that the active topology is replaced.