Context Window Optimization: Four Practical Ways to Manage Token Limits

    Manage LLM context limits with four complementary techniques: task-based sessions, compact system prompts, external memory with retrieval, and structured rolling summaries. This article explains how to allocate a shared token budget, preserve important information, and use measurement and evaluation to reduce context loss.

    1. Understand Why Models “Forget”

    A context window is the maximum number of tokens a model can accommodate in a single inference. It covers system instructions, conversation history, the current request, and the output the model will generate.

    Many teams mistakenly treat it as an allowance reserved for conversation history. They keep appending content until the model appears to forget the instructions established at the beginning. Three often-overlooked points explain what is happening:

    • The window is a shared budget. System prompts, tool results, retrieved passages, and pasted logs all consume the same allowance.
    • Overflow can appear as silent truncation rather than an error. When the application truncates content to fit the limit, earlier turns are often discarded. To the user, this looks like the model forgetting what they said.
    • Longer context increases resource costs. Attention computation grows nonlinearly with sequence length, while KV cache memory also grows as sequences get longer. Long contexts can therefore be slower and more expensive. Models also commonly show weaker recall for information placed in the middle of a long context—the “lost in the middle” effect.

    The goal is not simply to fit more content into the window. It is to maximize useful information within a fixed token budget.

    2. Technique One: Separate Sessions by Task

    The simplest technique is often the most effective: use one session per task. When a coding task is complete, close that session. Start a new one when moving on to data analysis.

    Two practical criteria can guide the decision:

    • Do the tasks share less than 30% of their input context?
    • Do they produce different deliverables?

    If both conditions apply, separate the sessions. Manage their lifecycle explicitly:

    1. # Pseudocode: session lifecycle and archiving
    2. session = start_session(system_prompt=PROJECT_RULES)
    3. try:
    4. result = run_task(session, task_input)
    5. finally:
    6. archive(session, store=object_storage) # Archive instead of appending indefinitely
    7. close(session)

    Archive sessions rather than deleting them so their contents remain searchable and reusable. This provides the foundation for external memory and retrieval, covered in Technique Three.

    3. Technique Two: Put Stable Knowledge in the System Prompt—But Count the Cost

    A common misconception needs correcting: system prompts also count toward the context window. They are not free.

    Their advantage is that stable instructions can be defined once instead of repeatedly added to the conversation. This prevents duplicate instructions from accumulating, although the system prompt still consumes context whenever it is included in a request.

    Good candidates for the system prompt include:

    • Technology stack and directory conventions
    • Coding standards
    • Output format requirements
    • Terminology
    • Explicit prohibitions

    Poor candidates include frequently changing business data, large raw logs, and complete file contents.

    As a starting guideline, keep the system prompt within 5–10% of the context window and manage it under version control. Run a fixed evaluation set after every change to avoid crowding out task context just to include more rules.

    1. system_prompt:
    2. project: order-service
    3. conventions: [4-space indentation, required type annotations, no bare except]
    4. output: {format: json, keys: [summary, files_changed, risks]}

    4. Technique Three: Use External Memory and On-Demand Retrieval

    Store long-term knowledge outside the conversation in a vector retrieval store, object storage, or a logging service. When needed, retrieve only a small number of relevant passages and inject them into the context.

    Four engineering considerations matter:

    1. Chunking: Split content along semantic or structural boundaries. Avoid cutting a function in half.
    2. Metadata filtering: Filter by project, module, or time before similarity search to reduce irrelevant results.
    3. Source traceability: Attach source identifiers to passages so the model can cite its evidence and people can verify it.
    4. Invalidation and updates: Update or rebuild indexes when knowledge changes; otherwise, retrieval may return outdated conclusions.
    1. hits = retriever.search(query, top_k=5, threshold=0.75,
    2. filters={"project": "order-service"})
    3. context = "\n\n".join(f"[{h.source}] {h.text}" for h in hits)

    Evaluate retrieval quality using hit rate and human-labeled examples. Do not tune thresholds based on intuition alone.

    5. Technique Four: Apply Rolling Compression and Structured Summaries

    When a conversation must continue for a long time, replace older raw content with hierarchical summaries: turn-level, session-level, and task-level.

    Preserve decisions, constraints, conclusions, action items, and unresolved questions. Remove greetings, repetitive trial and error, and lengthy raw outputs.

    Use structured summaries so software can consume them reliably:

    1. {
    2. "decisions": ["Use an event-driven approach to decouple components"],
    3. "constraints": ["The API must remain backward-compatible"],
    4. "open_questions": ["Is a phased rollout required?"],
    5. "artifacts": ["s3://.../design.md"]
    6. }

    Summarization is lossy. Preserve critical facts in two forms: include them in the summary and retain reference anchors to the original material. This helps prevent important details from being distorted during compression.

    6. Combine the Four Techniques into a Token Budget

    Use an explicit allocation to balance instructions, retrieved knowledge, conversation history, and output capacity.

    Budget component Suggested share
    System prompt About 10%
    Retrieved passages About 20%
    Recent conversation in full About 40%
    Structured historical summaries About 20%
    Reserved output capacity About 10%

    Observability is equally important. Instrument the application to measure token consumption for each turn, aggregate those measurements through a logging service, and configure monitoring thresholds.

    For example, issue a warning at 70% utilization and automatically trigger compression and archiving at 85%.

    Without measurement, optimization becomes guesswork.

    7. Four Common Mistakes

    • Relying only on models with larger context windows: Even a larger window eventually fills up, and longer contexts require more resources.
    • Pasting everything into the conversation: Full logs and files are among the fastest ways to exhaust the token budget.
    • Using unstructured summaries: Free-form summaries are harder to reuse and validate programmatically.
    • Skipping evaluation sets: Without consistent tests, it is difficult to tell whether changes to system prompts or compression strategies improve results.

    8. Conclusion

    Context management is fundamentally budget engineering. Task-based sessions limit unnecessary growth. System prompts hold stable constraints. External memory supplies relevant knowledge on demand. Rolling summaries keep conversation history from expanding indefinitely.

    Combined with token measurement and alerts, these techniques can address many apparent model-memory failures.

    These capabilities can be assembled from general-purpose cloud services: object storage for archiving, logging services for usage measurement, and monitoring and alerts for threshold enforcement. The original approach can also be implemented using relevant Baidu AI Cloud service categories, subject to their availability in the intended deployment region. The objective is the same: make context management a measurable, reusable engineering practice.