20 questions · Interactive practice

Context Engineering interview questions

Context window budgeting, attention degradation, message pruning, prompt caching, retrieval injection, and multi-step agent memory. Click a question to reveal a focused answer, then use the examples to shape your own response.

As AI applications grow past a single prompt, what the model sees at each step matters more than how any one instruction is worded. These lessons cover managing long conversations, feeding retrieval and tool results in cleanly, and keeping multi-step agents from drowning in their own context.

By aijobsok Editorial TeamPublished 2026-07-19Updated 2026-07-28
Dynamic context budgeting
python
MAX_BUDGET = 32000
RESERVED_OUTPUT = 4000
system_tokens = count_tokens(system_prompt)
history_tokens = count_tokens(history)
retrieval_budget = MAX_BUDGET - RESERVED_OUTPUT - system_tokens - history_tokens
active_chunks = prune_chunks(retrieved_docs, max_tokens=retrieval_budget)
01What is context engineering, and how does it differ from traditional prompt engineering?

Prompt engineering focuses primarily on the phrasing, style, and instructions given to a model within a single query. Context engineering is the systems-level discipline of managing the entire contents of the model's context window across time: assembling, pruning, ranking, caching, and formatting system prompts, conversation history, retrieved knowledge, tool schemas, and external state to ensure optimal model reasoning and lowest token cost at every step.

💡 What Interviewers Look For

Differentiate prompt engineering (how instructions are worded) from context engineering (the system-level architecture deciding what enters the window at each turn).

02What is the "Lost in the Middle" phenomenon, and how do you engineer around it?

"Lost in the Middle" refers to empirical research showing that decoder-only transformers retrieve and attend to information placed near the beginning (primacy effect) and end (recency effect) of a long context window much more effectively than tokens located in the middle. To mitigate this, place critical instructions, system rules, and the immediate user query at the very beginning and end of the prompt, and place secondary retrieved reference chunks in the middle.

💡 What Interviewers Look For

Explain the "Lost in the Middle" attention degradation: models recall information placed at the very beginning and very end of the prompt better than middle tokens.

03How do you implement a dynamic token budget for an LLM application?

A token budget defines hard ceilings for each context component: Total Budget = System Instructions + History Window + Retrieval Chunks + Tool Definitions + Reserved Output Tokens. If the prompt exceeds the maximum window, deterministic priority rules dictate what gets truncated: output tokens are strictly reserved, system instructions are inviolable, and conversation history or retrieved chunks are trimmed or summarized to fit within the remaining allowance.

💡 What Interviewers Look For

Describe a dynamic token budgeting system that allocates fixed headroom for system prompts, history, retrieval, tool schemas, and model completions.

04What are the trade-offs between sliding-window truncation and rolling summarization for conversation history?

Sliding-window truncation retains only the last N messages, dropping earlier turns. It is computationally simple and guarantees recent conversational flow, but permanently forgets early user constraints, preferences, or established context. Rolling summarization periodically condenses older messages into a compact summary block while keeping recent turns intact. This preserves long-term memory, but summarization costs extra latency/tokens and can introduce subtle inaccuracies.

💡 What Interviewers Look For

Compare sliding-window message truncation (which risks losing early constraints) with rolling conversational summarization (which risks subtle fact compression loss).

05How does provider-side prompt caching work, and how does it influence context layout?

Prompt caching (available on Anthropic Claude, OpenAI, and Google Gemini) caches the key-value (KV) activations of static prompt prefixes across requests. When subsequent requests share an identical prefix (typically 1,024+ tokens), the provider reuses the cached state, reducing time-to-first-token (TTFT) by up to 80% and token pricing by up to 90%. Context must be engineered so static content (system instructions, tool schemas, reference documentation) is strictly positioned at the start, with dynamic text (timestamps, user messages) at the end.

💡 What Interviewers Look For

Explain provider prompt caching (Anthropic, OpenAI, Gemini): how keeping static prefixes identical across calls slashes latency and API token costs by up to 90%.

06How should retrieved RAG chunks be formatted when injected into the context window?

