Prompt Caching and Batch Processing

Two provider features that can cut cost and latency dramatically when used deliberately: caching repeated prefixes and batching offline work.

Intermediate · about 4 hours · difficulty 3/5

Learn first: Messages APIs and Provider SDKs

Prompt caching

Many requests share a long, identical prefix: the same system prompt, tool definitions, a large document or a long chat history. Providers can cache the processed prefix (the KV cache from earlier) so later requests reuse it. Cached input tokens are billed at a fraction of normal price and the response starts faster.

How to benefit:

  • Put stable content first (system prompt, tools, documents) and variable content last (the latest user message).
  • Do not inject timestamps or random IDs at the top of the prompt; any change breaks the cache from that point onward.
  • Depending on the provider, caching is automatic or requires explicit cache markers. Caches expire after a few minutes of inactivity, sometimes with longer options.
  • Monitor cache hit metrics in the usage data.

Batch APIs

For work that does not need an immediate answer (classifying a million records, running nightly evals, generating embeddings for a corpus) batch APIs accept a file of requests and return results within hours at a significant discount, often around half price, with separate, higher throughput limits.

Pitfalls

Caching is invisible when it silently fails; check the usage fields. For batches, make each request carry an ID so you can join results back, and plan for partial failures.

Good enough to move on

You can restructure a prompt for cache hits, show a measurable drop in cost and latency, and run a batch job end to end.

Key concepts

  • How prefix caching works
  • Ordering prompts for cache hits
  • Cache TTLs and explicit breakpoints
  • Reading cache usage metrics
  • Batch APIs for offline jobs
  • Joining and retrying batch results

Mini project

Take a Q&A bot that sends a long document with every question, add prompt caching, and report the before-and-after cost and latency over 30 questions; then rerun the same 30 questions through a batch API.

Check yourself

You added the current timestamp to the first line of your system prompt and cache hits dropped to zero. Why?

Free resources