Forward Deployed EngineeringAI EngineeringContext Management

Your prompt plus retrieved documents exceed the context window. What are your options and tradeoffs?

Question 45 of 73 · Updated

On this page

Interview-ready answer#

I would not solve context overflow by blindly truncating the prompt or increasing the context window. First, I would calculate the actual token budget for the deployed model, reserve enough tokens for generation and reasoning where applicable, and protect the system instructions, current question and indispensable evidence.

For ordinary RAG question answering, I would usually improve selection before increasing context: filter documents by applicability and permissions, retrieve a reasonably broad candidate set, rerank it, remove redundancy and pack the most useful evidence into the available budget. I would preserve source identifiers, relevant surrounding context and any exceptions needed to interpret a passage correctly.

If essential evidence still cannot fit, I would choose a different processing strategy based on the task. Query-focused extractive compression can remove irrelevant material; summarization can condense lengthy passages but may lose important details. Hierarchical retrieval can navigate a large collection from coarse sections to precise evidence. Sliding windows or map-reduce can process long documents in stages when broad coverage is required. A larger-context model is another option, but I would benchmark actual evidence utilization, latency, memory and cost rather than assume that a larger window guarantees a better answer.

If I cannot retain or reliably combine the evidence required for a correct answer, I would explicitly return a partial result, ask the user to narrow the task, or abstain. The objective is not to fit the largest amount of text into a prompt; it is to provide sufficient authorized evidence to complete the customer's task reliably.

1. Establish the actual token budget#

A context window is a limit on the model's supported token sequence, not a character count or a guarantee of useful reasoning over every position. The exact limits and accounting rules vary by model and serving API. Some APIs expose separate input, output and combined sequence limits; reasoning tokens and tool-call tokens may also affect output or context accounting. Inspect the deployed model's contract.

For a simplified combined-window model:

Available evidence tokens = context limit − fixed prompt tokens − reserved generation tokens − safety margin.

The fixed prompt includes system/developer instructions, current query, selected conversation history, role markers, tool definitions, output schemas and other serialization overhead. Depending on the model, images, audio and tool results may also consume context.

Worked example#

Assume a combined limit of 8,192 tokens:

AllocationTokens
System instructions, question, selected history and serialization1,150
Reserved output1,024
Safety margin256
Available evidence5,762
Total8,192

Suppose the retrieved passages consume 2,100, 1,700, 2,600 and 900 tokens, respectively. Their total is 7,300 tokens, so sending all of them would exceed the evidence budget by 1,538 tokens.

If passage C (2,600 tokens) contains an indispensable exception, preserve it before spending the remaining budget on optional material. With A, C and D selected, evidence occupies 5,600 tokens, leaving 162 tokens of the evidence budget. This is an illustrative allocation, not a conclusion that these passages answer a real question.

The reserve is not necessarily the number of tokens the model will produce. It is an allowance consistent with the output limit and desired answer completeness. If the fixed instructions and mandatory reserves already exceed the window, reducing retrieved documents alone will not fix the request.

Count the rendered request#

Use the deployed model's compatible tokenizer and the actual chat or tool serialization rules. Token counts for separately encoded snippets are not necessarily additive because separators, special tokens and boundary tokenization can alter the count. Estimate candidate costs for planning, then count the complete assembled request and verify the hard limit before generation. When provider-side formatting is not fully exposed, use documented counting facilities, measured usage and a conservative margin. Handle context-length rejection explicitly rather than blindly retrying the identical request.

2. Choose the strategy by task, not just length#

The best context management depends on what the answer requires.

TaskPreferred initial strategy
Find the effective refund policyFilter by applicability, rerank and retain the relevant clause and exceptions
Answer a question spanning two documentsDecompose into subquestions and preserve evidence from both
Summarize a long manual comprehensivelySection-aware map-reduce or hierarchical summarization
Extract every obligation from a contractCoverage-oriented windows, structured extraction, reconciliation and review
Compare long documents with distributed dependenciesHierarchical navigation, iterative evidence collection or a validated larger-context model
Continue a long conversationRetain recent relevant turns and authoritative state; compress older history carefully

A top-k ranking is suited to focused evidence lookup, but may be inadequate for tasks that require exhaustive coverage. A comprehensive summary may legitimately discard detail, while an obligations extraction task must not silently discard a clause because it appears less salient to a ranker.

3. Retrieval filtering, reranking and evidence packing#

Start by reducing unnecessary context without changing the information itself.

  1. Apply authoritative authorization, tenant, effective-date, version and task-specific eligibility filters. Do not reveal unauthorized snippets, metadata or titles to the model.
  2. Retrieve candidates using suitable lexical, semantic or structured search. Broad retrieval can improve recall, but candidates are not necessarily the final context.
  3. Rerank using task relevance. Exact identifiers, exception clauses, dates and cross-references may matter more than general semantic similarity.
  4. Remove duplicate or overlapping passages without losing distinct details or provenance.
  5. Identify evidence groups that need to travel together: a rule and its exception, a table row and header, or a referenced definition.
  6. Pack the selected evidence with source IDs into the token budget, then validate the full serialized request.
