Context Window Optimization: 4 Techniques to Work Around Token Limits
This article explains why long AI conversations degrade as the context window fills up, then presents four practical techniques for making better use of a limited token budget: isolating one goal per session, moving stable project information into the system prompt, retrieving large volumes of material from external memory, and compressing model output and conversation history. It also covers how to combine the techniques and measure whether they are working.
Context Window Optimization: 4 Techniques to Work Around Token Limits
Why Models “Forget” as Conversations Get Longer
Many developers hit the same wall when using AI coding assistants or conversational AI services over an extended session: for the first ten minutes the model tracks the project structure, API contracts, and variable naming accurately, but after dozens of turns it starts asking questions it already asked, drops constraints, and even produces code that contradicts earlier decisions. This is usually not the model being lazy. It is the predictable outcome of a full context window.
The context window is the total number of tokens a model can “see at once” during a single inference call, and it covers both input and output. The system prompt, conversation history, current question, tool results, reference material, and the answer being generated all draw from the same budget. As the accumulated token count approaches the limit, the system has no choice but to drop the oldest content according to its policy, so the initial architecture decisions, coding conventions, and boundary conditions are the first things to disappear.
This distinction matters: optimizing context is not about giving the model a better memory. It is about raising the density of useful information within a fixed token budget. The four techniques below approach the problem from four angles: task boundaries, information placement, external storage, and output compression.
Technique 1: Isolate Tasks, One Goal per Session
This is the highest-return, lowest-cost change you can make. Context is a scarce resource, and packing unrelated tasks into one session forces different domains to compete for the same budget while introducing semantic interference, where a temporary convention from a coding task skews the judgment applied to later data analysis.
A practical unit of division is “one goal that can be verified independently.” Finish a particular endpoint implementation, then end the session. Open a new session to investigate a performance problem. Keep documentation work and test writing separate as well. When you switch tasks, do not rely on the model to “remember on its own”; carry the necessary conclusions into the new session explicitly as a short handoff note:
[Handoff Summary]Goal: Add unit tests for the order query endpointKnown: Signature is listOrders(userId, page, size), returns a paginated structureConstraints: No new dependencies; tests must run offlineTo do: Cover empty results, pagination boundaries, and invalid parameters
Treating a session as a unit of work means every session’s token budget serves the current goal in full. In practice, this noticeably reduces repeated explanations and self-contradiction.
Technique 2: Put Stable Information in the System Prompt
Project configuration, coding standards, directory conventions, and naming style share one characteristic: they stay unchanged over the long term and are needed on every turn. Placing them in the system prompt costs less than pasting them into the conversation repeatedly, and it avoids having the same constraint appear in multiple, conflicting versions across the history.
A system prompt should be structured, easy to scan, and as short as possible. A layered layout works well:
# RoleSenior backend developer; output runnable code with the necessary explanation# StackLanguage/framework versions, package manager, test framework# Conventions- Indentation and naming style- Error handling and logging conventions- No unreviewed dependencies# Output formatConclusion first, then code, then a list of risks
Two cautions apply. First, the system prompt also consumes window space, so keep it within what is necessary and avoid dumping long background material into it wholesale. Second, leave volatile content such as the current requirement and temporary data in the conversation, and promote only stable content to the system prompt. This separation of hot and cold information keeps the context clean over time.
Technique 3: Use External Memory for High-Volume Information
Not everything belongs in the context. Decision records, API documentation, incident post-mortems, long logs, and code search results routinely exceed the window’s capacity. Here the answer is external memory and retrieval: write the information to external storage or a vector search service, recall a small set of the most relevant fragments when needed, and inject only those into the current context.
In implementation, a “retrieve first, then assemble” pattern works well:
def build_context(question, k=3):# Recall the most relevant fragments from the external memory storehits = memory.search(question, top_k=k)snippets = "\n\n".join(f"[{i+1}] {h.text}" for i, h in enumerate(hits))return f"References:\n{snippets}\n\nQuestion: {question}"
Key engineering details: attach a source and timestamp to each fragment so freshness can be judged; cap both the number of recalled fragments and the length of each one so retrieval results do not blow up the window in the other direction; deduplicate and summarize the recalled content; and archive the original material in a general-purpose storage category such as object storage, with the retrieval layer fetching it on demand. The context then holds only what the current step genuinely needs.
Technique 4: Compress Output and History to Control Incremental Growth
The first three techniques manage input; the fourth manages growth. Every answer the model produces stays in the history permanently, and long code blocks, repeated logs, and line-by-line explanations are the main sources of token consumption.
Actionable practices: ask the model to output only the changed fragments instead of a whole file; use bullet lists in place of long prose; apply rolling summaries to completed turns, compressing the “process” into “conclusions”; and hand large logs to an external tool for aggregation first, bringing only the aggregate into the conversation. A rolling summary can follow a structure like this:
[Confirmed] Endpoint signature and return structure are finalized[Ruled out] The problem is not the database connection pool[Next] Verify the cache expiration policy
Combining the Four Techniques and Measuring Results
Any single technique only eases the problem; combined, they form a stable approach. Task isolation controls the total volume of context, the system prompt locks in high-frequency constraints, external memory absorbs bulky material, and output compression slows the rate of growth. It also helps to establish simple metrics, such as the estimated token count per request, the recall accuracy of key information, and the number of rework cycles caused by forgotten constraints, so you can judge from data whether the optimization is working.
In related work at Baidu AI Cloud, practices of this kind are typically combined with general cloud capabilities such as log services, monitoring and alerting, and object storage, keeping session context, retrieved material, and runtime metrics in the storage and observability paths that suit each, so that accuracy and consistency hold up in long-running sessions.
