Context is a budget
8 min read
Big windows do not save you from sloppy budgets
Model providers love advertising 200,000-token and 1,000,000-token windows. It tempts engineers into skipping budgeting altogether: "Just toss all the docs and the whole chat history in — it fits."
Three things break the moment you do that in production:
- Input and output share the same bucket. Stuffing 190,000 TokenA small piece of text that a model reads or writes as one unit, such as a short word, part of a longer word or a punctuation mark. In English, one token is about four characters. of prompt into a 200,000-token window starves the reply — or triggers an HTTP 400 error mid-session.
- You pay for every wasted token on every turn. Latency climbs and API bills multiply 5x–10x while 80% of the prompt is stale chatter.
- Quality drops long before the window is full. Models degrade when relevant facts are diluted by tens of thousands of irrelevant tokens.
A Context budgetA plan that gives each part of a request, such as instructions, history and documents, a size limit, so the whole fits in the context window with room left for the reply. is simply code that decides ahead of time how many tokens each section is allowed to spend — instead of letting whichever array grew longest push out the user's question.
Spend the window in strict priority order
When space runs tight, something has to get cut. Make that an explicit product decision in code, never an accidental string slice.
- Reserve the replySubtract the maximum reply token budget before touching anything else.
- Fund fixed essentialsSystem instructions, output schema, and the user's current request always go in.
- Add ranked evidencePolicy docs, code chunks, or records — best match first — while budget remains.
- Add recent historyNewest turns first, up to the history cap.
- Drop the rest cleanlyStop adding once the budget hits zero; never cut essential parts to fit noise.
Different products weight steps three and four differently. A compliance bot funds retrieved policy docs before old chat; a conversational tutor might fund the last three turns first. What matters is that you chose the priority order explicitly.
Enforce the budget in code
Notice what happens in this small allocator when two policies compete for limited space. Because the more specific sale policy sits above the general returns policy in the priority list, it wins the remaining tokens. Flip those two entries and the model gets the wrong rule!
def est_tokens(text):
return round(len(text.split()) * 1.3)
window = 60
reply_reserve = 15
fixed = {
"rules": "Answer strictly from the policy. Be brief.",
"request": "Can I return a discounted item bought 20 days ago?",
}
optional = [
("discount policy", "Discounted items are final sale after 14 days from delivery."),
("general returns", "Full-price items can be returned within 30 days for a refund."),
("old chat", "Customer asked about express shipping last week and was told 2 to 4 days."),
]
left = window - reply_reserve - sum(est_tokens(v) for v in fixed.values())
print("budget left for optional parts:", left)
for name, text in optional:
cost = est_tokens(text)
if cost <= left:
left -= cost
print(f"KEEP {name:16} ({cost} tok) -> {left} left")
else:
print(f"DROP {name:16} ({cost} tok) -> only {left} left")Running this prints:
budget left for optional parts: 23
KEEP discount policy (13 tok) -> 10 left
DROP general returns (14 tok) -> only 10 left
DROP old chat (18 tok) -> only 10 leftIn production, swap est_tokens for the model's real tokeniser (tiktoken or your provider's token-count endpoint). The allocation pattern stays identical: reserve reply, pay fixed costs, walk optional items from highest value to lowest.
What to do when even the essentials overflow
Sometimes a user pastes a 40-page stack trace and even the fixed parts blow past your limit. Whatever you do, never blindly slice from the end with prompt[:max_chars] — that cuts off whatever came last, which is usually the user's actual question.
Pick one of four honest strategies instead:
- Compress the culprit. Extract only error lines from logs, or summarise older turns into a short state block.
- Split the job. Map-reduce large inputs across separate focused calls and merge in code.
- Step up to a bigger window only after verifying the extra context actually helps your evals.
- Refuse cleanly. Tell the user the pasted file is too large and show the limit.
Log where your tokens actually go
An unmonitored budget always drifts toward whichever subsystem is noisiest. Emit per-bucket token percentages in your request logs and glance at them weekly. Almost every team gets a shock the first time they chart a real production request:
- Instructions8%
- History55%
- Retrieved documents25%
- Tool results10%
- Question2%
When chat history eats 55% of your prompt while the actual question is 2%, trimming or summarising history is an instant win — before you spend a single afternoon rewriting instructions or upgrading models.
Put hard numeric caps in config (for example: 500 tokens for instructions, 1,500 for history, 3,000 for retrieved chunks, 800 reserved for reply) and assert them in tests. Catching a bloated prompt in CI is infinitely cheaper than discovering it from a hallucinated customer reply.
What do you reserve first in a context budget?
A window holds 60 tokens and the reply may need 15.
Input and reply share one window, so the reply's space is set aside before the optional parts are added.
Why does the order of the priority list matter?
A general returns policy and a sale policy both fit alone, but not together.
Parts are funded in order. Put the part most likely to answer the question at the top.
What does a request breakdown showing 55 per cent history tell you?
You log the share of each part for a request.
A part that dominates the window while adding little is the first candidate for trimming or summarising.
Your reading position is saved
0 of 11 complete
Lesson complete
Context is a budget
Up next