mirror of
https://github.com/BerriAI/litellm.git
synced 2026-11-30 01:08:33 +00:00
Some checks failed
Cost map pins recheck / rerun-cost-map-guard (push) Has been cancelled
LiteLLM Rust DB / db-queries (push) Has been cancelled
LiteLLM Rust / rust-lint (push) Has been cancelled
LiteLLM Rust / rust-test (push) Has been cancelled
LiteLLM Rust / rust-wheel (push) Has been cancelled
Terraform Modules / fmt, validate, test (aws) (push) Has been cancelled
Terraform Modules / fmt, validate, test (gcp) (push) Has been cancelled
Adds publish(channel, payload) through the guarded command path and subscribe(channel), a Stream of raw payloads on its own RESP3 connection that resubscribes after a lost connection with the Python subscriber's 5s to 60s backoff, on standalone, cluster and Sentinel. Channel names skip the namespace, matching the Python publisher, so the auth cache invalidation channel can move onto the Rust client Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
12 KiB
12 KiB
- The one async Redis client for the gateway and the Rust cache crates. It owns connecting, timeouts, error classes and the key namespace
- It knows nothing about domains, so key builders, TTL policy, value formats and fallback decisions stay in the crate that owns the state. Every write takes its TTL from the caller, and there is no default
- Async only. Build one
RedisClientper Redis instance at the process boundary and clone it. Never add a pool, a sync API,spawn_blocking, or a client built inside a route - Every connection sets TCP_NODELAY, like redis-py's
socket.setsockopt(IPPROTO_TCP, TCP_NODELAY, 1). Set every redis-rs timeout and retry explicitly, citing the redis-py 5.3.1 orlitellm/source next to each constant. Its defaults (500ms response, 1s connect, 6 reconnect retries) are not the Python proxy's.Timeoutstakessocket_timeoutandsocket_connect_timeout, and the connect timeout falls back to the socket timeout like redis-py. Standalone reconnects on the next command with no retry of the failed one, matching redis-py'sRetry(NoBackoff(), 0). Cluster keeps redis-py's 3cluster_error_retry_attemptsand waits a flat 250ms between them, which is redis-py's CLUSTERDOWN sleep. redis-py's jittered per-node reconnect backoff has no redis-rs equivalent. The retry set also differs, redis-rs retries LOADING and READONLY internally, while redis-py 5.3.1 raises them. Do not claim exact retry parity - Resolving config from
config.yaml/REDIS_*env the waylitellm/_redis.pydoes belongs to the consumer that reads that config, not here.RedisConfigtakes already-resolved values
Errors
Transport,Server,Decode, each wrapping the redis-rs error as#[source].ConnectErroris separate because onlyconnectreturns it- Classify with
Error::classify(error, deployment), never a bareFrom<RedisError>, because redis-py (5.3.1) decides by topology.Transportis what Python's_redis_health_error_typescounts: LOADING everywhere, CLUSTERDOWN and MASTERDOWN only on cluster (onlyClusterParsermaps them), READONLY only under Sentinel (whereSentinelManagedConnectionturns it intoConnectionErrorand rediscovers), plus NOAUTH, WRONGPASS and theERRmessages redis-py maps toConnectionError, matched exactly likeparse_error. TRYAGAIN isServer, since the cluster client already retried it. Each code gets its own rstest case built from a parsed RESP error - A
Servererror never drops the connection Transportincludes timeouts, where the command may still have applied. Callers of counters and locks treat it as an unknown outcome- Never swallow an error or turn it into a miss. The caller picks the fallback
- Reads return
Option<T>: a missing key isNone, and a value that doesn't decode toT("15.0"asi64) isDecode
Circuit breaker
- The
litellm-circuit-breakerBreakeris injected throughRedisConfig::breakerand shared by every clone.Noneturns it off - Every public call (each command,
eval, onerunof a pipeline) takes one admission throughguarded/admitinclient.rs. Never call the connection around it Transportcounts as a failure (Timeoutwhenis_timeout(), elseHard).ServerandDecodecount as nothing, since Redis answered and the request was bad. A probe that gets one still reopens, through the dropped-probe rule incircuit-breaker. A pipeline counts one failure if any op came backTransport, else one success- An open breaker returns
Error::BreakerOpenwithout touching the socket
Namespace
- Applied once, here, to every key. A key that already starts with
{namespace}:is left alone, matchingRedisCache.check_and_fix_namespace - The rule never changes, because Python and Rust pods share keys in the same Redis
Commands
- One typed method per command, built with
redis::cmd. Empty batches (MGET, DEL) return without a round trip, since Redis rejects an empty MGET - On cluster, redis-rs splits MGET and DEL by slot and returns MGET values in input order. Other multi-key commands are not split, so a new one needs a cross-slot test
- Every command is the one
RedisCachesends, argument for argument, soMONITORon a mixed fleet shows one shape. A difference from main's Python is a defect even when the result is the same - TTLs are
Durationand are sent in whole seconds (SET ... EX,EXPIRE,TTL), like redis-py'sint(ttl).set_nxsendsEXbeforeNX, the order redis-py builds - Numbers go out as
Amount, written the way redis-py encodes them: anintwithstr()and afloatwithrepr()frompython-compat - Increments are plain commands, never a script.
incr_byisincrement_cache:INCRBY,TTL, thenEXPIREonly on a key with no TTL, each its own round trip.incr_by_floatisasync_increment:INCRBYFLOATwithEXPIRE(Expiry::Refresh) orTTL(Expiry::KeepExisting) in one round trip, and forKeepExistinga third,EXPIRE, only on a key with no TTL. In a pipelineincr_by_floatisRedisBatch's_Increment,INCRBYFLOATthenEXPIREwhen a TTL is given
Scripts and pipelines
- A
Scriptdeclares every key it touches in KEYS. On cluster an undeclared key works or fails depending on which node owns its slot, so it can pass tests and break in production evalgoes through redis-rsinvoke_async, which loads the script on NOSCRIPT. Inside a pipeline a script is sent asEVALSHA, likeRedisBatch. ANOSCRIPTreply means that op ran nothing, so it alone runs again after the pipeline throughinvoke_async(EVALSHA,SCRIPT LOAD,EVALSHA), likeRedisBatch's_settle_alone. It then lands after the ops around it, as it does in PythonEntrykeeps a script call apart from plain commands, and the one resend takes only aScriptCallwhose reply wasNOSCRIPT. Nothing can resend a pipeline or a command that already ran, so a retry can never apply an increment twice- A pipeline is never atomic. Every op gets its own
Result, from.ignore_errors(), so one rejected op leaves the others alone. A transport failure fails every op of that round trip - redis-rs rejects an async cluster pipeline whose ops span slots.
Pipelinegroups ops by the slot of their first key and runs the slots concurrently, returning results in input order. Within a slot, runs of idempotent ops (GET, SET, DEL, EXPIRE) share a request and every script op gets its own, sent in order. redis-rs retries a cluster request whole, so a script op batched with others would be applied twice when only a neighbour failed - Pipeline ops take one key each. A multi-key op would span slots inside one group. An op can send more than one command for that key (
INCRBYFLOATthenEXPIRE), and settles from the first reply, failing if any of its replies failed - Command builders live in
commands.rsand are shared byRedisClientandPipeline, so a command is written once
Pub/sub
- Classic
PUBLISH/SUBSCRIBE, never sharded, since redis-py publishes and subscribes through one plain client and cluster broadcasts classic messages to every node. Payloads are raw bytes, and the codec belongs to the store that owns the channel - Channel names never get the namespace. Python builds
{namespace}:{channel}itself, so the store does too publishis a command like any other, guarded by the breaker and reported to eventssubscribereturns aStreamthat opens its own RESP2PubSubconnection when first polled, like redis-py'sPubSub, to the endpoint, the first reachable cluster node, or the master Sentinel names at that moment. It never touches the breaker or events, like Python's subscriber, which reads off its own connection- After a lost connection or a failed subscribe it waits and resubscribes, 5s doubling to 60s and reset by a successful subscribe, like
AuthCacheInvalidationSubscriber._run. Messages published while it is down are lost. The connection has no idle ping, so a socket that dies silently is only noticed by TCP - redis-rs's
PubSubtakes no credentials provider, so a provider is asked for its current credentials once when the subscription connects, which is when redis-py's pubsub connection asks it. The connect is bounded by the connect timeout
Batches
RedisBatchis litellm'sRedisBatch(litellm/caching/redis_batch.py). It keeps each declared op as data and, on a standalone or Sentinel Redis, sends them later as onePipeline, so it inherits every pipeline rule above. On a cluster it never pipelines and runs each op on its own, concurrently, the way_settle_alonecalls theRedisCachemethod behind it. An increment there keeps a TTL the key already has, asasync_incrementdoes, where the pipelined one refreshes it like_Incrementmgetis oneMGETof the keys in order with repeats read once, like_MGet. Use it instead of onegetper key whenever Python reads several keys in one call It knows nothing about requests. The host that owns a request (Axum handler, pyo3 adapter) builds one and passes it down as a value, never through a task-local- Each op returns a
Declared<T>backed by a oneshot.flushsends everything declared so far, one flush at a time, and an empty flush makes no round trip.resolveflushes only when its op has not gone out yet, so an op declared after another caller resolved costs a second round trip. Stages that know their reads up front declare all of them and callflushonce - An op whose flush was cancelled resolves as
Transport, because it may already have reached Redis settledwaits for whichever flush carries the op and never sends one itself, for follow-ups that must not force a flush.RedisClient::same_clienttells clones of one client apart from a second connection, so a host can keep one batch per client- Against real Redis from
litellm-redis-testing, never a mocked wire or asserted command bytes - Tests that only need the public API live in
tests/<module>.rs, with client builders intests/support. Inline#[cfg(test)]modules are only for private items (error.rs,namespace.rs) - Observe connections from the server side (
RedisDeployment::clients,cli_on_every_node), never by reaching intoRedisClient's connection - Every command test runs on each topology through
#[values(Topology::Standalone, Topology::Cluster)]. A test is single-topology only when the behavior exists on one (adbnumber has no cluster meaning) - Assert values and Redis state. Outages come from the container (
restart,freeze/thaw), notDEBUG, which the official image disables - Use a short client timeout in outage tests so they stay fast. Never sleep to wait for a state; poll with a deadline
TLS, credentials and Sentinel
TlsOptionsfollows redis-py 5.3.1. It verifies the certificate by default, skips the hostname check by default (ssl_check_hostname=False), and trusts the system roots plusca_certs- rustls only reads unencrypted keys, so a PKCS#8
ENCRYPTED PRIVATE KEYis decrypted withkey_passwordbefore it reaches redis-rs. A legacyProc-Type: 4,ENCRYPTEDPEM key is refused withKeyError::LegacyEncryptionrather than decrypted by hand-rolled OpenSSL key derivation - redis-rs loads the system trust store for every TLS connection and fails if that fails, even with
ca_certsset. Where the macOS keychain is blocked (agent sandboxes), run the TLS tests withSSL_CERT_FILE=/etc/ssl/cert.pem Credentials::Staticare sent at connect, and URL userinfo wins over them, like redis-py'sfrom_urlCredentials::Providerwraps a redis-rsStreamingCredentialsProvider. redis-rs takes the first item at connect and re-AUTHs live connections on every later item, on each cluster node. Providers push, redis-rs never polls. With a provider, redis-rs overwrites URL userinfo at connect, which matches Python strippinguser:pass@from the URL- Sentinel discovers the master on each new connection and drops it on a transport failure or READONLY, like redis-py's
SentinelConnectionPool - Sentinel monitors get
sentinel_password, the data username when that password is set, and the TLS mode and certificates. Python's_sentinel_auth_kwargsforwards every other connection kwarg too, and it sends the username even without a sentinel password - A
Debugimpl never shows a secret. Follow.agents/skills/rust-redaction