Context Window Management: Strategies for Long Documents and Large Codebases

Model vendors keep advertising bigger context windows, and that has quietly convinced a lot of developers that long inputs are a solved problem for artificial intelligence applications. Paste the whole contract, the whole repo, the whole chat log, and let the model sort it out. In production this fails in predictable ways: the bill grows with every call, answers slow down, and models use the middle of a long prompt far worse than the edges. The fix is not a bigger window. The context window management strategies for long documents and large codebases that hold up in production are about deciding what earns a place in the window: chunking at structural boundaries, retrieval-first filtering, map-reduce and refine passes, compaction, and deliberate placement.

Why stuffing the window fails

Three things break when you dump everything into one prompt. First, attention spreads thin. The “lost in the middle” effect describes how models use information at the start and end of a long context more reliably than information buried in the middle. A fact placed at token 40,000 of an 80,000-token prompt is not treated the same as one at token 100, and the degradation is invisible: the answer sounds confident and is quietly wrong.

Second, cost and latency grow with input size. Every extra thousand tokens is billed and processed on every call, so a prompt ten times bigger costs roughly ten times more on the input side even when only one paragraph matters. Third, silent failure. Stuff a prompt past the limit and the provider either truncates it or errors out, and the part that gets cut is rarely the part you would have chosen to cut. Bigger windows raise the ceiling on all three problems; they solve none of them.

Chunk at structural boundaries, not token counts

Chunking decides what the units of retrieval and summarization are, and naive fixed-size chunking makes those units meaningless: it splits a function in half, tears a table row across two chunks, and separates a claim from the sentence that qualifies it. Chunk at boundaries that match the content instead: markdown headings and paragraph breaks for prose, abstract syntax tree nodes for code. For the full taxonomy of splitting strategies, our guide to RAG chunking strategies compares fixed-size, recursive, and semantic approaches in depth. Chunk quality also depends on what happens before splitting: a parser that mangles tables or drops headings poisons every chunk downstream, and the tools in our document parser comparison differ exactly on this.

def chunk_code(source, lang, max_tokens=512):
    tree = parse_ast(source, lang)
    chunks = []
    for node in tree.top_level_functions():
        if token_count(node) <= max_tokens:
            chunks.append(node.text)
        else:
            # Large function: split by inner blocks,
            # keep the signature attached to each part
            chunks.extend(split_large_function(node, max_tokens))
    return chunks

Three rules of thumb follow from this. Overlap prose chunks by roughly 10-20% so a sentence split at a boundary still reads correctly in at least one chunk. Attach metadata to every chunk (file path, heading trail, function name), because the model needs to know where evidence came from, and so do you when debugging a bad answer. And when a code chunk must be split, keep the enclosing signature on each part so the fragment stays interpretable on its own.

Retrieval-first filtering

For query-driven applications (document QA, code search, support bots), the strongest move is to never put the whole document in the prompt at all. Index it once, retrieve the handful of chunks that match the query, and put only those in the context. This is the core idea behind retrieval-augmented generation, and it wins on all three axes at once: lower cost, lower latency, and a small enough window that the lost-in-the-middle effect has little room to operate. It also changes model selection, because a mid-size window used well beats a flagship window used badly. Our comparison of the best LLM APIs for developers covers current context limits and pricing tiers.

def answer(question, index):
    candidates = hybrid_search(question, index, k=50)  # BM25 + embeddings
    top = rerank(question, candidates)[:8]             # cross-encoder
    prompt = build_prompt(question, top)
    return llm.complete(prompt)

Retrieval-first wins when users query a stable corpus repeatedly: you pay the indexing cost once and amortize it over thousands of questions. It is the wrong tool for one-shot, ordered processing of a single long document, where you genuinely need to touch every section in sequence.

Map-reduce and refine for full-document processing

Sometimes you cannot skip anything: summarizing a 200-page report, reviewing every file in a migration, extracting obligations from a complete contract. Two patterns handle this, and they trade off differently.

Map-reduce summarizes each chunk independently, then summarizes the summaries. It parallelizes well and stays cheap, but it loses relationships that span chunks: a cause described in section 2 and its effect in section 9 may never meet in the same prompt.

Refine rolls a running summary forward, folding each new chunk into the previous summary. It preserves continuity across sections, which narratives and code reviews need, but it runs sequentially and spends more tokens per step.

def map_reduce_summary(chunks, llm):
    partials = [llm.summarize(c) for c in chunks]  # map: runs in parallel
    return llm.summarize("nn".join(partials))    # reduce

def refine_summary(chunks, llm):
    running = llm.summarize(chunks[0])
    for c in chunks[1:]:
        running = llm.refine(running, c)  # fold the next chunk in
    return running

Pick map-reduce for long documents with independent sections. Pick refine when later parts depend on earlier ones and losing the thread costs more than the extra tokens.

