Cutting Coding-Agent Token Costs by >50%: Dynamic Prompt Caching & RAG Intent Gating

Multi-turn coding agents are uniquely expensive because every tool loop replays the full system prompt, project schema, and prior file-edit history. Before optimization on Qtec Cloud, our agent re-sent a 15 KB static system instruction and ran vector RAG retrieval on every single message—even simple acknowledgments.
1. Trim & Pin the System Prefix for Cache Hits
Prompt caching only pays off when your prefix stays byte-for-byte stable across turns while volatile state (current workspace tree, active errors, tail history) moves after the cache breakpoint. Compressing redundant rules shrunk our base system prompt from 15 KB down to a tight 4 KB core.
// Separate stable policy rules from volatile turn context
const systemBlocks = [
{
type: "text",
text: CORE_AGENT_SPEC_4KB,
cache_control: { type: "ephemeral" },
},
];
// Place dynamic breakpoint right before the trailing user/tool turn
const messagesWithBreakpoint = attachDynamicTailCacheBreakpoint(
compactHistoryPreservingToolPairs(conversationHistory)
);2. Tool-Pair-Safe History Compression
Naive sliding-window truncation breaks model APIs whenever an assistant tool_use block is trimmed without its paired tool_result block. Our compactor walks message boundaries explicitly, keeping paired blocks intact while delegating background turn summaries to lightweight Flash/Haiku models.
- RAG Intent Gating skips vector search on conversational follow-ups, saving ~1,200 tokens per small-talk turn.
- 24-hour Redis embedding caching eliminates repeat embedding API round-trips on hot repository queries.
- Boundary-safe compaction preserves tool_use and tool_result pairing across arbitrarily long coding sessions.
Production Result
Across Qtec Cloud's automated suite (46 tests, 207 assertions passing), dynamic-tail Prompt Caching reached >75% cache hit rates and reduced overall agent build token cost by more than 50%.