# Claude Prompt Caching: 10x Maliyet Azalt Rehberi
Prompt caching, Claude API maliyetini dramatik düşürmenin tek en etkili yolu. Doğru kullanıldığında %90 maliyet tasarrufu, daha hızlı response ve daha consistent output. Ama setup'ı yanlış yaparsan hiç tasarruf yok ya da ters tepki (cache miss'te yüksek ücret) yaşarsın. Bu rehber cache breakpoint'leri, TTL seçimleri, minimum 1024 token kuralı, multi-turn pattern'ler ve production'da nasıl ölçeceğinizi detaylı anlatır.
💡 Pro Tip: Prompt caching production'da kullanılmıyorsa %80 ihtimalle LLM API maliyetinizi yarı yarıya azaltabilirsiniz. İlk günde set up etmek kritik.
İçindekiler
- Prompt Caching Nedir
- Nasıl Çalışır: Cache Key
- Cache Breakpoints (Max 4)
- TTL: 5 dk vs 1 saat
- Minimum Token Kuralı
- Fiyatlandırma
- Multi-turn Conversation Pattern
- Tool Definitions Caching
- Production Metrikleri
- Anti-Pattern'ler
Prompt Caching Nedir
Claude, aynı input prefix'i gördüğünde internal state'i "cache"liyor. Sonraki aynı prefix'li request'lerde o kısmı yeniden processing yerine cache'ten okuyor. Sonuç:
- Input cost %90 azalma: $15/1M → $1.50/1M cache read
- Latency düşme: İlk cache hit'te 30-50% hızlı
- Consistency: Aynı prefix = aynı başlangıç durumu
Nasıl Çalışır: Cache Key
Cache key = content hash. Aynı content = aynı cache entry. Küçücük bir karakter değişikliği = cache miss.
python
1# Cache hit2messages=[{"role": "user", "content": LONG_CONTEXT + question_1}]3messages=[{"role": "user", "content": LONG_CONTEXT + question_2}]4# → LONG_CONTEXT cached!5 6# Cache miss (bir boşluk farkı)7messages=[{"role": "user", "content": LONG_CONTEXT + " " + question_1}]8# → Whole thing re-processedKritik: Dynamic data (timestamp, user ID) cache'lenen kısımda olursa her request miss olur.
Cache Breakpoints (Max 4)
Max 4 cache breakpoint per request. Strategic placement:
python
1messages=[{2 "role": "user",3 "content": [4 # Breakpoint 1: Static system instructions (persistent)5 {6 "type": "text",7 "text": SYSTEM_INSTRUCTIONS,8 "cache_control": {"type": "ephemeral"}9 },10 11 # Breakpoint 2: Reference docs (reused across queries)12 {13 "type": "text",14 "text": REFERENCE_DOCS,15 "cache_control": {"type": "ephemeral"}16 },17 18 # Breakpoint 3: User-specific context (stable for session)19 {20 "type": "text",21 "text": USER_CONTEXT,22 "cache_control": {"type": "ephemeral"}23 },24 25 # Breakpoint 4: Conversation history (for multi-turn)26 {27 "type": "text",28 "text": HISTORY,29 "cache_control": {"type": "ephemeral"}30 },31 32 # Query-specific (not cached)33 {34 "type": "text",35 "text": current_question36 }37 ]38}]Order matters: Her breakpoint'ten ÖNCEKİ tüm content cache'lenir. Yani breakpoint 2 = Breakpoint 1 içeriği + kendisi.
TTL: 5 dk vs 1 saat
İki TTL seçeneği:
ephemeral (default, 5 dakika)
- Write cost: 1.25x base input
- Read cost: 0.1x base input
- TTL: 5 dakika (son kullanımdan itibaren)
python
1"cache_control": {"type": "ephemeral"} # 5 dk1 saat (beta)
- Write cost: 2x base input
- Read cost: 0.1x base input
- TTL: 1 saat
python
1"cache_control": {"type": "ephemeral", "ttl": "1h"} # 1 saatSeçim kriteri:
- Session 5 dk'dan kısaysa → 5 dk (write maliyeti düşük)
- Session uzunsa (>5 dk) → 1 saat (5 dk'lık cache rebuild ekonomik değil)
Hidden detail: Cache TTL "son kullanımdan itibaren" — her read cache'i refresh ediyor, böylece aktif kullanım süresince cache yaşar.
Minimum Token Kuralı
Kritik kural: Cache breakpoint için minimum 1024 token gerekir. Altında cache aktivasyonu olmaz.
python
1# ❌ 500 token cached — IGNORE, cache ACTIVATE OLMAZ2{3 "type": "text",4 "text": short_text_500_tokens,5 "cache_control": {"type": "ephemeral"}6}7 8# ✅ 1200 token cached — aktif9{10 "type": "text",11 "text": long_text_1200_tokens,12 "cache_control": {"type": "ephemeral"}13}API bu ihlali silently ignore eder — response'u döner ama cache write olmaz. Log'da görünmez. Bu yüzden cache setup'tan sonra cache_read_input_tokens'i monitor et.
Fiyatlandırma
Model | Base Input | Cache Write | Cache Read | Output |
|---|---|---|---|---|
Opus 4.7 | $15 | $18.75 (1.25x) | $1.50 (0.1x) | $75 |
Sonnet 4.6 | $3 | $3.75 | $0.30 | $15 |
Haiku 4.5 | $0.80 | $1.00 | $0.08 | $4 |
1-hour cache (beta) fiyatları:
- Opus: $30 write (2x), $1.50 read
- Sonnet: $6 write, $0.30 read
- Haiku: $1.60 write, $0.08 read
Multi-turn Conversation Pattern
Long conversation'da history caching kritik:
python
1def build_cached_messages(system_prompt, history, current_query):2 messages = [{"role": "user", "content": [3 # Cache the system prompt (1024+ token)4 {5 "type": "text",6 "text": system_prompt,7 "cache_control": {"type": "ephemeral"}8 },9 # Cache the conversation history (grows over turns)10 {11 "type": "text",12 "text": format_history(history),13 "cache_control": {"type": "ephemeral"}14 },15 # Current query (not cached)16 {17 "type": "text",18 "text": current_query19 }20 ]}]21 return messagesHer turn'de history büyüyor ama system_prompt cached kalıyor — maliyet lineer değil logaritmik artıyor.
Tool Definitions Caching
Tool use ile çalışıyorsan tool definitions'ı cache et:
python
1response = client.messages.create(2 model="claude-opus-4-7",3 tools=[...], # Many tool definitions (large)4 tool_choice={"type": "auto", "cache_control": {"type": "ephemeral"}},5 messages=[{"role": "user", "content": user_input}]6)Tool use agent'larda tool definitions genellikle 5k-20k token — cache ile %90 tasarruf.
Production Metrikleri
Cache etkisini ölç:
python
1response = client.messages.create(...)2print(response.usage)3# {4# "input_tokens": 100, # Yeni input (query)5# "cache_creation_input_tokens": 0, # First call: cache write, sonra 06# "cache_read_input_tokens": 12000, # Cache'ten gelen7# "output_tokens": 5008# }9 10# Metric'ler11total_input = response.usage.input_tokens + response.usage.cache_creation_input_tokens + response.usage.cache_read_input_tokens12cache_hit_rate = response.usage.cache_read_input_tokens / total_inputHedef Metrikler
- Cache hit rate: >%70 (production sessions)
- Cost reduction: >%50 vs no-cache baseline
- Latency reduction: >%20 (cache hit requests)
Prometheus / DataDog'a log at, dashboard kur.
Anti-Pattern'ler
1. Dynamic Data Cached Section'da
python
1# ❌ timestamp cached content'te2cached = f"Current time: {datetime.now()}\n\n{reference_docs}"3# → Her request cache miss2. Variable User ID in System Prompt
python
1# ❌ Her user için farklı cache2system = f"User {user_id} için sistem talimatları\n..."3# → Per-user cache, kaçınılmaz4# ✅ User ID'yi separate section olarak yaz3. Short Prompts Cache
python
1# ❌ 500 token content cached2# → Cache activate olmaz, sessiz başarısızlık4. 5 Breakpoints
python
1# ❌ 5. breakpoint ignored2# → Son breakpoint cache'lenmez5. TTL Seçimi Yanlış
python
1# ❌ 30 saniyelik session için 1-hour TTL2# → Write cost 2x, hiç fayda yokALTIN İPUCU
Bu yazının en değerli bilgisi
Bu ipucu, yazının en önemli çıkarımını içeriyor.
Easter Egg
Gizli bir bilgi buldun!
Bu bölümde gizli bir bilgi var. Keşfetmek ister misin?
python
1# cache_optimizer.py2from anthropic import Anthropic3from dataclasses import dataclass4 5@dataclass6class CacheAnalysis:7 should_cache: bool8 estimated_savings_pct: float9 recommended_ttl: str10 11def analyze_cache_opportunity(12 content: str,13 reuse_frequency: float, # 0-1 (0=one time, 1=always reused)14 session_duration_min: int15) -> CacheAnalysis:16 token_count = estimate_tokens(content)17 18 if token_count < 1024:19 return CacheAnalysis(False, 0, "n/a")20 21 if reuse_frequency < 0.3:22 return CacheAnalysis(False, 0, "n/a")23 24 # Calculate savings25 write_cost = token_count * 18.75 / 1_000_000 # Opus example26 read_cost = token_count * 1.50 / 1_000_00027 no_cache_cost = token_count * 15 / 1_000_00028 29 expected_reads = reuse_frequency * 10 # assumption30 total_cached = write_cost + expected_reads * read_cost31 total_nocache = (expected_reads + 1) * no_cache_cost32 savings = (total_nocache - total_cached) / total_nocache33 34 ttl = "1h" if session_duration_min > 5 else "5m"35 return CacheAnalysis(True, savings * 100, ttl)36 37# Example38analysis = analyze_cache_opportunity(39 content=my_system_prompt,40 reuse_frequency=0.9, # Almost always reused41 session_duration_min=3042)43print(f"Cache? {analysis.should_cache}")44print(f"Savings: {analysis.estimated_savings_pct:.1f}%")45print(f"TTL: {analysis.recommended_ttl}")Okuyucu Ödülü
**External Resources:** - [Prompt caching docs](https://docs.anthropic.com/en/docs/prompt-caching) - [1-hour cache beta](https://docs.anthropic.com/en/docs/prompt-caching#1-hour-cache-ttl) - [Pricing calculator](https://www.anthropic.com/pricing) - [Cache breakpoint best practices](https://docs.anthropic.com/en/docs/prompt-caching#cache-breakpoints) - [Usage metrics API](https://docs.anthropic.com/en/api/messages#response-usage)
Sonuç
Prompt caching = production Claude API kullanımının en önemli optimization'ı. %90 maliyet azaltma, %20+ latency düşüş, consistent output. 4 cache breakpoint, 1024 token minimum, dynamic data'yı cached section'dan uzak tutma — bu kuralları takip ederek ayda binlerce dolar tasarruf edebilirsin. Sunucu tarafında implementation 1-2 günlük iş, ROI olarak %500+ geri dönüş. Ekip LLM kullanıyorsa, caching DevRel/Engineering'in ilk hafta çözmesi gereken priority.
*İlgili yazılar: Opus 4.6, Opus 4.7 Strategy, 1M Context.*