Sliding windows and compaction for long conversations

A chat session grows every turn, and a coding assistant or support bot will eventually hit the wall even if each individual message is small. The standard fix has two parts: keep the last few turns verbatim, since recent turns carry the most signal, and compress everything older into a running summary. That compression step is usually called compaction, and it is one instance of a broader set of memory patterns for AI agents that also covers long-term and episodic memory stores.

def compact(history, llm, keep_recent=6, budget=8000):
    if token_count(history) < budget:
        return history
    old, recent = history[:-keep_recent], history[-keep_recent:]
    summary = llm.summarize(old, focus="decisions, facts, open items")
    return [system_message(summary)] + recent

What you compact matters more than how often you compact. Summarize decisions and state, not noise. “User pasted a traceback; we traced it to a missing null check in auth.py” is worth keeping. The three turns of small talk around it are not. Store the summary as its own message at the head of the history, so the thread still makes sense once the raw turns are gone.

Beat lost-in-the-middle with placement

Since models attend best to the start and end of a long context, order the prompt deliberately instead of appending chunks in raw retrieval-score order:

  • Repeat the question at the end. State it once up front for framing, then repeat it right before generation so the task is the last thing the model reads.
  • Put your strongest evidence at the edges. Highest-confidence chunks first and last; lower-confidence material in the middle, where attention is weakest.
  • Restate the goal on every agent turn. In multi-turn agent loops, repeat the objective and constraints in the final message of each turn instead of trusting the model to remember them from turn one.
def build_prompt(question, chunks):
    # Strongest evidence at the edges, weaker filler in the middle
    ordered = [chunks[0], chunks[-1]] + chunks[1:-1]
    evidence = "nn".join(f"[Source {i}] {c}" for i, c in enumerate(ordered))
    return f"Answer using only the evidence below.nn{evidence}nnQuestion: {question}"

Treat placement as a solid heuristic, not a law of physics. Exact behavior varies by model and version, so verify it against your own evaluations before baking it into the prompt builder.

Large codebases: repo maps, not file dumps

Most writing on context window management strategies long documents large codebases focuses on PDFs and contracts, then hand-waves the repository case. Code needs its own tactics. Start with a repo map: the directory tree plus the exported signatures for each file. That usually fits in a few thousand tokens and gives the model a truthful index of the repo. Retrieve at the symbol level rather than the file level: when the model asks about a function, send its definition, its callers, and the types it touches, in dependency order. Keep generated files, lockfiles, and vendored code out of the index entirely; they are large and low-signal. Finally, pin the files the user is actively editing at the front of the context, because for code that just changed, recency beats retrieval scores.

Context Window Management Strategies for Long Documents and Large Codebases Start with a Budget

The teams that do this well stop thinking of the context window as a bucket and start treating it like a memory budget: deliberate allocations for the system prompt, retrieved documents, conversation history, and headroom for the response. Stable prefixes such as system prompts can often be cached between calls instead of being reprocessed every time; our guide to prompt caching explains when that pays off. A tiny helper turns the budget from a hope into a team convention:

BUDGET = {
    "system": 1000,
    "retrieval": 6000,
    "history": 4000,
    "response_headroom": 2000,
}

def within_budget(parts, window_limit):
    used = sum(token_count(p) for p in parts)
    return used <= window_limit - BUDGET["response_headroom"]

Add one observability habit: log full contexts from production and read what is actually going into the window. Most teams have never looked. The results usually surprise them: duplicated chunks, stale history, and system prompts nobody remembers writing.

Mistakes to avoid

Mistake Why it hurts Fix
One chunk size for every query Short factual queries drown in oversized chunks Tune chunk size to the query type
Fixed-size code chunking Splits functions mid-body, destroying the unit AST-aware chunking
No overlap between chunks Context gets severed at boundaries 10-20% overlap plus per-chunk metadata
Stuffing without retrieval High cost, slow answers, lost-in-the-middle Retrieval-first pipeline
Compacting noise into history Summaries bloat and signal gets lost Compact decisions and facts only
Never inspecting real prompts Context drift goes unnoticed Log and review sampled contexts

Small, relevant, and well-ordered beats big and cluttered. Pick the strategy that matches how your application touches the data: retrieval-first for repeated queries, map-reduce or refine for full sweeps, compaction for conversations, repo maps for code. Then budget the window deliberately, and inspect real prompts regularly.

Ditulis oleh

Firdaus Safari Putra

Founder, PT FirKaizen Digital Solutions

Firdaus Safari Putra adalah founder PT FirKaizen Digital Solutions. Ia membangun dan mengoperasikan infrastruktur server di balik panduan ini, dan menulis berdasarkan apa yang benar-benar ia jalankan, uji, dan ukur — bukan teori.