Chunks should be structured with explicit boundary delimiters (e.g., XML tags like <documents><doc id="1">...</doc></documents> or markdown headers), clear metadata (source title, section, date), and unique identifier tags. Structuring chunks cleanly prevents the model from conflating retrieved external text with system instructions, facilitates precise citations, and makes it clear that retrieved content is third-party data subject to verification.

💡 What Interviewers Look For

Structure retrieved RAG chunks cleanly with explicit metadata headers, document IDs, timestamps, and delimiters so the model can cite sources without confusion.

07How do you prevent context bloat and degraded reasoning in multi-step AI agents?

Context bloat occurs when an agent accumulates raw tool outputs, lengthy file dumps, and intermediate verbose reasoning steps over multiple turns. Countermeasures include: 1) Truncating or summarizing tool outputs before returning them to context (e.g., returning only matching rows instead of an entire SQL dump); 2) Removing completed intermediate tool call history once a subtask is verified; and 3) Using scratchpad files on disk rather than keeping full text in the context window.

💡 What Interviewers Look For

Prevent context bloat in multi-step agents by pruning intermediate verbose tool outputs, summarizing completed milestones, and discarding redundant file reads.

08What is context compaction, and what techniques are used in production?

Context compaction reduces token count while preserving semantic information. Techniques include: deterministic compaction (stripping excessive whitespace, minifying JSON payloads, removing non-informative boilerplate headers), lexical compaction (extracting key sentences or entities using lightweight NLP algorithms), and LLM-driven compaction (summarizing past conversational turns or multi-document findings into dense factual bullet points).

💡 What Interviewers Look For

Demonstrate context compaction techniques: removing whitespace, stripping unnecessary JSON keys, and summarizing repetitive log lines before prompt injection.

09How do you handle contradictory information present within the context window?

Contradictions arise when retrieved documents conflict with conversation history, or when multiple retrieved sources disagree. To resolve this, establish clear precedence rules in the system prompt: specify that retrieved documents supersede the model's internal training weights, recent retrieved documents supersede older documents based on timestamp metadata, and explicit user corrections supersede prior conversation assumptions.

💡 What Interviewers Look For

Handle contradictory context explicitly by ordering information chronologically and adding clear system rules on source precedence (e.g., retrieved docs override training knowledge).

10What is the distinction between working context, episodic memory, and semantic memory?

Working context is the active token window sent to the model for the immediate turn (immediate prompt + recent history). Episodic memory stores chronological transcripts and events from past user sessions, typically indexed in a database and retrieved when relevant. Semantic memory stores extracted general facts, user preferences, and domain entities in a vector database or knowledge graph, independent of when they were learned.

💡 What Interviewers Look For

Distinguish working context (active prompt window), episodic memory (past session transcripts), and semantic memory (vector database facts) in cognitive agent design.

11How should tool schemas and definitions be optimized for the context window?