Loading diagram…

The loop must be bounded. If an alternative cannot satisfy the budget and evidence requirements, stop and return an explicit limitation. Required evidence is determined by the task and available evidence analysis, not guaranteed to be identified by a ranker. A relevance score is not an authorization decision.

Packing the highest-ranked chunks is a reasonable baseline. It does not necessarily maximize answer quality or information coverage. A long high-ranked passage might consume budget that could otherwise cover several complementary sources. Diversity-aware selection, coverage constraints or budget-aware optimization can help, but depend on reliable scoring and add complexity. More aggressive pruning can reduce evidence recall.

4. Tested Python implementation: protect required evidence#

The following helpers demonstrate a combined-window budget and a deterministic, rank-priority packing policy. They accept precomputed integer token costs, including estimated passage formatting overhead. The caller must already have enforced document permissions and determined required evidence.

PYTHON
def evidence_budget(window, fixed, reserve, margin): if any(type(n) is not int or n < 0 for n in (window, fixed, reserve, margin)) or window == 0: raise ValueError('invalid token budget') budget = window - fixed - reserve - margin if budget < 0: raise ValueError('fixed prompt and reserves exceed window') return budget def pack(ranked, required, budget): # ranked: unique (source_id, positive token cost) pairs, best first if type(budget) is not int or budget < 0: raise ValueError('invalid budget') costs = dict(ranked) if len(costs) != len(ranked) or any(type(n) is not int or n <= 0 for n in costs.values()): raise ValueError('duplicate source ID or invalid cost') required = set(required) if not required <= costs.keys(): raise ValueError('missing required evidence') remaining = budget - sum(costs[k] for k in required) if remaining < 0: return None selected = set(required) for key, cost in ranked: if key not in selected and cost <= remaining: selected.add(key) remaining -= cost return [key for key, _ in ranked if key in selected], remaining
PYTHON
budget = evidence_budget(8192, 1150, 1024, 256) assert budget == 5762 ranked = [('A', 2100), ('B', 1700), ('C', 2600), ('D', 900)] assert pack(ranked, {'C'}, budget) == (['A', 'C', 'D'], 162)

The packer reserves all required passages before evaluating optional ones. It then considers optional candidates in rank order, skips any that do not fit, and returns the selected identifiers in their original rank order together with the remaining estimated budget. None means the mandatory evidence alone cannot fit. Missing required evidence is treated as an invalid selection, rather than silently ignored.

Correctness and complexity#

The budget calculation subtracts all declared non-evidence allocations and rejects negative remaining capacity. In the packer, the sum of required costs is reserved first. Each optional insertion is permitted only when its cost is no greater than the remaining budget. By induction, the selected set always fits, all required items remain present, and no source ID is returned more than once.

With positive integer costs and a fixed rank order, this greedy policy lexicographically maximizes the inclusion decisions of optional candidates among feasible subsets containing the mandatory set. At each position it includes the candidate if feasible, because excluding it cannot produce a lexicographically higher inclusion vector. This is not a general knapsack solver and does not maximize total relevance scores or claim coverage.

For n candidates, expected time and space are O(n) under ordinary hash-table assumptions, excluding prior ranking, text retrieval, tokenization and rendering. Source IDs must be hashable and ranked must be a reusable sized sequence. Required evidence groups can be represented as atomic bundles upstream, with a combined estimated cost.

Local verification#

Python 3.13.5 ran the exact helpers against:

  • 16,848 exhaustive packing scenarios: four ranked passages with costs from one through three, all sixteen possible required subsets and budgets from zero through twelve. An independent exhaustive-subset oracle selected the lexicographically greatest feasible inclusion vector.
  • 2,240 token-budget scenarios covering feasible and overflowing fixed allocations.
  • Seven invalid-input cases and two worked-example assertions.

All 19,097 checks passed. The tests verify arithmetic and selection policy on synthetic token counts. They do not verify model tokenization, semantic relevance, retrieval recall or actual prompt assembly. The final rendered-request check remains essential.

5. Contextual compression and summarization#

Compression can preserve enough evidence while reducing the number of tokens sent to the generator.

Extractive compression keeps original sentences, clauses, table entries or other source fragments and removes irrelevant material. It is relatively easy to preserve exact quotes and citations. Its main risk is dropping the surrounding context necessary for interpretation, such as a definition, negation, condition or exception.

