ANTIGRAVITY LABJP
Articles/Agents & Manager
Agents & Manager/2026-05-20Advanced

Prompt Caching and Context Strategy for Antigravity Agents — Cutting 60-80% Off Monthly API Costs in Long-Running Production

The longer you keep agents running, the more the monthly invoice quietly piles up. Running Antigravity agents alongside an AdMob-monetized indie app business (50M cumulative downloads), I managed to cut API costs by 60-80% by rebuilding prompt caching and context strategy. This article shares the three-layer cache, context compression, and TTL design I now run in production — with the code and numbers behind them.

Antigravity321prompt caching2cost optimizationindie developer11agent operations5

Premium Article

Six months after I started running agents seriously, I sat down with my monthly API bill and realized it was time to redo the design. I've been shipping apps as an indie developer since 2014, and around the time cumulative downloads crossed 50 million, AdMob revenue started growing — and the agents I had built into my workflow were eating a noticeable share of that revenue as a fixed cost.

So I rebuilt the whole prompt caching and context strategy from scratch. The result: same functionality, but 60-80% lower monthly API spend. Specifically, average input tokens per agent request dropped from 12,400 to 4,800, and total monthly cost went from $480 to $112. This article walks through the design and the gotchas.

Why Prompt Caching Alone Doesn't Cut It

Prompt caching is the first thing the official docs recommend. I started there. But when I measured, my cache hit rate was only 30-40%, and the cost savings never matched expectations.

The reason was simple. I was mixing "cacheable" and "always-changing" pieces of context without separating them. System prompts and reference docs were static, but I was inserting dynamic user input and tool results between them. Prompt caching only works as a prefix match — the moment one byte shifts upstream, everything after it becomes a cache miss.

I needed to redesign the context itself as a cache layer.

A Three-Layer Cache Architecture

The structure I now run in production splits into three layers by TTL and expected hit rate characteristics.

  • Layer 1 — System prompt: ~24 hour TTL, ~99% expected hit rate
  • Layer 2 — Reference docs: ~6 hour TTL, ~85% expected hit rate
  • Layer 3 — Recent dialogue history: ~5 minute TTL, ~60% expected hit rate

The key is keeping layer order strict. Layer 1 always comes first, then Layer 2, then Layer 3. Dynamic content (user input, tool results) goes inside Layer 3, ideally at the tail. Here's the TypeScript I run:

import { Anthropic } from "@anthropic-ai/sdk";
 
interface CacheLayer {
  type: "system" | "reference" | "history";
  content: string;
  cacheControl: { type: "ephemeral" } | undefined;
}
 
const buildContext = (
  systemPrompt: string,
  references: string[],
  history: Array<{ role: string; content: string }>,
  userInput: string,
): CacheLayer[] => {
  const layers: CacheLayer[] = [];
 
  // Layer 1: system (intended for ~24h caching)
  layers.push({
    type: "system",
    content: systemPrompt,
    cacheControl: { type: "ephemeral" },
  });
 
  // Layer 2: reference docs (~6h caching)
  for (const ref of references) {
    layers.push({
      type: "reference",
      content: ref,
      cacheControl: { type: "ephemeral" },
    });
  }
 
  // Layer 3: history + dynamic input (short cache + no cache)
  for (let i = 0; i < history.length; i++) {
    const isRecent = i >= history.length - 2;
    layers.push({
      type: "history",
      content: `${history[i].role}: ${history[i].content}`,
      // do not cache the last 2 turns (they change fastest)
      cacheControl: isRecent ? undefined : { type: "ephemeral" },
    });
  }
 
  // final user input is never cached
  layers.push({
    type: "history",
    content: `user: ${userInput}`,
    cacheControl: undefined,
  });
 
  return layers;
};

The moment I switched to this structure, cache hit rate jumped from 38% to 78%. The whole idea reduces to "stable stuff first, changing stuff last." That sounds obvious in hindsight, but I had been embedding timestamps in my system prompt, which alone was killing every layer.

Thank you for reading this far.

Continue Reading

What follows includes implementation code, benchmarks, and practical content we hope you'll find useful. This site runs without ads — server and development costs are supported entirely by members like you. If it's been helpful, we'd be truly grateful for your support.

WHAT YOU'LL LEARN
How to structure a three-layer cache (system / reference / history) with separate TTLs, and the concrete code that keeps cache hit rate above 75%
Context compression plus summary snapshots that cut input tokens by 60% — the actual numbers from my Antigravity production setup
The break-even point of cost-per-request when running alongside AdMob revenue, and three traps that indie developers walk into early
Secure payment via Stripe · Cancel anytime

Unlock This Article

Get full access to the rest of this article. Buy once, read anytime. This site is ad-free — your support goes directly toward keeping it running.

or
Unlock all articles with Membership →
Share

Thank You for Reading

Antigravity Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.

  • Copy-paste ready implementation code
  • New advanced guides published daily
  • $5/mo or $10 for lifetime access
View Membership →

Related Articles

Agents & Manager2026-05-24
Designing Antigravity Agents That Survive Multi-Hour Batches — A 4-Layer Durability Pattern From the Trenches
Long-running Antigravity batch agents will fail somewhere. After running them against the operations of an indie app business, I distilled four durability layers — checkpoint granularity, persistence choice, idempotent restore, and context summarization — into a single, opinionated design memo with working code and real cost numbers.
Agents & Manager2026-04-28
Before Your Antigravity Agent Bill Goes Sideways: A Solo Developer's Forecast and Cutback Playbook
Discovering your monthly bill is an order of magnitude larger than expected is the first big trap of running agents. Here's the forecasting and cutback playbook I've built up as an indie developer, with concrete numbers, a working guardrail script, and the monthly review cycle I use.
Agents & Manager2026-07-10
Tracing Why an Agent Wrote That Line Six Months Ago — Commit Granularity and Provenance Trailers
When an agent packs 14 files and 800 lines into a single commit, git blame tells you nothing six months later. Here is how I split commits at intent boundaries, recorded provenance as machine-readable Git trailers, and built a one-command path from a blamed line back to the design decision behind it.
📚RECOMMENDED BOOKS
Build a Large Language Model (From Scratch)
Sebastian Raschka
LLM Dev
Prompt Engineering for LLMs
Berryman & Ziegler
Prompting
AI Engineering
Chip Huyen
AI Eng
* Contains affiliate links
See all →