Retrieval // cache economics

RAG Bloat and Prompt Caching Limits: Stop Paying for the Same Chunks Twice

Retrieval-augmented generation saves factual calls until embeddings, chunk overlap, and cache key drift inflate every prompt. Learn how to measure RAG tax, align with provider prompt caches, and prune context before the retriever runs wild.

Engineering teams adopted RAG to ground LLMs in private wikis, ticket systems, and policy PDFs. Six months later, finance notices input token spend climbing faster than user growth. The culprit is rarely the embedding API—it is chunk sprawl. Overlapping 512-token windows duplicate paragraphs three times in a single prompt. Stale vector indexes retrieve superseded runbooks alongside current ones. Agents append entire retrieved files instead of cited spans. Provider-side prompt caching, marketed as automatic savings, only helps when byte-identical prefixes repeat; dynamic RAG inserts defeat the cache key on every turn.

Polycracker does not replace your vector database. It ensures that whatever survives retrieval—plus whatever the IDE attaches from git—enters the model through a size-aware, structure-aware intake path. Combine Tuning House maps for corpus-specific strip rules with Polydyno metrics that split “RAG tokens” versus “code tokens” so you can optimize each layer.

The anatomy of RAG bloat

Classic ingestion pipelines split documents on fixed token boundaries. Confluence exports, Notion HTML, and Markdown readmes produce uneven sections; fixed windows slice mid-sentence and duplicate headings in adjacent chunks. At query time, top-k retrieval returns both chunks; the prompt contains the same H2 twice with slightly different trailing sentences. Multiply by k=8 and a chat with three retrieval rounds—you may inject 12k tokens of near duplicates before the user question.

Code RAG is worse. Embedding every file in a monorepo without language-aware chunking treats generated GraphQL types the same as hand-written domain logic. Agents query “payments service,” receive six fragments from deprecated microservices, and hallucinate APIs that shipped three quarters ago.

Bloat sourceTypical token taxMitigation
Overlapping chunks+18–35% per retrievalSemantic chunking; MMR dedupe
Full-file attach after retrieve+4k–40k per hitSpan citation only; AST prune remainder
Stale index entriesVariableTTL + git SHA in metadata
System prompt churnCache miss 100%Freeze prefix; isolate RAG suffix

Prompt caching: what providers actually cache

OpenAI and Anthropic prompt caching (names and TTLs vary by release) hash a prefix of the combined prompt. Identical system instructions and tool definitions hit cache; changing one character in the system block invalidates the entire stored KV. RAG inserts usually land after the stable prefix, but many teams inject retrieved Markdown before tools or shuffle JSON keys—accidentally shifting the boundary and forfeiting discounts.

Design prompts as a frozen header and a volatile tail:

┌───────────────────────────────┐
│ SYSTEM + TOOLS (versioned)    │  ← cacheable prefix
├───────────────────────────────┤
│ Pruned code attach (stable SHA)│  ← cacheable while files unchanged
├───────────────────────────────┤
│ RAG hits (query-specific)     │  ← volatile tail
└───────────────────────────────┘

When code attachments flow through Polycracker ECU, serialized pruned output is deterministic for a given file hash and map version—ideal cache fodder. Pair with guidance in AST Pruning vs Prompt Compression so you do not summarize away cache keys.

Worked savings: enterprise support bot

A SaaS support bot retrieves eight chunks per turn from a 120k-article Zendesk export. Baseline prompts average 19,600 input tokens; 31% is duplicated heading text across chunks.

Optimization stepInput tokensCache hit rate (7d)
Baseline RAG19,60012%
+ MMR dedupe (k=8→5)15,20012%
+ Prefix/tail prompt layout15,20048%
+ Prune attached log snippets via ECU11,40061%

Effective cost dropped further because cached input tokens bill at reduced rates on supported tiers—check your provider invoice line items. Polydyno tags each request with rag_tokens and code_tokens when hooks are enabled, making regression visible in Grafana.

Retrieval hygiene for code-aware teams

  1. Store chunk metadata: repo, commit, path, symbol. Filter retrieves to active branch.
  2. Prefer symbol-level chunks for AST languages over naive newline splits.
  3. Cap total retrieved tokens; overflow triggers map-reduce summary at retrieval layer—not LLM summarization of code.
  4. Run MCP tool output through the same prune maps as IDE attachments (I/O bloat guide).

Embedding spend versus generation spend

Teams optimize generation tokens while ignoring embedding re-index jobs that run nightly on unbounded Confluence spaces. Track embedding dollars separately in FinOps dashboards. Incremental indexing—only changed files since last git SHA—often cuts embedding cost more than tuning k in retrieval. Polycracker maps can exclude paths from ever entering the vector store (generated artifacts, vendored SDKs) so you do not pay twice to embed what agents should never see.

Evaluation harness for chunk quality

Before changing chunk sizes, build a labeled set of fifty internal questions with authoritative answers and source paths. Measure recall@k and duplicate token rate per configuration. A smaller k with aggressive dedupe frequently beats large k with redundant overlap once generation cost is included. Document winning parameters in Tuning House so staging and production retrievers stay aligned.

Incident patterns we see in the field

Runaway RAG prompts often follow catalog migrations: new embedding model, unchanged chunk table, relevance shifts, engineers compensate by raising k. Another pattern is “attach full PDF for safety” after a compliance scare—every legal question balloons to 80k tokens. Replace with citation spans and pruned excerpts. When prompt cache hit rates crater after a deploy, diff the system prompt file character by character; a single timestamp macro in the header can invalidate an entire week of savings.

Bridging RAG and codegen in one session

Hybrid sessions attach both retrieved policy snippets and live repository files. Without coordination, total intake exceeds either budget alone. Cap each lane independently—5k tokens RAG, 12k tokens pruned code—and surface a UI warning when engineers paste megabyte logs. The ECU exhaust phase can drop lowest-scoring retrieval hits first while preserving map-mandated security files, a compromise product managers can understand.

Cost attribution for FinOps

Tag each request with cost_center and corpus_id in metadata your proxy forwards. Invoice lines become explainable: “40% spend came from legal RAG, 35% from monorepo codegen, 25% from support macros.” That split guides whether the next dollar goes to embedding hygiene or AST maps—debates that used to stall in architecture reviews.

Quick wins this week

Freeze your system prompt version string, run MMR dedupe on the retriever, and route IDE attachments through ECU before merging them with RAG tails. Re-measure cache hit rate after each change; stop when marginal gains fall below your logging noise floor. Share results in the weekly infra note so product teams see retrieval discipline as part of release readiness—not an optional science project.

When in doubt, print the fully assembled prompt prefix length in tokens before and after RAG assembly. If the delta exceeds your retrieval budget policy, fail the request in CI-like fashion rather than silently burning TPM. Prevention beats post-hoc finance meetings every single time.

RAG should narrow context, not dump the archives. Prompt caching should reward stable engineering discipline, not luck. Measure duplication, restructure prompts, and prune attachments so retrieval plus codegen stays inside TPM budgets outlined in Fix LLM Rate Limits and Latency.

Ship signed intake maps Measure cache hit rate Local pruning runtime