Sub topic 1
Why Processing a Long Prompt Is Expensive
Prompt caching exists because reading a prompt costs real compute, and most applications make the model read the same text again and again. This chapter explains where that cost comes from. Later chapters cover what the provider stores to avoid it and how to get the savings.
Prerequisites
This chapter assumes you have:
- Called an LLM API at least once and seen the request and response shape.
- A working idea of tokens (the chunks of text a model reads) and the context window (the maximum number of tokens a model accepts in one request).
- Enough Python to read short loops and functions.
You do not need to know how transformers are implemented. The chapter gives only the parts of the architecture that matter for cost.
Two phases of every request
When you send a prompt, the model does two different kinds of work.
- Prefill processes every input token you sent. The model reads the whole prompt and builds an internal representation of it. No output text exists yet.
- Decode generates the answer one token at a time. Each new token depends on all the tokens before it, including the ones it just produced.
The first output token cannot appear until prefill finishes. The delay between sending the request and seeing the first token is called time to first token (TTFT). For a long prompt, prefill is usually the largest part of it.
The two phases stress the hardware differently:
| Phase | Work pattern | Typical bottleneck | Scales with |
|---|---|---|---|
| Prefill | All input tokens processed in parallel | Compute (arithmetic throughput) | Number of input tokens |
| Decode | One token per step, strictly sequential | Memory bandwidth (reading model weights and stored state) | Number of output tokens |
Prefill can run many tokens at once, so the hardware is well used. But it still has to do arithmetic for every token, and that arithmetic is what you pay for and wait for.
Where the prefill cost comes from
Inside the model, each input token passes through many layers. Each layer has two main parts.
- Feed-forward and projection layers. These do a fixed amount of arithmetic per token. Doubling the prompt doubles this work. The growth is linear.
- Attention. For each token, the model looks back at the earlier tokens and decides how much each one matters. Attention is the mechanism that lets token 5,000 use information from token 12. Each token interacts with every token before it, so the number of token pairs grows with the square of the prompt length.
You can count the pairs directly. For a prompt of n tokens, where each token attends to itself and all earlier tokens, there are n * (n + 1) / 2 pairs.
def attention_pairs(n):
return n * (n + 1) // 2
for n in (1_000, 10_000, 100_000):
print(f"{n:>7} tokens -> {attention_pairs(n):>14,} pairs")Running it prints:
1000 tokens -> 500,500 pairs
10000 tokens -> 50,005,000 pairs
100000 tokens -> 5,000,050,000 pairsA prompt 10 times longer has about 100 times as many pairs. This is the source of the common claim that long prompts get expensive faster than they get long.
What the model must remember
Prefill does more than compute and discard. While reading each token, the model produces intermediate values at every layer that later tokens will need to look back at. The model must hold these values in memory for as long as it keeps generating, because every decode step consults them.
This stored state is what the next chapter calls the attention key/value cache. For now, note two consequences:
- Memory use grows with prompt length. A long prompt occupies more of the accelerator's memory for the whole request.
- Whatever prefill produces is thrown away when the request ends, unless the provider chooses to keep it. A normal request starts from nothing.
That second point is the opening for caching. If two requests start with the same tokens, the second request repeats the same prefill work as the first and gets the same result.
How the cost reaches your bill and your users
Prefill cost appears in two places.
Latency. TTFT grows with prompt length because prefill must complete before output begins. A short question over a 50,000-token document can feel slow even when the answer is one sentence. The wait is prefill, not generation.
Price. Providers bill input tokens per token. Input tokens are usually cheaper per token than output tokens, but input volume is often far larger. A typical request might send thousands of tokens and get back a few hundred. In those workloads, input cost can outweigh output cost even at the lower rate. Check your provider's current price list for the exact rates, because they differ by model and change over time.
Why repetition is the real problem
One long prompt that you send once is a fair price for the work. The waste appears when the same text is processed over and over. Three common patterns cause it:
- A large fixed prefix. A system prompt with instructions, a policy document, or tool definitions is sent with every request. Only the final user question changes.
- Multi-turn chat. The API is stateless. Every turn, you resend the full conversation so far plus the new message.
- Agent loops. An agent calls tools in a cycle. Each step resends the instructions, the tool list, and every earlier step, then adds one more result.
Multi-turn growth is easy to underestimate, so here is a model of it. Each turn's prompt is the system prompt, the full history, and the new user message. After the turn, the user message and the model's reply both join the history.
def conversation_cost(system, user, reply, turns):
processed = 0 # input tokens the model reads across all requests
history = 0 # tokens of earlier user messages and replies
for _ in range(turns):
processed += system + history + user
history += user + reply
unique = system + turns * user + (turns - 1) * reply
return processed, unique
processed, unique = conversation_cost(system=3000, user=100, reply=300, turns=10)
print("input tokens processed:", processed)
print("distinct input tokens:", unique)
print(f"repeat factor: {processed / unique:.1f}x")The output is:
input tokens processed: 49000
distinct input tokens: 6700
repeat factor: 7.3xOver 10 turns, the conversation contains only 6,700 distinct input tokens, but the model reads 49,000. The extra 42,300 tokens are repeated work. The processed total grows with the square of the number of turns, because each new turn resends everything before it. Longer conversations make the repeat factor worse.
Edge cases and common misunderstandings
- Output length does not fix a prefill problem. Asking for a shorter answer reduces decode time and output cost. It does nothing for a 50,000-token prompt that must still be read.
- A bigger context window does not make long prompts cheap. The window sets what fits. You still pay to process what you put in it.
- Truncating or summarizing is a different tool. Cutting the prompt reduces prefill but also removes information. Caching keeps the full text and avoids repeating the work.
- Not every repeated token can be skipped. Reuse depends on the repeated text being an exact match at the start of the prompt. This is the subject of a later chapter and the reason prompt layout matters.
- Prefill and decode can compete. On a busy server, a very long prefill can delay other requests. Providers manage this internally, which is one reason their latency and pricing can differ for long inputs.
Key takeaways
- Every request pays a prefill cost proportional to its input length, with an attention term that grows faster at long lengths.
- Prefill sets time to first token and is billed per input token.
- The model keeps internal state for the prompt during the request and discards it afterward by default.
- Fixed prefixes, chat history, and agent loops make the model reread the same tokens many times. That repetition is what prompt caching targets.
Exercise
A support bot sends a 6,000-token system prompt on every request, followed by a 50-token user question. It handles 20 requests with no conversation history. How many input tokens does the model read in total, and how many of them are repeats of the system prompt?
Show answer
The model reads 20 (6,000 + 50) = 121,000 input tokens. The system prompt accounts for 20 6,000 = 120,000 of them. Only the first copy (6,000 tokens) is new work, so 114,000 tokens are repeats. That is about 94% of all input tokens, which is why a fixed prefix is the first thing to look at when reducing prefill cost.
Exercise
Using the attention_pairs function from this chapter, roughly how many times more token pairs does a 20,000-token prompt have than a 5,000-token prompt? Why does this matter for latency?
Show answer
The prompt is 4 times longer, so the pair count is about 4 * 4 = 16 times larger (200,010,000 pairs versus 12,502,500, a ratio of about 16.0). Attention work, and therefore prefill time, rises faster than prompt length once prompts are long. Time to first token for the longer prompt grows by more than 4x in the regime where attention dominates.