Skip to main content

Prompt Caching ของ Claude Code

การจัดการ cache, actions ที่ทำให้ cache หมดอายุ และอายุของ cache

ภาพรวม

Prompt caching ช่วยลดค่าใช้จ่ายและเพิ่มความเร็วในการตอบสนองของ Claude โดยการ cache ส่วนของ prompt ที่ไม่เปลี่ยนแปลงบ่อย เช่น system prompt, project instructions และ file contents

การทำงานของ Cache

สิ่งที่ถูก Cache

Claude Code จัดระเบียบ cache ตามลำดับความสำคัญ:

  1. System prompt และ instructions - ถูก cache ไว้เสมอ
  2. File contents - cached เมื่อถูกอ่าน
  3. 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
  • /clear command

การ 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:

  1. สรุป conversation ที่ผ่านมา
  2. ลบ history เก่าออก
  3. เก็บ 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 อย่างมีประสิทธิภาพ

  1. รักษา system prompt ให้คงที่ - เปลี่ยนแปลงน้อยที่สุดเพื่อให้ cache hit สูง
  2. หลีกเลี่ยงการ /clear บ่อย ๆ - ทำให้ cache ถูก invalidate
  3. ใช้ CLAUDE.md - ข้อมูลที่นี่จะถูก cache ไว้ตลอด session
  4. Compact แทนที่จะ clear - การ compact รักษา cache บางส่วนไว้

ดูสิ่งที่เกี่ยวข้อง