캐싱
캐싱 (Caching)
note
OpenAI/Anthropic 프롬프트 캐싱은 여기로 가세요.
LLM 응답을 캐시해요. LiteLLM의 캐싱 시스템은 LLM 응답을 저장·재사용해서 비용을 절약하고 지연을 줄여요. 동일한 요청을 두 번 보내면 LLM API를 다시 호출하는 대신 캐시된 응답을 반환해요.
출처: 문서
본문
지원되는 캐시 (Supported caches)
| 캐시 | cache_params.type | 설정 |
|---|---|---|
| Redis, Valkey, ElastiCache, Memorystore | redis | Redis and Valkey |
| Redis 시맨틱 | redis-semantic | Semantic caching |
| Valkey 시맨틱 | valkey-semantic | Semantic caching |
| Qdrant 시맨틱 | qdrant-semantic | Semantic caching |
| S3 버킷 | s3 | S3 and GCS |
| GCS 버킷 | gcs | S3 and GCS |
| 인메모리 | local | 아래 |
| 디스크 | disk | 아래 |
Redis는 단일 워커를 넘어서는 경우 올바른 기본값이에요. 인메모리 캐시는 한 워커 프로세스 안에 살아있어서, 워커 4개로 프록시를 실행하면 4개의 분리된 캐시를 유지하게 되고 히트율이 대략 워커 수만큼 떨어져요. Redis가 그 밖에 무엇을 제공하는지는 What Needs Redis를 보세요.
정확 일치 캐시(redis, s3, gcs, local, disk)는 전체 요청의 해시를 키로 사용하므로, 대화에 어떤 변화라도 있으면 미스가 돼요. 시맨틱 캐시는 프롬프트를 임베딩하고 유사도 임계값보다 높은 가장 가까운 일치를 서빙하는데, 단발 프롬프트에는 맞고 에이전트형 트래픽에서는 크게 잘못 동작해요. 켜기 전에 Semantic caching을 읽어보세요.
빠른 시작 (Quick start)
1단계: config.yaml에 캐시 추가
cache 키를 config.yaml에 추가하면 캐싱이 활성화돼요.
model_list:
- model_name: gpt-5.6-luna
litellm_params:
model: gpt-5.6-luna
- model_name: text-embedding-ada-002
litellm_params:
model: text-embedding-ada-002
litellm_settings:
set_verbose: True
cache: True # set cache responses to True, litellm defaults to using a redis cache
2단계: .env에 Redis 자격 증명 추가
REDIS_URL = "" # REDIS_URL='redis://username:***@hostname:port/database'
## OR ##
REDIS_HOST = "" # REDIS_HOST='redis-18841.c274.us-east-1-3.ec2.cloud.redislabs.com'
REDIS_PORT = "" # REDIS_PORT='18841'
REDIS_PASSWORD = "" # REDIS_PASSWORD='liteLlmIsAmazing'
네임스페이스, ACL 사용자, 클러스터·센티넬 토폴로지, TLS, IAM 인증, 그리고 REDIS_* 변수의 전체 목록은 Redis and Valkey를 보세요. 캐시 클라이언트의 명령별 타임아웃은 REDIS_SOCKET_TIMEOUT이 아니라 cache_params.socket_timeout(기본 5초)이에요. Redis socket_timeout 참고.
3단계: 콘피그로 프록시 실행
$ litellm --config /path/to/config.yaml
4단계: 테스트
/chat/completions
동일한 요청을 두 번 보내세요:
curl http://0.0.0.0:4000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-5.6-luna",
"messages": [{"role": "user", "content": "write a poem about litellm!"}],
"temperature": 0.7
}'
curl http://0.0.0.0:4000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-5.6-luna",
"messages": [{"role": "user", "content": "write a poem about litellm!"}],
"temperature": 0.7
}'
/embeddings
동일한 요청을 두 번 보내세요:
curl --location 'http://0.0.0.0:4000/embeddings' \
--header 'Content-Type: application/json' \
--data ' {
"model": "text-embedding-ada-002",
"input": ["write a litellm poem"]
}'
curl --location 'http://0.0.0.0:4000/embeddings' \
--header 'Content-Type: application/json' \
--data ' {
"model": "text-embedding-ada-002",
"input": ["write a litellm poem"]
}'
두 번째 응답은 캐시에서 서빙돼요. x-litellm-cache-key 응답 헤더를 같이 보내는데, 이를 /cache/delete에 넘겨줄 수 있어요.
인메모리 캐시와 디스크 캐시 (In memory and disk caches)
둘 다 외부 인프라가 필요 없지만, 워커나 복제본 간에 공유되지도 않아요. 그러니 프로덕션보다는 로컬 개발에 사용하세요.
인메모리 캐시 (In Memory Cache)
litellm_settings:
cache: True
cache_params:
type: local
디스크 캐시 (Disk Cache)
litellm_settings:
cache: True
cache_params:
type: disk
disk_cache_dir: /tmp/litellm-cache # OPTIONAL, default to ./.litellm_cache
캐싱 디버깅 - /cache/ping
LiteLLM 프록시는 캐시가 예상대로 동작하는지 테스트하는 /cache/ping 엔드포인트를 노출해요.
사용법
curl --location 'http://0.0.0.0:4000/cache/ping' \
-H "Authorization: Bearer ***"
예상 응답 - 캐시가 정상일 때
{
"status": "healthy",
"cache_type": "redis",
"ping_response": true,
"set_cache_response": "success",
"litellm_cache_params": {
"supported_call_types": "['completion', 'acompletion', 'embedding', 'aembedding', 'atranscription', 'transcription']",
"type": "redis",
"namespace": "None"
},
"redis_cache_params": {
"redis_client": "Redis<ConnectionPool<Connection<host=redis-16337.c322.us-east-1-2.ec2.cloud.redislabs.com,port=16337,db=0>>>",
"redis_kwargs": "{'url': 'redis://:******@redis-16337.c322.us-east-1-2.ec2.cloud.redislabs.com:16337'}",
"async_redis_conn_pool": "BlockingConnectionPool<Connection<host=redis-16337.c322.us-east-1-2.ec2.cloud.redislabs.com,port=16337,db=0>>",
"redis_version": "7.2.0"
}
}
다음 단계 (Next steps)
무엇을 얼마나 오래 캐시할지 cache controls로 조정하고, 어떤 설정이든 cache_params 참조에서 찾아보거나, 위 표에서 특정 백엔드를 설정해보세요.