Skip to the solution
EasySystem Design14 min read

Context windows in 2025-26: how do you use 128k-1M tokens without drowning?

604 views

The problem

Question presented to candidate: "Models now advertise context windows from 128k up to a million tokens. If you can fit a whole contract or a whole codebase in one prompt, why would you still build retrieval? How do you actually use a very large context window well?"

What a strong answer should cover:

  • Advertised window is not effective window: recall is weaker in the middle of long inputs (lost in the middle), benchmarks such as RULER found many models fall short of their claimed length on harder tasks than single-needle lookup, and quality degrades with distractors
  • Cost and latency scale with input: every token is paid on every call and must be processed before the first output token; some providers bill long requests at a higher rate above a threshold, and caching changes the arithmetic for a reused document
  • When long context wins: one large, bounded input asked many questions (a contract, a codebase snapshot), cross-document reasoning, cached prefixes; when retrieval wins: corpora larger than any window, high query volume, frequently changing data, a need for citations
  • Placement: long documents first, instructions and question last, each document tagged with its source, most relevant material at the edges, ask for supporting quotes before the answer
  • Measure it on your own data: multi-needle and distractor tests at several depths and lengths, not one single-needle demo

Clarifying questions expected:

  • How large is the corpus, how often does it change, and how many queries per day hit it?
  • Are we asking many questions about one document, or searching across many?

Code / implementation expected: Optional β€” the cost arithmetic of stuffing versus retrieving, a reordering of chunks for the edges, or a needle-at-depth test harness.

  • context-window
  • long-context

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

14 min read Β· 12 sections

Read the code

Stuff vs retrieve cost at volume, edge ordering, and a needle-at-depth harness
// Long context without drowning: (1) cost of stuffing vs retrieving at volume,
// (2) placing the best chunks at the edges, (3) a needle-at-depth test harness.
// Prices are ILLUSTRATIVE round numbers, not any vendor list.
const WINDOW = 1_000_000;
const PRICE = 3.0;           // $ per 1M input tokens up to the long-context threshold
const LONG_THRESHOLD = 200_000, LONG_MULT = 2; // whole request billed at 2x above it
const CACHE_READ = 0.1;      // cached prefix tokens billed at 10% of the input price
const QUERIES_PER_MONTH = 300_000;
const OVERHEAD = 1_500;      // instructions + question per request

function perRequest(tokens, cachedTokens = 0) {
  const rate = tokens > LONG_THRESHOLD ? PRICE * LONG_MULT : PRICE;
  return ((tokens - cachedTokens) * rate + cachedTokens * rate * CACHE_READ) / 1e6;
}
function money(x, d = 2) {
  const [int, frac] = x.toFixed(d).split(".");
  return "$" + int.replace(/\B(?=(\d{3})+(?!\d))/g, ",") + "." + frac;
}

const CORPORA = [["one contract", 90_000], ["mid codebase", 600_000], ["company wiki", 40_000_000]];
console.log("corpus         tokens      strategy          tok/request  $/request  $/month");
for (const [name, size] of CORPORA) {
  const rows = [];
  if (size + OVERHEAD <= WINDOW) {
    rows.push(["stuff all", size + OVERHEAD, perRequest(size + OVERHEAD)]);
    rows.push(["stuff all+cache", size + OVERHEAD, perRequest(size + OVERHEAD, size)]);
  } else rows.push(["stuff all", size + OVERHEAD, null]);
  const rag = 8 * 800 + OVERHEAD; // top-8 chunks of 800 tokens
  rows.push(["retrieve top-8", rag, perRequest(rag)]);
  for (const [s, tok, cost] of rows) {
    const c = cost === null ? "does not fit" : `${money(cost, 4).padStart(9)}  ${money(cost * QUERIES_PER_MONTH)}`;
    console.log(`${name.padEnd(14)} ${String(size).padStart(10)}  ${s.padEnd(16)} ${String(tok).padStart(11)}  ${c}`);
  }
}

// (2) Edge ordering: rank 1 is most relevant. Alternate front/back so the
// weakest chunks end up in the middle (the idea behind LangChain LongContextReorder).
function edgeOrder(ranked) {
  const front = [], back = [];
  ranked.forEach((x, i) => (i % 2 === 0 ? front.push(x) : back.unshift(x)));
  return [...front, ...back];
}
const ranked = [1, 2, 3, 4, 5, 6, 7, 8];
console.log("\nretrieval order:", ranked.join(" "));
console.log("edge order:     ", edgeOrder(ranked).join(" "), "(best at both ends, weakest in the middle)");

// (3) Needle-at-depth harness. Filler sentences, one fact inserted at a depth.
const FILLER = "The quarterly report lists routine facility updates and staffing notes.";
const NEEDLE = "The vault access code for project Heron is 4417.";
const QUESTION = "What is the vault access code for project Heron?";
function buildHaystack(nSentences, depth) {
  const s = Array(nSentences).fill(FILLER);
  const at = Math.round((nSentences - 1) * depth);
  s.splice(at, 0, NEEDLE);
  const text = s.join(" ");
  return { text, needleTokenPos: Math.ceil(text.indexOf(NEEDLE) / 4), totalTok: Math.ceil(text.length / 4) };
}
// Canned answers stand in for a model; the harness scores them.
const CANNED = { 0: "4417", 0.25: "The code is 4417.", 0.5: "I could not find a code.", 0.75: "4471", 1: "Code: 4417" };
const grade = (answer) => /\b4417\b/.test(answer);
console.log("\nneedle test, 2000 filler sentences:");
console.log("depth  needle at tok  of total  canned answer               pass");
let pass = 0;
for (const depth of [0, 0.25, 0.5, 0.75, 1]) {
  const h = buildHaystack(2000, depth);
  const ok = grade(CANNED[depth]);
  pass += ok;
  console.log(`${(depth * 100).toFixed(0).padStart(4)}%  ${String(h.needleTokenPos).padStart(13)}  ${String(h.totalTok).padStart(8)}  ${CANNED[depth].padEnd(26)}  ${ok ? "yes" : "NO"}`);
}
console.log(`recall ${pass}/5 for question: ${QUESTION}`);

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 5 of 83 in AI engineering

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextEasy

What is RAG and why use it instead of fine-tuning for knowledge?

Continue