LiteLLM-RS Caching Architecture. Covers Redis caching, vector database semantic caching, multi-tier cache strategy, TTL management, and cache invalidation patterns.
LiteLLM-RS ships exactly one wired caching subsystem: an exact-match response cache for non-streaming chat completions and embeddings. It is a two-tier read-through cache, not a three-tier stack ā semantic (vector) caching exists as a deprecated, unwired module (see below).
Request (non-streaming /v1/chat/completions, /v1/embeddings)
ā lookup_chat / lookup_embedding (src/server/routes/ai/response_cache.rs)
ā¼
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā LLMCache (src/core/cache/llm_cache.rs) ā
ā chat_cache: DualCache<CachedChatResponse> ā
ā embedding_cache: DualCache<CachedEmbeddingResponse> ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā per-key get / set
ā¼
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā DualCache<T> (src/core/cache/dual.rs) ā
ā L1 InMemoryCache<T> ā DashMap, TTL, sampled eviction ā
ā L2 RedisCache<T> ā optional, backed by RedisPool ā
ā Read: L1 miss ā L2 hit ā repopulate L1 ā
ā Write: both tiers; L2 failure logs a warning, not fatal ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā miss
ā¼
LLM Provider ā response stored back into both tiers
| Capability | Status |
|---|---|
| Exact-match response cache (chat + embeddings) | Wired: AppState.response_cache, built by build_response_cache (src/server/state.rs:143) |
| Semantic similarity cache | Not wired: cache.semantic_cache: true fails startup validation (src/config/validation/cache_validators.rs:16); core::semantic_cache is deprecated since 0.6.0, removal planned in 0.7.0 (src/core/semantic_cache/mod.rs) |
| Vector DB backends | Storage-only: QdrantStore implemented; weaviate/pinecone declared but return "not implemented yet" (src/storage/vector/backend.rs:29). Nothing connects them to caching at runtime |
| Cloud object-storage caches | core::cache::cloud (CloudCache trait; S3/GCS/Azure under feature s3) ā not part of the request path |
cache:
enabled: true # default false; requires ttl > 0
ttl: 3600 # seconds; applied to chat AND embedding entries
max_size: 1000 # max entries per in-memory layer
semantic_cache: false # must stay false ā true fails startup validation
similarity_threshold: 0.95 # parsed but unused while semantic cache is unwired
These are the only five fields (src/config/models/cache.rs:9, deny_unknown_fields). There is no l1/l2/l3 block, redis_url, prefix, exclude_models, or skip_streaming key.
CacheMode::MemoryOnly).enabled: true with ttl: 0 logs an error and leaves the cache off (src/server/state.rs:148).enabled: true, ttl: 0 outright (src/config/validation/cache_validators.rs:12).POST /v1/chat/completions calls lookup_chat before routing (src/server/routes/ai/chat.rs:112). A hit passes ensure_chat_cache_pricing_gate and returns immediately.store_chat writes the response (chat.rs:261). Embeddings do the same via lookup_embedding / store_embedding (src/server/routes/ai/embeddings.rs:98,283).store: true, or was marked bypassed by an upstream handler (should_bypass_chat_cache, src/server/routes/ai/response_cache.rs:25). Embeddings have no such bypass conditions.api_key:{id} or user:{id}, optionally suffixed :max_tokens_per_request:{limit} (cache_identity, response_cache.rs:46). The key does not hash the separate client-supplied ChatCompletionRequest.user, so two requests from the same caller that differ only in that provider-facing field collide. Embedding entries are currently shared across callers: the route copies the identity into EmbeddingRequest.user, but LLMCache calls generate_embedding_key with no user_id, and that key does not hash request.user. Identical model/input embeddings therefore reuse one entry. Streaming chat requests are never cached (LLMCache::get_chat_response_with_user, src/core/cache/llm_cache.rs:280).Dual or MemoryOnly caches, and Dual suppresses Redis L2 write failures. A
programmatically installed RedisOnly LLMCache differs: Redis store errors propagate
through store_chat / store_embedding, so the route returns an error after the
provider call succeeded.Keys come from free functions, not a generator struct. They hash a canonical-JSON payload (sorted keys, transport fields stripped) with SHA-256 under schema version v4:
use litellm_rs::core::cache::{generate_chat_key, generate_chat_key_with_user};
let key = generate_chat_key(&request); // chat:gpt-4:v4:<64-hex>
let key = generate_chat_key_with_user(&request, Some(user)); // user-scoped variant
Do not add non-deterministic fields (request_id, stream, timestamps) ā canonical_json_string already strips the known ones at the top level and inside extra_body. Details: reference/cache-key-generation.md.
// LLMCacheConfig::default() (src/core/cache/llm_cache.rs:55)
chat_ttl: Duration::from_secs(3600), // 1 hour
embedding_ttl: Duration::from_secs(86400), // 24 hours ā embeddings are deterministic
At startup build_response_cache overrides both from cache.ttl, so per-tier TTL tuning requires code changes, not YAML.
The deterministic path already enforces its own skips; do not re-implement them:
// src/core/cache/llm_cache.rs:280 ā streaming requests are never cached
if request.stream.unwrap_or(false) {
return Ok(None);
}
// src/server/routes/ai/response_cache.rs:25 ā chat-only bypasses
fn should_bypass_chat_cache(request: &ChatCompletionRequest, context: &RequestContext) -> bool {
context.metadata.get(BYPASS_CHAT_RESPONSE_CACHE_KEY).and_then(|v| v.as_bool()).unwrap_or(false)
|| context.api_key_budget_id().is_some()
|| request.store == Some(true)
}
The temperature/tools-based filtering you may find in src/core/semantic_cache/validation.rs (should_cache_request) belongs to the deprecated semantic cache and has no runtime effect.
v4 key format, canonicalization policy, CacheKeyBuilder.InMemoryCache<T>: DashMap storage, TTL, sampled eviction, cleanup task.RedisCache<T>: RedisPool usage, key prefix, serializable entry envelope.AtomicCacheStats / CacheStatsSnapshot / CombinedCacheStats, admin status endpoint, collector hooks.