LLM Context Window Management in Production: A Governance Checklist
Your model advertises a 200K token window. Your agent starts producing worse answers somewhere around 90K, and nobody notices for three weeks, because nothing throws. That gap between advertised capacity and usable capacity is the entire problem, and LLM context window management in production is the discipline that closes it.
This article covers what context rot is, where degradation actually begins, what an ungoverned window costs you in tokens and latency, and a governance model you can implement today. By the end you will have a budget calculation, a compaction trigger, and a telemetry schema you can drop into an existing agent loop.
Context rot: the failure mode nobody monitors
Context rot is the progressive loss of answer quality as a session grows, while the context stays comfortably inside the model's advertised limit. Nothing truncates. Nothing errors. Every token you sent is still sitting in the payload. The model simply attends to it worse.
A study of 18 frontier models found that all of them degraded at every increment of context growth, with accuracy drops above 30 percent for information buried in the middle of long sessions. Not most of them. All 18, without exception. If you are running an agent on a frontier model, you are running it on a model that has this property.
For a coding agent the symptom is specific and expensive. The agent forgets a constraint you gave it 40 turns ago, rewrites a function it already fixed, or reintroduces a bug it removed two files back. You read the diff, decide the model is having an off day, and run the prompt again. The actual cause is that your constraint now sits in the low attention middle of a 90K token conversation.
Two vocabulary items separate teams that fix this from teams that keep rerolling prompts:
Nominal window: the number printed on the model card.
Effective window: the region where retrieval accuracy actually holds. Always smaller.
Your job is to keep every session inside the effective window. That is context governance, and it is a system property, not a prompting trick.
It starts at 50 percent capacity, not 100 percent
Significant context degradation begins at roughly 50 percent of a model's advertised context window capacity, not at the ceiling. That single number should change how you build.
If you treat the nominal window as your budget, you are already deep into degraded territory long before any alarm fires. Treat half of it as your working ceiling instead, and give yourself a second threshold that forces action:
// context-budget.ts
export interface ContextBudget {
nominal: number; // advertised window from the model card
soft: number; // 50% of nominal: degradation onset
hard: number; // 70% of nominal: force a compaction now
}
export function budgetFor(nominal: number): ContextBudget {
return {
nominal,
soft: Math.floor(nominal * 0.5),
hard: Math.floor(nominal * 0.7),
};
}
export type BudgetState = "healthy" | "degrading" | "critical";
export function classify(used: number, b: ContextBudget): BudgetState {
if (used >= b.hard) return "critical";
if (used >= b.soft) return "degrading";
return "healthy";
}
Crossing the soft threshold is not an error condition. It is a signal that answer quality has quietly become a function of how well you curated the middle of that window.
Lost in the middle: position bias inside a long session
The 30 percent accuracy drop is not spread evenly across the payload. It concentrates on information buried in the middle. Content near the start and near the end survives. Content in the belly of a long transcript is the content the model treats as optional.
This is the lost in the middle problem, and in production it has one practical consequence: transcript position is not a stable place to store anything that must hold for the whole session. A constraint you stated at turn 12 is in a different relative position at turn 80, and its relative position is exactly what determines whether the model still honours it.
So stop storing durable facts in the transcript. Pin them, and rewrite the pinned block on every turn:
// build-messages.ts
import type { Message } from "./types";
export function buildMessages(opts: {
contract: string; // rewritten every turn, never buried
retrieved: string[]; // top k documents for THIS turn only
recentTurns: Message[]; // sliding window of dialogue
task: string;
}): Message[] {
return [
{ role: "system", content: opts.contract },
...opts.recentTurns,
{
role: "user",
content: `${opts.retrieved.join("\n\n")}\n\n${opts.task}`,
},
];
}
Two things are doing the work here. The contract lives at a fixed high attention position and is regenerated each turn from structured state, so it never drifts into the middle. The retrieved documents are scoped to the current turn and do not accumulate. That second decision alone removes most of the growth that produces llm context degradation in a long session.
The hidden cost: 100K tokens at 50x the price of 2K
Context window cost optimization usually gets filed under nice to have. The arithmetic disagrees. A 100K token conversation costs 50 times more than a 2K token conversation on the same model, because you resend the entire accumulated context on every single turn. One study recorded a 7x increase in latency at 15,000 words of context.
Stack those two facts. The ungoverned session is the slow one and the expensive one, and it is also the one giving worse answers. There is no tradeoff to balance here, which is unusual and worth exploiting. Governance wins on cost, on latency, and on accuracy simultaneously.
Now multiply by traffic. An agent serving 10,000 sessions a day at 60K tokens per turn instead of 12K is not marginally more expensive. It is 5 times more expensive on your single largest line item, every day, while being slower and less accurate than the cheaper version.
Silent failure versus loud failure: why context rot is dangerous
Overflow is a loud failure. You get an exception, a truncated payload, a 400 from the provider, an alert in your channel. Loud failures get fixed, because they show up on a dashboard within minutes of shipping.
The dominant production failure mode for agents is not overflow. It is silent quality degradation well before the limit is reached. For coding agents specifically, context rot is the primary failure mode. Nothing pages anyone. Your p50 latency chart looks normal. Your error rate is flat at zero. The only real signal is that users quietly stop trusting the agent for anything long, and you learn about it in a retro instead of an alert.
That is why context governance has to be instrumented rather than assumed. Log this on every turn:
// telemetry.ts
export interface TurnContextEvent {
sessionId: string;
turnIndex: number;
tokensContract: number; // pinned block
tokensRetrieved: number; // this turn's documents
tokensDialogue: number; // sliding window
tokensTotal: number;
budgetState: BudgetState;
compacted: boolean;
tokensReclaimed: number;
}
export function emitTurnContext(e: TurnContextEvent): void {
logger.info("agent.context", { ...e, ratio: e.tokensTotal / e.nominal });
}
Then chart your quality metrics against budgetState rather than against wall clock time. If the thumbs down rate is 3 percent in the healthy band and 11 percent in the degrading band, you have just measured your own context rot curve, and you know precisely where to set your trigger instead of guessing.
Context engineering: the discipline that replaced prompt wrangling
Context engineering, meaning the practice of governing what enters the context window rather than only how large that window is, has become the core discipline of production AI engineering. The research converges on one finding worth internalising: fewer, higher signal objects outperform larger ungoverned windows.
Signal density is the metric, not token count. Ten precisely retrieved paragraphs beat 200 loosely related ones, and they beat them on accuracy, not merely on cost. Every token you add that is not load bearing dilutes the attention available to the tokens that are.
Which reframes what a bigger model card number means. A larger nominal window is not permission to send more. It is headroom that lets your governed window sit further from the edge.
A governance model: when to summarize, when to retrieve, when to reset
Three actions, three triggers. Wire them explicitly rather than hoping the window absorbs everything.
Retrieve when the information is external to the dialogue. Scope retrieval to the current turn, never let it accumulate, and prefer a small top k with a reranker over a large top k without one. Retrieval is the cheap path because retrieved context leaves the window as soon as the turn ends.
Summarize when budgetState reaches degrading. Compact the oldest dialogue into a structured summary, keep the most recent turns verbatim in a sliding window, and preserve decisions and constraints losslessly by promoting them into the pinned contract instead of the summary prose.
// compact.ts
const KEEP_VERBATIM = 8; // most recent turns stay untouched
export async function compactIfNeeded(
session: Session,
budget: ContextBudget,
): Promise<Session> {
if (classify(session.tokensUsed, budget) === "healthy") return session;
const older = session.turns.slice(0, -KEEP_VERBATIM);
const recent = session.turns.slice(-KEEP_VERBATIM);
if (older.length === 0) return session;
const summary = await summarizeTurns(older); // returns { prose, decisions[] }
return {
...session,
contract: mergeContract(session.contract, summary.decisions),
turns: [asSystemNote(summary.prose), ...recent],
compactions: session.compactions + 1,
};
}
Reset when the task changes. A session that has moved from debugging an auth bug to writing release notes is carrying 40K tokens of pure noise. Start a fresh window seeded only with the pinned contract. Resets are the most underused of the three and often the highest leverage.
The checklist
Run this against any agent you have in production:
Do you know your nominal window and have you set a soft ceiling at 50 percent of it?
Is
budgetStatecomputed and logged on every turn?Are durable constraints stored in a rewritten pinned block rather than in the transcript?
Is retrieved context scoped to a single turn instead of accumulating?
Does compaction fire automatically at the degrading threshold?
Are decisions promoted into the contract losslessly when you compact?
Do you reset on task change instead of continuing forever?
Are quality metrics charted against budget state so you can see your own rot curve?
Anything you answer no to is an ungoverned surface, and ungoverned surfaces fail silently.
FAQ
What is context rot in LLMs?
Context rot is the measurable decline in an LLM's answer quality as the amount of context in a session grows, even while the total stays inside the advertised window. A study of 18 frontier models found every model degraded at every increment of context growth, with accuracy drops above 30 percent for information positioned in the middle of long sessions. It differs from context overflow because nothing errors and nothing truncates.
How do you manage context in a long running AI session?
Set a soft budget at 50 percent of the nominal window and classify every turn against it. Keep durable constraints in a pinned block that you rewrite each turn instead of leaving them in the transcript. Scope retrieval to the current turn so it never accumulates. Compact older dialogue into a structured summary once you cross the soft threshold, keeping recent turns verbatim in a sliding window. Reset the session outright when the task changes.
When does LLM context degradation start?
Significant degradation begins at roughly 50 percent of a model's advertised context window capacity, not at the limit. Treat that halfway point as the boundary of your effective window and instrument around it, because the failure produces no exception to catch.
Where to start
Pick your busiest agent and add one thing this week: the budgetState field on your existing turn log. Do not change behaviour yet. After a few thousand sessions, chart your quality metric against that field and you will see the exact token count where your own product starts rotting. Everything else in this article is easier to justify once that chart exists.
Comments
Join the discussion"Nothing throws" is exactly why this goes unnoticed for three weeks. The advertised-versus-usable gap deserves the treatment we already give disk: nobody runs a filesystem at 100% and expects normal latency, yet people plan for a 200K window as if all of it is equally usable.
Two additions to the telemetry schema. Track the position of retrieved evidence within the assembled context, not just total tokens, because material in the middle of a long window gets used less reliably and a growing history quietly pushes evidence into that zone. And log the compaction event with what was dropped, otherwise a quality regression right after compaction is indistinguishable from a retrieval regression and you will debug the wrong stage.




