Migrating from redis-rs
This guide maps redis-rs 1.7 to the
current redis-tower API. Both clients provide typed conveniences, raw commands,
multiplexing, pipelines, transactions, Cluster, Sentinel, TLS, pub/sub, and
RESP3. The migration is primarily about choosing explicit connection and
response contracts, not replacing an “untyped” client with a typed one.
The migration in one table
| redis-rs 1.7 | redis-tower |
|---|---|
MultiplexedConnection | MultiplexedClient |
ConnectionManager | Factory-backed MultiplexedClient, or serialized ResilientRedisClient |
AsyncCommands / AsyncTypedCommands methods | Command values such as Get and Set, passed to execute |
Caller-selected FromRedisValue response | Command-defined response type; RedisValueExt converts at the edge |
Cmd | RawCommand, returning Frame, or TypedRawCommand<T> |
Pipeline / atomic pipeline | Pipeline / Transaction |
| Async pub/sub connection | Dedicated PubSubConnection |
| Async Cluster connection | MultiplexedClusterClient |
| Sentinel client | MultiplexedSentinelClient |
RedisError + ErrorKind | RedisError + classification helpers |
Dependencies
The versions below are the released APIs used by this guide. Choose only the redis-tower topology crates the application needs:
[dependencies]
# Before
redis = { version = "=1.7.0", features = ["tokio-comp", "cluster-async", "connection-manager"] }
# After
redis-tower = "0.1.4"
redis-tower-cluster = "0.1.4" # only for Redis Cluster
redis-tower-sentinel = "0.1.4" # only for Sentinel
bytes = "1"
tokio-stream = "0.1" # only for stream APIs such as pub/sub
For TLS, enable tls-rustls (recommended) or tls-native-tls on the facade and
on each topology crate that opens TLS connections; neither backend is enabled
by the facade’s default feature set. Redis Stack command groups can be selected
individually or through the facade’s default commands-stack feature.
TlsConfig::with_root_ca_pem replaces the default trust roots with every CA in
the supplied PEM bundle for either backend. Rustls loads native roots once per
process, caching the result or loading error; an empty native store falls back
to the webpki bundle, while loading failures with no usable roots return the
loader diagnostics. Restart the process to pick up changes to native roots.
danger_accept_invalid_hostnames(true) works on both backends and matches
redis-rs’s hostname-only bypass: the certificate must still chain to a trusted
root, but its names need not match the connected host or IP. That is the usual
answer for a cluster whose nodes report IPs the certificate does not name.
danger_accept_invalid_certs(true) disables all certificate verification. Both
are dangerous settings. Caller-built ClientConfig / TlsConnector
configurations retain their own verification and trust policy.
The standalone registry compatibility harness is compiled in CI against these exact crates.io versions. It is an independent workspace, so local path crates cannot mask a published-API mismatch. The larger live oracle is documented in Differential testing.
Connect and share
// redis-rs
let redis_rs = redis::Client::open("redis://127.0.0.1:6379/0")?;
let mut connection = redis_rs.get_multiplexed_async_connection().await?;
// redis-tower
use redis_tower::MultiplexedClient;
let client = MultiplexedClient::connect_url("redis://127.0.0.1:6379/0").await?;
Both handles can be cloned and shared across Tokio tasks. Do not add an
Arc<Mutex<_>> around MultiplexedClient; its worker already serializes and
auto-pipelines concurrent requests.
Choose a different redis-tower connection when the ownership contract differs:
RedisConnectionexclusively owns one socket.RedisClientis a simple serialized shared connection.ConnectionPool<RedisConnection>owns multiple independent sockets.- A factory-backed
MultiplexedClientreconnects without giving up concurrent multiplexing. ResilientRedisClientis a simpler reconnecting, mutex-serialized client.
Protocol, URLs, and authentication
The defaults differ. A normal redis-rs 1.7 URL selects RESP2; add
?protocol=resp3 to request RESP3. redis-tower’s default
ProtocolVersion::Auto tries HELLO 3 and falls back to RESP2 when RESP3 is not
available. If wire shape matters during a migration, pin both clients instead
of comparing different protocols:
// redis-rs RESP2
let redis_rs = redis::Client::open("redis://127.0.0.1:6379/?protocol=resp2")?;
// redis-tower RESP2. The released URL parser does not consume `protocol=`;
// select the protocol with ConnectionConfig.
use redis_tower::{ConnectionConfig, MultiplexedClient, ProtocolVersion};
let config = ConnectionConfig::new().with_protocol(ProtocolVersion::Resp2);
let tower = MultiplexedClient::connect_url_with_connection_config(
"redis://127.0.0.1:6379/",
&config,
).await?;
// Use ProtocolVersion::Resp3 to force RESP3 without fallback.
redis://user:password@host/db and rediss://... carry ACL credentials,
database selection, and TLS. Percent-encode URL-special bytes in usernames and
passwords. redis-tower authenticates and selects the database as part of setup;
a reconnecting URL factory repeats those steps on every new socket.
redis-tower’s Unix URL parser accepts authentication, database, and protocol query keys:
redis+unix:///run/redis.sock?user=app&pass=secret&db=1&protocol=resp3
For rotating tokens, replace static URL credentials with redis-tower’s
CredentialProvider. CredentialConnectionFactory::from_url preserves the
URL transport, database, and protocol while taking authentication from the
provider. Its with_setup_timeout covers provider lookup through final session
setup. SharedCredentialProvider gives type-erased hosts one cloneable cache
owner for ordinary, Cluster, and dedicated connections.
redis-rs’s streaming provider is not a signal to inject AUTH into every
socket state. redis-tower owners expose proactive reauthentication only where
they serialize it safely. Pub/Sub reconnects and replays confirmed
subscriptions; MONITOR terminates and reopens with an explicit observation
gap; transactions and blocking operations move to fresh credentials only at a
new operation boundary. See Cloud and rotating credentials.
Typed commands and response shapes
redis-rs command traits select a conversion from the type requested by the caller. redis-tower command values have one public response type:
// redis-rs
use redis::AsyncCommands;
let _: () = connection.set("key", "value").await?;
let value: Option<String> = connection.get("key").await?;
// redis-tower
use redis_tower::commands::{Get, Set};
client.execute(Set::new("key", "value")).await?;
let value: Option<bytes::Bytes> = client.execute(Get::new("key")).await?;
String-shaped Redis data stays binary-safe as Bytes. Convert only at an
application boundary:
use redis_tower::RedisValueExt;
let value: String = client.execute(Get::new("key")).await?.parse_into()?;
SET is one place where choosing a return conversion is not enough. Redis uses
OK, null, and the previous bulk value differently depending on NX, XX, and
GET. The base redis-tower Set keeps its original Option<Bytes> response so
existing code continues to compile, but that compatibility shape maps both
OK and a rejected conditional write to None. Use the additive outcome mode
when the decision matters:
use redis_tower::commands::{Set, SetPreviousValue, SetStatus};
let outcome = client
.execute(Set::new("lease", "owner-a").nx().get().with_outcome())
.await?;
match (outcome.status, outcome.previous) {
(SetStatus::Applied, SetPreviousValue::Missing) => {
println!("lease acquired from an absent key");
}
(SetStatus::NotApplied, SetPreviousValue::Value(owner)) => {
println!("lease already held by {owner:?}");
}
other => println!("other SET outcome: {other:?}"),
}
Call with_outcome() last. Without GET, the status remains unambiguous but
the previous value is SetPreviousValue::NotRequested; with GET, missing,
empty, and arbitrary binary previous values remain distinct.
Do not assume identical public values just because both clients decoded the
same RESP frame. RESP2 may represent a map as a flat array; RESP3 has map, set,
boolean, and verbatim-string types. redis-rs Value, redis-tower Frame, and a
typed command response deliberately expose different layers. Compare the
documented command result, normalizing only semantics Redis declares unordered
or protocol-dependent.
Binary arguments
The published 0.1.4 facade depends on redis-tower-commands 0.1.3, where typed
builders take keys and values as binary-safe CommandArg inputs. Byte slices,
arrays, Vec<u8>, and Bytes pass through unchanged, so opaque data does not
need the raw-command escape hatch:
use redis_tower::commands::{Get, Set};
let key = b"binary:\xff".as_slice();
let payload = vec![0x00, 0xfe, 0xff];
client.execute(Set::new(key, payload)).await?;
let value: Option<bytes::Bytes> = client.execute(Get::new(key)).await?;
RawCommand::arg remains binary-safe for commands without a typed builder. Do
not force opaque data through UTF-8. The per-family inventory and ownership
rules are tracked in Binary data and typed arguments.
Raw commands
// redis-rs
let value: redis::Value = redis::cmd("MYCOMMAND")
.arg("key")
.query_async(&mut connection)
.await?;
// redis-tower
use redis_tower::commands::RawCommand;
let frame = client
.execute(RawCommand::new("MYCOMMAND").arg("key"))
.await?;
RawCommand returns a Frame; validate its shape at the boundary. A typed
builder is preferable when available because it also carries key-routing,
blocking, idempotency, and response-decoding metadata.
Pipelines and transactions
Concurrent MultiplexedClient calls are automatically batched. Use an explicit
Pipeline when one task needs an ordered batch on one connection:
use redis_tower::{Pipeline, RedisConnection};
use redis_tower::commands::{Get, Incr};
let mut connection = RedisConnection::connect("127.0.0.1:6379").await?;
let mut replies = Pipeline::new()
.push(Incr::new("counter"))
.push(Get::new("counter"))
.execute(&mut connection)
.await?;
let count: i64 = replies.take(0)?;
let observed: Option<bytes::Bytes> = replies.take(1)?;
A pipeline is not atomic. Replace redis-rs’s atomic pipeline with
Transaction; its result explicitly distinguishes Committed from Aborted
after a WATCH conflict:
use redis_tower::{Transaction, TransactionResult};
match Transaction::new()
.watch(["counter"])
.push(Incr::new("counter"))
.execute(&mut connection)
.await?
{
TransactionResult::Committed(mut replies) => {
let count: i64 = replies.take(0)?;
let _ = count;
}
TransactionResult::Aborted => { /* rebuild and retry if appropriate */ }
}
For read-compute-write WATCH loops, keep the entire loop on a dedicated
RedisConnection (or another connection instance that the application owns
exclusively for the full loop).
Dedicated and stateful sessions
Do not move every operation onto the default multiplexed client. These APIs need an exclusive or purpose-built session:
- Run
BLPOP, blockingXREAD, and other blocking commands on a dedicatedRedisConnectionor a pool with enough independent connections. One blocking request would otherwise stop the shared pipeline worker. - Construct
PubSubConnectionfrom a freshRedisConnection; it owns subscription state, andreconnect_withcan restore confirmed subscriptions after the application supplies a replacement connection. - Construct
MonitorStreamfrom a freshRedisConnection; entering MONITOR permanently changes that socket’s mode until it is closed. - Keep manual connection-state sequences and read-compute-write WATCH loops on one exclusive connection.
use redis_tower::{PubSubConnection, RedisConnection};
use tokio_stream::StreamExt;
let connection = RedisConnection::connect_url("redis://127.0.0.1:6379").await?;
let mut pubsub = PubSubConnection::from_connection(connection)?;
pubsub.subscribe(&["events"]).await?;
while let Some(message) = pubsub.next().await {
let message = message?;
let _ = message;
}
Cluster and Sentinel
use redis_tower_cluster::MultiplexedClusterClient;
let cluster = MultiplexedClusterClient::connect_url(
"rediss://default:secret@seed.example:6379",
).await?;
use redis_tower_sentinel::MultiplexedSentinelClient;
let sentinel = MultiplexedSentinelClient::connect(
&["127.0.0.1:26379"],
"mymaster",
).await?;
Cluster handles MOVED/ASK routing and topology refresh. Sentinel separates Sentinel-hop and Redis-node credentials/TLS in its builder and verifies the discovered role. Cluster pub/sub makes ownership explicit: fixed-node regular subscriptions and slot-following sharded subscriptions are different APIs.
Reconnection, retry, and unknown execution
redis-rs ConnectionManager reconnects in the background: the command that
observes the dropped connection errors, while later commands wait for the new
connection. redis-tower separates three policies:
- a connection factory recreates and reconfigures the socket;
- reconnect backoff controls when another socket is attempted;
- retry or offline-queue policy decides whether an application command is eligible to be sent again.
A write whose request reached Redis but whose reply was lost has unknown
execution. redis-tower does not blindly replay a non-idempotent command such as
INCR. Applications that retry such work need an idempotency key or a
transaction/script that makes duplication safe.
Tower middleware
redis-tower clients implement tower::Service, so timeout, tracing, metrics,
circuit-breaker, concurrency, and application-specific policy can compose at a
stable request boundary. The built-in layers are documented on the
redis-tower crate. Connection setup timeout,
per-command deadline, Redis’s own blocking timeout, and an end-to-end request
deadline are separate controls; preserve that distinction during migration.
Lessons from an MCP integration
A downstream MCP integration motivated the public differential corpus. The reusable lessons are backed by that repository-local case ledger and executable tests:
- keep redis-rs as an independent oracle instead of sharing redis-tower’s serializers or response conversion;
- define an application response boundary instead of leaking either client’s raw protocol enum through a public schema;
- distinguish top-level server errors from nested per-entry errors;
- exercise RESP2 and RESP3 rather than assuming one public response shape;
- test Cluster routing, blocking sessions, binary/null/error values, cancellation, and lost replies as separate contracts.
The corpus pins redis-rs 1.7.0 and records the intentionally narrow normalizations used for each case.