Prompt Caching ของ Claude Code
การจัดการ cache, actions ที่ทำให้ cache หมดอายุ และอายุของ cache
ภาพรวม
Prompt caching ช่วยลดค่าใช้จ่ายและเพิ่มความเร็วในการตอบสนองของ Claude โดยการ cache ส่วนของ prompt ที่ไม่เปลี่ยนแปลงบ่อย เช่น system prompt, project instructions และ file contents
การทำงานของ Cache
สิ่งที่ถูก Cache
Claude Code จัดระเบียบ cache ตามลำดับความสำคัญ:
- System prompt และ instructions - ถูก cache ไว้เสมอ
- File contents - cached เมื่อถูกอ่าน
- Conversation history - ถูก cache เป็นบางส่วน
โครงสร้าง Cache
Session Start
├── System Prompt (cached)
├── CLAUDE.md content (cached)
├── Tool definitions (cached)
└── Conversation
├── Turn 1: User + Assistant (cached after turn)
├── Turn 2: User + Assistant (cached after turn)
└── Turn N: Current (not cached yet)
Actions ที่ทำให้ Cache หมดอายุ (Invalidate)
Cache จะถูก invalidate เมื่อ:
การเปลี่ยนแปลง Configuration
- เปลี่ยน settings files
- เพิ่ม/ลบ MCP servers
- เปลี่ยน model
การเปลี่ยนแปลง Context
- แก้ไขไฟล์ที่อยู่ใน context
- เพิ่มไฟล์ใหม่เข้า context
/clearcommand
การ Compaction
เมื่อ context ถูก compact cache บางส่วนจะถูก invalidate แต่ summary ใหม่จะถูก cache แทน
อายุของ Cache
Cache มีอายุจำกัดตามที่ Anthropic กำหนด:
- Standard cache: 5 นาที
- Extended cache (Anthropic API): สูงสุด 1 ชั่วโมง
ผลกระทบต่อ Token Usage
Cache Hits
เมื่อ cache hit:
- Tokens ที่ cached ใช้ราคา input ที่ถูกกว่า (~90% ลดลง)
- เวลาตอบสนองเร็วขึ้น
Cache Misses
เมื่อ cache miss:
- Tokens ถูกคิดราคาตามปกติ
- Tokens จะถูก cache เพื่อใช้ในรอบต่อไป
Session Compaction
เมื่อ context เต็ม Claude Code จะทำ compaction:
- สรุป conversation ที่ผ่านมา
- ลบ history เก่าออก
- เก็บ summary ไว้ใน context ใหม่
การดู Compaction Status
ดูว่าถูก compact ไปแล้วกี่ครั้งใน session status
Hooks สำหรับ Compaction
ใช้ hooks เพื่อ inject context หลัง compaction:
{
"hooks": {
"SessionStart": [
{
"matcher": "compact",
"hooks": [
{
"type": "command",
"command": "echo 'Reminder: use Bun, not npm. Current sprint: auth refactor.'"
}
]
}
]
}
}
การ Optimize Cache Usage
Tips สำหรับการใช้ Cache อย่างมีประสิทธิภาพ
- รักษา system prompt ให้คงที่ - เปลี่ยนแปลงน้อยที่สุดเพื่อให้ cache hit สูง
- หลีกเลี่ยงการ
/clearบ่อย ๆ - ทำให้ cache ถูก invalidate - ใช้
CLAUDE.md- ข้อมูลที่นี่จะถูก cache ไว้ตลอด session - Compact แทนที่จะ clear - การ compact รักษา cache บางส่วนไว้
ดูสิ่งที่เกี่ยวข้อง
- ./hooks-guide - ใช้ hooks สำหรับ compaction events
- ./interactive-mode - การจัดการ sessions