caching-architecture
БесплатноБез исполняемых скриптовНе проверенLiteLLM-RS response caching architecture. Covers the two-tier deterministic cache (L1 in-memory + optional L2 Redis) behind LLMCache and DualCache, SHA-256…
Об этом скилле
Caching Architecture Guide
Overview
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 — the former unwired semantic (vector) module has been removed from unreleased source.
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
What Is Wired vs Not
| 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 | Removed: core::semantic_cache, cache.semantic_cache, and cache.similarity_threshold no longer exist in unreleased source; remove those config keys, including false/default values |
| 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 |
Configuration
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
These are the only three 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.
- Redis is not configured here: the cache reuses the gateway's Redis pool. Without a pool it runs memory-only (
CacheMode::MemoryOnly). enabled: truewithttl: 0logs an error and leaves the cache off (src/server/state.rs:148).- Validation rejects
enabled: true, ttl: 0outright (src/config/validation/cache_validators.rs:12).
Request Flow
POST /v1/chat/completionscallslookup_chatbefore routing (src/server/routes/ai/chat.rs:112). A hit passesensure_chat_cache_pricing_gateand returns immediately.- On a miss, the provider executes and
store_chatwrites the response (chat.rs:261). Embeddings do the same vialookup_embedding/store_embedding(src/server/routes/ai/embeddings.rs:98,283). - Chat lookups and stores are skipped when the request carries a per-key budget, sets
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. - Chat entries are scoped per caller: identity is
api_key:{id}oruser:{id}, optionally suffixed:max_tokens_per_request:{limit}(cache_identity, response_cache.rs:46). The key does not hash the separate client-suppliedChatCompletionRequest.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 intoEmbeddingRequest.user, butLLMCachecallsgenerate_embedding_keywith nouser_id, and that key does not hashrequest.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). - Cache lookup errors are logged and treated as misses. Gateway startup constructs only
DualorMemoryOnlycaches, andDualsuppresses Redis L2 write failures. A programmatically installedRedisOnlyLLMCachediffers: Redis store errors propagate throughstore_chat/store_embedding, so the route returns an error after the provider call succeeded.
Best Practices
1. Cache Key Determinism
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
Установить caching-architecture в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл caching-architecture?
LiteLLM-RS response caching architecture. Covers the two-tier deterministic cache (L1 in-memory + optional L2 Redis) behind LLMCache and DualCache, SHA-256 cache key generation with schema versioning, TTL and eviction policy, request-path wiring for chat completions and embeddings, cache statistics, and admin endpoints. Use when adding or tuning gateway response caching — cache keys, tiers, TTLs or eviction, cache metrics, or invalidation.
Как установить скилл caching-architecture?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл caching-architecture запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic