Cache trong LLMCaching in LLMs

Cache là phép khớp tiền tố.Caching is a prefix match.

Một byte khác ở đầu request là mọi thứ phía sau phải tính lại. Bấm các thao tác dưới đây để xem một phiên Claude Code trả giá thế nào. Change one byte near the start of a request and everything after it is recomputed. Try the actions below to see what a Claude Code session pays.

Mỗi hàng là một request gửi lên APIEach row is one request sent to the API

Tools + system → CLAUDE.md → hội thoạiTools + system → CLAUDE.md → conversation

Token đọc từ cacheTokens read from cache0%
Cả phiên trả so với không cacheSession cost vs. no cache0%
Đọc cache (0,1×)Cache read (0.1×) Ghi mới (1,25×)New write (1.25×) Ghi lại thứ từng có trong cache (1,25×, lãng phí)Rewriting what was already cached (1.25×, wasted)

Số token là ước lượng để minh hoạ. Hệ số giá theo Anthropic, TTL 5 phút.Token counts are illustrative estimates. Price multipliers per Anthropic, 5-minute TTL.

Chọn cái nàoWhich one to use

Hỏi câu "có cần không" trước câu "dùng cái nào".Ask "do I need it" before "which one".

  1. Bạn dùng Claude Code trực tiếp?Using Claude Code directly?

    KhôngNoBạn tự gọi API, đi tiếpYou call the API yourself, continue
  2. Có tiền tố đủ dài lặp lại giữa các request trong vòng 5 phút?Is a long enough prefix repeated across requests within 5 minutes?

    KhôngNoKhông cache. Xem khung bên trái.No cache. See the box on the left.
  3. Nhiều request chung tiền tố cần chạy cùng lúc?Do several requests sharing it need to run at once?

    CóYesO2Làm ấm bằng 1 request rồi fan-outWarm with 1 request, then fan out Không bắn song song khi cache lạnh.Never fire in parallel on a cold cache.
  4. Người dùng hay hỏi lại cùng một câu?Do users repeat the same question?

Sáu khái niệm, bốn tầngSix concepts, four layers

Mã chữ cho biết cache sống ở tầng nào. Màu theo tầng, xem quy ước ở cuối trang.The letter code tells you which layer the cache lives in. Colors follow the layer; see the key at the bottom.

M1

KV cache

Tầng modelModel layer

Giữ Key/Value của các token đã xử lý trong VRAM để sinh token tiếp theo mà không tính lại attention cho cả chuỗi.Keeps the Keys/Values of processed tokens in VRAM so the next token is generated without recomputing attention over the whole sequence.

Đổi bộ nhớ GPU lấy tốc độ sinh token.Trades GPU memory for token generation speed.

Dùng choUse for
Mọi lần sinh văn bản; quan trọng khi tự host nhiều người dùng đồng thời.Every generation; critical when self-hosting many concurrent users.
ĐượcGain
Decode tuyến tính thay vì bình phương; nền móng cho prompt cache.Linear instead of quadratic decode; foundation of prompt caching.
MấtCost
128 KB mỗi token với Llama 3 8B fp16, tức khoảng 1 GB cho một ngữ cảnh 8K. VRAM hết trước sức tính.128 KB per token for Llama 3 8B fp16, about 1 GB for one 8K context. VRAM runs out before compute.

Dấu hiệu:Tell: GPU còn sức tính nhưng hết bộ nhớ khi tăng người dùng hoặc độ dài prompt.The GPU has compute to spare but runs out of memory as users or prompt length grow.

P1

Prompt cache

Tầng nhà cung cấpProvider layer

Giữ kết quả prefill của một tiền tố giữa các request. Request sau có cùng tiền tố thì đọc lại thay vì tính.Keeps the prefill result of a prefix across requests. A later request with the same prefix reads it instead of recomputing.

Đổi kỷ luật giữ tiền tố bất biến lấy input rẻ hơn 10 lần và token đầu đến nhanh hơn.Trades the discipline of an immutable prefix for 10× cheaper input and a faster first token.

Dùng choUse for
Agent như Claude Code, hỏi đáp trên tài liệu dài, few-shot nhiều ví dụ.Agents like Claude Code, Q&A over long documents, many-shot prompts.
ĐượcGain
Đọc cache 0,1× giá input; một lần hit đã hoà vốn.Cache reads at 0.1× input price; one hit already breaks even.
MấtCost
Ghi 1,25× (TTL 5 phút) hoặc 2× (1 giờ). Lệch một byte là miss. Request đồng thời không dùng chung được cache lạnh.Writes at 1.25× (5-min TTL) or 2× (1 hour). One byte off is a miss. Concurrent requests can't share a cold cache.

Dấu hiệu:Tell: Một khối hướng dẫn hoặc tài liệu lớn, cố định, lặp lại ở mọi request trong vài phút.A large, fixed block of instructions or documents repeats on every request within minutes.

A1

Exact-match cache

Tầng ứng dụngApplication layer

Lưu câu trả lời, khoá bằng hash của toàn bộ request. Giống hệt thì trả ngay, không gọi model.Stores the answer, keyed by a hash of the whole request. Identical requests return instantly without calling the model.

Đổi độ tươi và sự đa dạng của câu trả lời lấy chi phí bằng 0 cho câu hỏi lặp y hệt.Trades freshness and variety of answers for zero cost on exactly repeated questions.

Dùng choUse for
CI và bộ test, pipeline chạy lại, nút câu hỏi gợi ý trong UI.CI and test suites, rerunnable pipelines, canned question buttons.
ĐượcGain
0 token, vài mili giây, kết quả xác định.Zero tokens, milliseconds, deterministic output.
MấtCost
Thêm một dấu cách là miss. Trả lời cũ khi dữ liệu nguồn đã đổi.One extra space is a miss. Stale answers when source data changes.

Dấu hiệu:Tell: Chuỗi request do code tạo ra, không phải người gõ.The request string is produced by code, not typed by a person.

A2

Semantic cache

Tầng ứng dụngApplication layer

Lưu câu trả lời, khoá bằng embedding. Câu hỏi mới đủ gần về nghĩa thì trả lại câu trả lời cũ.Stores answers keyed by embedding. A new question close enough in meaning gets the old answer.

Đổi một tỷ lệ trả lời sai có kiểm soát lấy tỷ lệ trúng cao hơn hẳn exact-match.Trades a controlled rate of wrong answers for a much higher hit rate than exact-match.

Dùng choUse for
Chatbot FAQ, tìm kiếm nội bộ có câu trả lời chung cho mọi người.FAQ bots, internal search where the answer is the same for everyone.
ĐượcGain
Trúng cả khi diễn đạt khác; một hit chỉ tốn một lần gọi embedding.Hits across rephrasings; a hit costs one embedding call.
MấtCost
"Huỷ đơn" và "huỷ gói" có thể trúng nhau. Rò rỉ dữ liệu nếu dùng chung giữa người dùng."Cancel order" can match "cancel plan". Leaks data if shared across users.

Dấu hiệu:Tell: 20% chủ đề chiếm 80% lượt hỏi, mỗi chủ đề được diễn đạt nhiều cách.20% of topics make up 80% of questions, each phrased many ways.

O1

Chạy tuần tựSequential

Tầng điều phốiOrchestration layer

Request sau chỉ bắt đầu khi request trước xong. Mỗi lượt mở rộng đúng tiền tố của lượt trước.Each request starts only after the previous one finishes. Each turn extends exactly the previous prefix.

Đổi thời gian chờ lấy tỷ lệ trúng cache gần như tuyệt đối.Trades wall-clock time for a near-perfect cache hit rate.

Dùng choUse for
Hội thoại nhiều lượt, agent loop gọi tool, chuỗi biến đổi phụ thuộc nhau.Multi-turn chats, agent tool loops, dependent transformation chains.
ĐượcGain
Gần 100% token đọc từ cache sau lượt đầu.Near 100% of tokens read from cache after the first turn.
MấtCost
Tổng thời gian bằng tổng từng request. Nghỉ quá 5 phút là mất cache.Total time is the sum of all requests. A gap over 5 minutes loses the cache.

Dấu hiệu:Tell: Bước sau cần kết quả của bước trước.The next step needs the previous step's result.

O2

Làm ấm rồi fan-outWarm-then-fan-out

Tầng điều phốiOrchestration layer

Gửi một request ghi cache trước, chờ nó bắt đầu trả về, rồi bắn đồng loạt phần còn lại.Send one request to write the cache, wait for it to start returning, then fire the rest at once.

Đổi độ trễ của đúng một request đầu lấy chi phí ngang tuần tự với tốc độ gần bằng song song.Trades one first request's latency for sequential-level cost at near-parallel speed.

Dùng choUse for
Nhiều câu hỏi độc lập trên cùng tài liệu, eval trên nhiều test case, nhiều subagent cùng loại.Independent questions over one document, evals across many cases, many same-type subagents.
ĐượcGain
Với 10 request: chi phí tiền tố 2,15P thay vì 12,5P của song song lạnh.For 10 requests: prefix cost 2.15P instead of 12.5P for cold parallel.
MấtCost
Thêm độ trễ một request ở đầu đợt; dưới tải cao vẫn có thể miss vài request.One request's latency up front; a few may still miss under heavy load.

Dấu hiệu:Tell: N việc độc lập, chung một tiền tố lớn, cần xong trong vài phút.N independent tasks sharing one large prefix, needed within minutes.

Claude Code: thao tác nào làm vỡ cacheClaude Code: which actions break the cache

Claude Code tự quản lý prompt cache. Mỗi request gồm ba tầng; vỡ ở tầng nào thì tầng đó và mọi tầng bên phải phải xử lý lại.Claude Code manages prompt caching itself. Each request has three layers; a break at one layer reprocesses it and every layer to its right.

System prompt

Hướng dẫn lõi, định nghĩa tool, output styleCore instructions, tool definitions, output style

Vỡ khi tập tool đổi hoặc nâng cấp Claude CodeBreaks when the tool set changes or Claude Code upgrades

Project context

CLAUDE.md, auto memory, rules

Dựng lại khi bắt đầu phiên, /clear, /compactRebuilt at session start, /clear, /compact

Hội thoạiConversation

Tin nhắn, câu trả lời, kết quả toolMessages, responses, tool results

Lớn thêm mỗi lượtGrows every turn

ổn định nhấtmost stablehay đổi nhấtmost volatile
Thao tácActionẢnh hưởngEffect
Gửi tin nhắn mớiSend a new messageĐọc toàn bộ tiền tố cũ, chỉ ghi phần mới.Reads the whole old prefix, writes only the new part.
Bật/tắt MCP server giữa phiênToggle an MCP server mid-sessionVỡ từ tầng đầu tiên, xử lý lại mọi thứ.Breaks from the first layer, reprocesses everything.
Đổi model giữa phiênSwitch model mid-sessionCache tách theo model, bắt đầu lại từ đầu.Caches are per model; starts over.
Đổi mức effortChange effort levelCó thể vỡ cache; Claude Code hỏi xác nhận trước khi áp dụng.Can invalidate the cache; Claude Code asks for confirmation first.
/compactThay lịch sử bằng bản tóm tắt, dựng lại project context và hội thoại. Rẻ nếu làm khi cache còn ấm.Replaces history with a summary, rebuilding project context and conversation. Cheap while the cache is warm.
/rewindCắt về một tiền tố đã có trong cache, không phải dựng lại.Truncates to a prefix already cached; nothing to rebuild.
Nghỉ quá TTLIdle past the TTLCache hết hạn, lượt sau trả giá đầy đủ cho cả ngữ cảnh.The cache expires; the next turn pays full price for the whole context.
SubagentChuỗi request riêng, không dùng chung cache với hội thoại chính. Tiếp tục (resume) một subagent thì đọc lại được cache của lần chạy gốc.Its own request chain, not sharing the main conversation's cache. A resumed subagent can read the cache its original run warmed.

Bảng đánh đổiTrade-off table

Các trục quyết định thật khi chọn cache cho LLM.The axes that actually decide which cache to use.

Còn gọi model?Model still called? Rủi ro sai/cũWrong/stale risk Tiết kiệm khi hitSavings on hit Tỷ lệ trúngHit rate Ảnh hưởng thời gianLatency effect Ai vận hànhWho operates
M1KVCóYesKhôngNoneTốc độ decodeDecode speedLuôn dùngAlways onDecode nhanhFast decodeInference engine
P1PromptCóYesKhôngNone90% input tiền tố90% of prefix inputCao nếu tiền tố ổn địnhHigh if prefix is stableTTFT giảmLower TTFTNhà cung cấp; bạn giữ tiền tốProvider; you keep the prefix stable
A1ExactKhông (khi hit)No (on hit)Cũ nếu nguồn đổiStale if source changes100%Thấp với văn bản gõ tayLow for typed inputmsBạnYou
A2SemanticKhông (khi hit)No (on hit)Trả lời nhầm câu hỏiAnswers the wrong question~100% trừ embedding~100% minus embeddingTrung bìnhMediumChục msTens of msBạn (khó nhất)You (hardest)
O1Tuần tựSequentialCóYesKhôngNoneNhư P1As P1Gần 100%Near 100%Chậm nhấtSlowestBạnYou
O2Warm + fan-outCóYesKhôngNoneNhư P1As P1Cao, best effortHigh, best effortGần song songNear parallelBạnYou

Anti-patterns

Những lỗi làm hoá đơn tăng mà không ai để ý.Mistakes that raise the bill without anyone noticing.

Sai lầmMistakeVì sao saiWhy it's wrongSửa thế nàoFix
Timestamp hoặc request ID trong system promptTimestamp or request ID in the system promptTiền tố khác ở mọi request, không bao giờ trúngThe prefix differs every time; never hitsĐưa thông tin động xuống tin nhắn cuốiMove dynamic data into the last message
Bắn N request song song khi cache lạnhFiring N parallel requests on a cold cacheCả N cùng miss, trả phí ghi N lầnAll N miss; you pay N writesLàm ấm bằng 1 request, chờ nó bắt đầu trả về, rồi fan-outWarm with 1 request, wait for it to start, then fan out
Bật/tắt MCP giữa phiên Claude CodeToggling MCP mid-session in Claude CodeVỡ tầng đầu, xử lý lại mọi thứBreaks the first layer; everything reprocessedCố định tool từ đầu phiênFix tools at session start
Compact sau khi đi ăn trưa vềCompacting after returning from lunchCache đã hết hạn, đọc lại cả lịch sử giá đầy đủCache expired; whole history reread at full priceCompact trước khi nghỉCompact before the break
Serialize tool schema từ map không thứ tựSerializing tool schemas from an unordered mapThứ tự key đổi giữa các lần chạyKey order drifts between runsSắp xếp key trước khi serializeSort keys before serializing
TTL 5 phút cho lưu lượng thưa5-minute TTL for sparse trafficTrả phí ghi mà không bao giờ đọcPaying writes that are never readTTL 1 giờ, hoặc bỏ cache1-hour TTL, or drop caching
Semantic cache dùng chung, câu trả lời cá nhânShared semantic cache with personal answersDữ liệu người này lộ sang người khácOne user's data leaks to anotherPhân vùng theo user/tenantPartition by user/tenant
Hạ ngưỡng semantic để "tăng hit rate"Lowering the semantic threshold to "boost hit rate"Trả lời đúng một câu hỏi khácCorrectly answers a different questionGiữ ngưỡng cao, đọc mẫu hit định kỳKeep it high, audit hits regularly

Ba câu cần nhớThree things to remember

  • Prompt cache là phép khớp tiền tố từng byte: thứ ổn định ở đầu, thứ thay đổi ở cuối.Prompt caching is a byte-for-byte prefix match: stable content first, volatile content last.
  • Đừng bắn song song khi cache còn lạnh: làm ấm bằng một request rồi mới fan-out.Never fire in parallel on a cold cache: warm it with one request, then fan out.
  • Trong Claude Code, việc của bạn là đừng làm vỡ cache: cố định tool, đừng đổi model giữa chừng, compact trước khi nghỉ.In Claude Code, your job is not to break the cache: fix your tools, don't switch models midway, compact before a break.