Abstractive compression creates a shorter summary or synthesized representation. It can reduce redundant information much more aggressively, but may omit details, alter quantities, lose qualifiers or introduce unsupported claims. A generated summary is a derived artifact, not a replacement for the authoritative source.

TechniquePotential advantageRisk or cost
Select original relevant spansTraceability and exact wordingFragmentation and missing context
Query-focused summariesMore information within a small budgetExtra inference, omissions and hallucinations
Structured fact extractionExplicit fields, units and source IDsSchema may miss unusual facts or relationships
Learned prompt compressionPotential token savingsModel-specific behavior and difficult fidelity validation

For a policy question, preserve the precise wording of a relevant exception rather than replacing it with a vague summary. For a table, preserve units, row/column labels and references. For high-stakes workflows, use extractive evidence or verify summaries against the original source before depending on them.

Record which source and version produced each compressed fragment. Measure whether the compressed context still supports the expected answer. Compression does not waive access controls; the derived content may remain sensitive.

6. Hierarchical retrieval#

Large documents often have natural structure: collection, document, chapter, section, paragraph, table and attachment. Hierarchical retrieval uses that structure to narrow the search before loading detailed evidence.

For example, a customer asks which service-level agreement applies to an enterprise account in a specific region. A coarse index can identify relevant contract families and sections; fine-grained retrieval can obtain the exact applicable clause, definitions and exclusions.

A hierarchy can also store approved section summaries as navigational aids and link back to original source spans. Coarse summaries should not be the sole evidence for detailed claims.

Trade-offs:

  • Reduces irrelevant candidate volume and supports structured navigation.
  • Can miss relevant leaf passages if an early coarse-selection step is wrong.
  • Requires maintained parent-child relationships and source-version synchronization.
  • Benefits from fallback search across leaves or other recovery mechanisms when coarse retrieval has low confidence.

This is different from simply increasing chunk overlap or selecting more neighbors. It adds a structured retrieval strategy to find the most useful parts of a large collection.

7. Sliding windows and map-reduce for broad coverage#

When the task requires processing a document larger than the model window, divide the document into bounded segments that preserve relevant structure. Overlap can reduce boundary omissions, but overlapping outputs must be reconciled and deduplicated.

Sliding windows are useful for sequential scanning, extraction or review. They should not be confused with architectural sliding-window attention, which limits the attention receptive field in some models. Application-level windows are independent requests or stages and require explicit coordination.

Map-reduce is useful when processing can be decomposed into local tasks and a synthesis step. For example, map over a contract's sections to extract obligations and exceptions with source IDs, then reduce the extracted records into a consolidated inventory.

Loading diagram…

If intermediate outputs exceed the reducer budget, use hierarchical aggregation or a deterministic structured store rather than silently discarding records. For a comprehensive extraction task, preserve coverage bookkeeping per window, stable evidence identifiers, and an explicit unresolved state. An LLM reducer can introduce new errors, so validate counts, duplicate handling, source links and required fields.

Parallel map calls can reduce wall-clock time when capacity is available, but increase concurrency and total token use. Sequential refinement retains previous state across windows but can accumulate summarization errors and become order-sensitive. Neither approach guarantees global reasoning about dependencies spanning distant windows; targeted cross-reference retrieval or human review may still be required.

8. Conversation history and tool results#

Overflow may be caused by chat history or tool outputs rather than document retrieval. Separate stable instructions and structured application state from transient conversation text.

Keep authoritative state in application storage where possible. Retain the current task, relevant recent turns and essential earlier decisions. Summarize older conversation only when appropriate, with pointers to original messages if they can be retrieved safely. Do not summarize away authorization constraints, consent, unresolved commitments or task-critical identifiers.

Large tool results can be paginated, filtered, aggregated or retrieved on demand through an authorized interface. For exact calculations and exhaustive structured queries, use deterministic database or application operations instead of placing every row into the LLM context. Treat tool outputs and document content as untrusted data, not as new system instructions.

9. When to use a long-context model#

A larger-context model can simplify tasks involving many interconnected passages and reduce the need for multiple summarization stages. But nominal context capacity is not the same as effective evidence utilization.

Research on lost-in-the-middle behavior has shown that some language models perform worse when relevant evidence is placed in the middle of a long sequence. The effect depends on model, task, prompt and input distribution. It is not a universal law that the middle is always ignored, nor does moving evidence to the ends guarantee accuracy.

Compare candidates with realistic input lengths and evidence positions. Test multi-document synthesis, scattered facts and conflicting sources. Avoid repeating passages indiscriminately merely to place them at multiple positions.

Long inputs can increase prefill time, memory use and billed input tokens. In a conventional decoder with dense attention, pairwise prefill attention work grows quadratically with sequence length, while standard per-sequence KV-cache storage grows approximately linearly in cached positions for a fixed architecture and precision. Optimized attention kernels reduce intermediate memory or IO costs; some model architectures have different complexity. Benchmark the actual runtime instead of inferring a precise latency increase from sequence length alone.