Tool definitions consume token budget on every turn. To optimize them: write concise parameter descriptions focusing strictly on expected formats and edge cases; use compact JSON schema types; avoid providing dozens of niche tools simultaneously; and implement dynamic tool selection (retrieving and injecting only the 3-5 relevant tool schemas based on the user's current query intent).

💡 What Interviewers Look For

Design compact tool schemas by providing concise descriptions, precise parameter types, and omitting internal implementation details that confuse the model.

12How does context structure influence citation accuracy and hallucination reduction?

When context assigns explicit, short, unique reference keys to chunks (e.g., [Ref-1], [Ref-2]) and instructs the model to anchor every assertion to a reference key, citation accuracy dramatically improves. The prompt must also explicitly instruct the model: "If the provided reference documents do not contain sufficient evidence to answer the question, state that you do not know rather than fabricating an answer."

💡 What Interviewers Look For

Enforce faithful source attribution by structuring context with numbered citation markers and prompting the model to reference IDs rather than inventing URLs.

13Why can expanding context windows to 1M+ tokens actually degrade reasoning accuracy?

While massive context windows accommodate large documents, attention mechanisms must distribute weights across hundreds of thousands of tokens. This increases noise, makes the model susceptible to distraction by irrelevant details, and exacerbates latency and compute costs. Empirical testing often shows that a well-retrieved, highly relevant 8k context window outperforms an uncurated 500k context dump on reasoning tasks.

💡 What Interviewers Look For

Acknowledge that massive 1M+ context windows suffer from distraction and needle-in-a-haystack latency degradation; compact, relevant context still yields higher accuracy.

14How should context be managed during delegation from a parent agent to subagents?

A parent agent should never pass its entire accumulated conversation and tool history to a subagent. Instead, it should practice minimal context delegation: isolate the exact task description, provide only the specific input data or file paths needed, and define an explicit return contract. When the subagent completes, it returns a concise summary or structured artifact to the parent, keeping the parent's context clean.

💡 What Interviewers Look For

Isolate context between parent agents and subagents by passing only the targeted subtask requirements and returning concise summaries rather than full execution traces.

15What is a Needle In A Haystack (NIAH) test, and why is it useful?

A Needle In A Haystack test evaluates retrieval accuracy across context depth. A distinct, synthetic fact ("the needle") is placed at varying depths (e.g., 10%, 50%, 90%) across documents of varying lengths (e.g., 8k to 200k tokens "the haystack"). The model is queried about that fact. The resulting heat map reveals whether the model reliably retrieves information regardless of position or suffers from blind spots.

💡 What Interviewers Look For

Use Needle In A Haystack (NIAH) evaluations to systematically test whether a model reliably retrieves subtle facts placed at various depth percentages of the context window.

16How do you ensure multi-tenant security and prevent cross-user context leakage?

Cross-tenant leakage occurs if shared prompt caches, global memory buffers, or vector search queries accidentally mix data between users. Prevent this by enforcing strict tenant isolation in memory storage, scoping all vector queries by authenticated tenant ID, never sharing prompt cache prefixes containing tenant-specific data, and running automated regression tests that attempt cross-tenant retrieval.

💡 What Interviewers Look For

Enforce multi-tenant data boundaries by never allowing shared or cached context buffers to cross tenant boundaries or user authorization scopes.

17When should you maintain structured key-value state rather than raw conversation transcripts?

For transactional or workflow-driven applications (e.g., flight booking, ecommerce checkout, onboarding flows), state should be maintained as a deterministic JSON or database object (e.g., cart, destination, dates). Relying on the LLM to deduce the current state by reading 20 turns of chat is error-prone, token-heavy, and non-deterministic. Pass the structured state object into the prompt on each turn.

💡 What Interviewers Look For

Use structured key-value state (e.g., current order ID, authenticated user ID, cart items) rather than relying on the model to infer state from raw unstructured conversation.

18How do you update system prompts in production without breaking active user sessions?

If system prompts are updated naively mid-conversation, cached KV prefixes are invalidated, incurring latency spikes and potentially altering the model's behavior mid-dialogue. In production, version system prompts. Active sessions continue using the prompt version they started with, while new sessions initialize with the updated version, ensuring consistency and cache stability.

💡 What Interviewers Look For

Maintain prompt cache stability by isolating frequent dynamic variables (like current timestamp or random seeds) to the end of the prompt rather than the prefix.

19What is the role of tokenizer alignment in context engineering?

Different model families use different tokenizers (e.g., GPT models use tiktoken, Llama models use SentencePiece). A character or word count does not reliably predict token usage—code, non-English languages, and JSON syntax consume significantly more tokens per word. Accurate context budgeting requires counting tokens with the exact tokenizer matching the target model to prevent sudden context overflow exceptions.

💡 What Interviewers Look For

Account for tokenizer discrepancies across different model families (e.g., tiktoken vs. SentencePiece), noting that character lengths do not map 1:1 to tokens.

20How do you diagnose and debug a production failure caused by context degradation?

To debug context failures, production systems must log the exact, raw prompt string and token array dispatched to the model API for the failed turn. Inspecting this snapshot allows engineers to verify whether the critical chunk was truncated, whether noisy tool outputs diluted attention, whether prompt cache invalidated unexpectedly, or whether the model suffered from "lost in the middle" degradation.

💡 What Interviewers Look For

Debug context degradation in production by logging full un-truncated prompt snapshots at the failing turn to inspect exact token order and noise levels.

By aijobsok Editorial TeamPublished 2026-07-19Updated 2026-07-28

Sources and further reading

These primary or specialist references informed the concepts in this guide. Product details can change, so verify current documentation before implementation.