A larger model window may be worthwhile if critical cross-document dependencies cannot be preserved through decomposition. It should still have explicit token budgeting, retrieval authorization and source-grounding checks.

10. Latency, cost and quality trade-offs#

ApproachMain benefitMain trade-off
Drop irrelevant/duplicate textCheap, direct reductionPoor filters can remove necessary evidence
Rerank and packConcentrates limited contextExtra ranking latency; recall depends on ranking quality
Extractive compressionRetains original wordingBoundary and context loss
Abstractive summarizationHigh compression ratioAdditional model calls and fidelity risk
Hierarchical retrievalScalable structured navigationCoarse-selection errors and maintenance
Map-reduce / sliding windowsSupports broad coverage beyond one requestMultiple calls, aggregation errors and coordination
Larger context windowRetains more original evidencePrefill, memory, price and effective-use constraints

For hosted inference, estimate cost from the total input and output tokens across all stages, plus retrieval, reranking, storage and orchestration costs under the actual provider's pricing. For self-hosted inference, measure accelerator memory, request concurrency, prefill/decode throughput and utilization.

A compressor that uses a second model call may save generator tokens but still increase total cost or latency. Parallel processing may save wall-clock time but increase resource pressure. Long-context prompting may be simpler operationally than a multi-stage pipeline. Compare cost per successful task and quality at the required latency, not token count in isolation.

11. Hypothetical customer scenario: a contract assistant#

A customer asks whether a supplier may terminate a contract early. Retrieval finds the termination provision, a general notice clause, an amendment and a definitions section. The combined material exceeds the context budget.

A naive system takes the first three chunks and omits the amendment. It produces a plausible but incomplete answer. A better approach determines the applicable contract version, identifies the amendment and its relationship to the original clause, preserves the relevant definitions and notice requirements, and removes unrelated boilerplate. It gives a source-linked answer that acknowledges any unresolved ambiguity.

If the entire agreement must be reviewed for every exception, use a coverage-oriented section extraction pipeline and reconcile cross-references. If the evidence remains incomplete, identify the missing material rather than concluding that no exception exists.

This example is fictional and illustrates engineering choices, not legal advice or a measured customer result.

12. Evaluate and monitor the system#

Use a representative held-out evaluation set containing focused lookup, multi-source questions, exhaustive extraction, long-document synthesis, unanswerable queries and access-control boundary cases.

Measure:

  • Evidence recall before and after pruning or compression, including required evidence groups.
  • Claim correctness, source support and citation accuracy.
  • Coverage of required sections or records for exhaustive tasks.
  • Compression fidelity: omitted exceptions, changed values and unsupported additions.
  • Actual rendered token counts, overflow errors, truncation events and generation-limit stops.
  • End-to-end latency percentiles, total token consumption, cost per successful task and failure rate.
  • Appropriate abstention and permission enforcement.

A useful experiment holds the model and task constant and compares full authorized oracle evidence, selected evidence, compressed evidence and a larger-context baseline. This helps isolate evidence selection failures from model reasoning failures. Do not claim a benchmark result until the relevant evaluation has actually run.

Version the tokenizer, prompt templates, model, source metadata, retrieval strategy, compression logic and budget policy. Monitor overflow and recall regressions when any component changes. Avoid logging sensitive document contents unnecessarily.

Likely interviewer follow-ups#

Why not just use the top five chunks? Five chunks may fit or overflow depending on their lengths, and their scores may not capture all necessary evidence. Select against a token budget and coverage requirements.

What if the system prompt alone is too large? Review unnecessary schemas, history and repeated instructions; keep mandatory controls intact. Use a compatible model or redesign the workflow if essential fixed content cannot fit.

Is summarization always lossy? It can preserve task-relevant information, but abstractive summarization cannot generally guarantee retention of every original detail. Validate fidelity against the source.

Does a 128K context guarantee reliable use of all 128K tokens? No. Model support, effective recall, task complexity and serving constraints must be evaluated separately.

How would you process a task that requires every clause? Use structure-aware windows, coverage tracking, structured extraction and reconciliation. Do not rely on relevance-only top-k selection.

When should you abstain? When the required evidence is missing, unauthorized, contradictory or cannot be reliably retained or combined within the allowed resources.

Interview takeaway#

Budget the complete request, preserve indispensable authorized evidence, and reduce irrelevant or redundant context first. Choose compression, hierarchical retrieval, staged processing or a larger-context model according to the task's coverage and fidelity requirements. Verify the actual rendered token count and downstream answer quality rather than silently truncating inputs.

Related questions

Explore other topics:AI AgentsAI System DesignLarge Language Models