4.4 Context Engineering, Prompt Caching & Batch Processing

Key Takeaways

  • Long context still requires relevant evidence and verified state; budget history, active inputs and generated output together.

  • Context editing selectively clears older content, compaction summarizes history, and the client-side memory tool enables authorized persistence and retrieval across conversations.

  • Prompt caching needs an eligible identical leading prefix; dynamic values belong after the reusable portion and cache costs depend on model, write TTL and hit rate.

  • Message Batches discounts input/output token rates by 50%; correlate by custom_id, plan for 24-hour expiry, separate quotas and best-effort cache hits.

  • Asynchronous batches do not guarantee interactive or other short deadlines; validate the complete workload and feature/data eligibility.

Last updated: December 2026

Context Engineering, Prompt Caching & Batch Processing

Having a 1M-token context window does not mean dumping 400,000 raw tokens into every prompt is smart architecture. Uncurated context inflates bills, slows TTFT, and degrades reasoning accuracy—a failure mode known as context rot. Effective context engineering curates what enters the window, where it sits, and how repeated prefixes are cached or batched.

Context Composition & Mitigating Lost-in-the-Middle

Long contexts can degrade recall and focus (context rot); information placement can matter, but the degree and pattern depend on the model and task. Measure performance as context grows. In multi-turn agent loops, raw tool outputs (HTML dumps, verbose JSON pagination envelopes, duplicate stack traces) rapidly crowd out core rules.

Architects prevent context rot with three concrete practices:

  1. Anchor High-Signal Blocks at Boundaries: Keep immutable policies and schemas at the top of the prompt, and maintain a distilled <case_facts> block (confirmed user IDs, amounts, dates, constraints) immediately adjacent to the latest turn so critical state is easy to find. Keep authorization and canonical state in application controls, not only prompt summaries.
  2. Trim & Project Tool Outputs: Strip unused metadata, HTML boilerplate, and oversized arrays inside tool wrappers before returning observations to Claude. Return compact, schema-projected fields or paginated slices with summary counts.
  3. Structured History Compaction: When the measured context budget or loss of focus warrants it, summarize resolved earlier turns, retain recent details and preserve verifiable canonical state. The threshold is workload- and model-specific.

Prompt Caching Mechanics & Payload Ordering

Prompt caching lets the API reuse processing of a matching prefix rather than paying full input rates and processing time on repeated content. It is not a cache of completed answers.

  • Exact Prefix Matching: Caching evaluates tokens sequentially from position zero (tools -> system -> messages). A changed value within the cached prefix prevents matching from that point; earlier unchanged eligible breakpoints may still hit.
  • Automatic vs. Explicit Breakpoints: Top-level automatic cache_control simplifies single-boundary caching on growing conversations, whereas explicit block-level cache_control breakpoints let architects pin up to four strategic boundaries (e.g., end of tool schemas, end of static system prompt, end of a 150K-token static RAG corpus, and end of prior conversation history) so changes after a stable corpus may preserve its cache, subject to model configuration, minimum length and TTL.
  • Economic & Latency Impact: For direct Claude API pricing, the usual five-minute write is 1.25x and the one-hour write is 2x the base input rate. Read multipliers are model-specific: 0.1x for many models, 0.05x for Sonnet 5.5/Opus 5.5, and 0.025x for Fable 5.2. For a hypothetical model with a 0.1x read multiplier, one five-minute write plus one hit costs 1.35x versus 2x uncached; one write and 99 hits costs 11.15x versus 100x (88.85% reduction on that prefix). A one-hour write plus two hits costs 2.2x versus 3x. These calculations assume the same prefix, no expiry or other invalidations, and exclude dynamic input/output charges. Caching can reduce TTFT; measure its actual effect.
  • Minimum Cacheable Thresholds & Compaction Strategy: Always verify your prefix meets minimum cacheable token thresholds before adding breakpoints, and avoid triggering full compaction on every turn—choose compaction timing based on context and task requirements; rewriting old messages can invalidate affected cached history. The current latest models have model/surface-specific cache minimums; check the docs instead of assuming any prompt length will cache.

The Volatile-Prefix Anti-Pattern

Never place dynamic per-request metadata—such as current_timestamp, request_uuid, user_id, or per-query retrieved snippets—inside the static system prompt ahead of cache_control breakpoints. Injecting Timestamp: 2026-12-03T14:22:09Z at line 3 can make the system-prefix and later caches miss on each distinct request. Put dynamic content after the intended stable breakpoint, and verify cache creation/read counts and lifetime. Tool-prefix caching may still hit.

Context lifecycle: select the right mechanism

NeedMechanismTrade-off
Clear bulky obsolete tool results or old thinkingContext editing (supported beta feature)Selectively removes content; needed evidence must not be discarded
Keep a long conversation within the context budgetCompactionReplaces older turns with a model-generated summary; test for lost constraints and keep essential recent turns
Preserve durable project facts across conversationsMemory toolClient-side file operations backed by application-controlled storage; isolate by tenant/user, validate access and enforce retention

Anthropic currently recommends server-side compaction where available for long-running tasks; on-demand and threshold-driven options differ in who initiates compaction and how the returned summary replaces older turns. Context editing is useful for fine-grained clearing. The memory tool is not implicit model training or unlimited context: the application executes requested operations and controls storage, while Claude reads the relevant entries when needed. Preserve source references and unresolved decisions outside lossy summary text. Treat stored memories as data, not authority. Check the actual feature/data-handling matrix before using regulated content (e.g., the context editing beta is not HIPAA eligible).

For example, a support agent with stale verbose tool outputs needs selective clearing and compacted history; a later independent support session that needs a verified account preference can load the approved record from scoped memory. If an old policy version was superseded, storing the stale summary indefinitely makes errors more likely. Use versioned references and revalidate critical state.

Loading diagram...
Optimal Prompt Payload Ordering for Cache Hit Maximization

Message Batches API & Stacking Offline Savings

When workloads do not require synchronous human-facing responses, the Message Batches API processes large queues asynchronously with best-effort completion and expiration if unfinished after 24 hours (many finish sooner) at a 50% discount on both input and output tokens.

How Batch Correlation Works

Each item in a batch submission carries a developer-assigned custom_id (for example, doc-88412-pass1). Because batch items execute asynchronously and may be returned out of submission order, downstream consumers reconcile results reliably using custom_id rather than array index.

Stacking Batch API + Prompt Caching

Eligible batch and prompt-caching discounts can stack. Cache hits in batches are best-effort, not guaranteed. Consider an offline nightly pipeline evaluating 20,000 approved non-sensitive documents against a shared 50,000-token compliance rubric on Claude Sonnet 5.5 (1,000M shared rubric tokens + 20M unique document tokens input; 10M output tokens). Assume uncached base rates of $2 and $10 per million, unchanged token counts, and no extra fees:

Execution ModeShared Rubric Input CostUnique Input + Output CostTotal Job Cost
Standard Synchronous (No Cache)1,000 x $2.00 = $2,000.00$40.00 + $100.00 = $140.00$2,140.00
Message Batches Only (50% Off)1,000 x $1.00 = $1,000.00$20.00 + $50.00 = $70.00$1,070.00
Batches + Cache (80% read / 20% five-minute write)800 x $0.05 + 200 x $1.25 = $290.00$20.00 + $50.00 = $70.00$360.00

When Batch API Is Disqualified

Despite its 50% input/output rate discount, the Message Batches API is strictly disqualified whenever an SLA demands a synchronous response or a short guaranteed deadline:

  • Disqualified: Live customer support chat, interactive IDE assistants, synchronous checkout fraud checks, and real-time voice/webhook responders.
  • Ideal Fit: Nightly LLM-as-judge evaluations, large-scale historical document backfills, bulk classification/enrichment, and synthetic dataset generation when permitted. Check maximum batch size (100,000 requests or 256 MB), separate quotas, expiration and retry/failure results; batches are not ZDR/HIPAA eligible on the Claude API.

Context & Caching Checklist

  • Deterministic serialization: Sort tool definitions and JSON keys deterministically to keep the prefix stable; byte/prefix matching still depends on the actual payload and model settings.
  • Monitor cache hit ratios: Alert immediately if cache_read_input_tokens drops below expected baselines—investigate changed prefixes, TTL expiry, minimum cacheable length, model behavior or configuration changes.
  • Right-size TTLs: Use the default 5-minute TTL for rapid-fire agent loops and active queues; choose extended 1-hour TTLs when sparse human-in-the-loop workflows pause for 10–45 minutes between turns.

The cache row uses Sonnet 5.5’s documented cache-read rate of 0.05x base input: with the batch input rate of $1/MTok, reads are $0.05/MTok and five-minute writes are $1.25/MTok. Actual hit rate, write frequency, request limit and TTL determine spend; the illustrative 80% hit rate is not promised.

Official references

Test Your Knowledge

An engineering team caches a 75,000-token static policy handbook in the system prompt, yet production telemetry shows cache_read_input_tokens is 0 on every request and no eligible system-prefix reads occur. Inspecting the request builder reveals the system prompt starts with Current UTC: 2026-12-03T12:04:19Z | User: usr_9921 followed by the handbook and cache_control. Why is caching failing?

A

Prompt caching requires a minimum of 100,000 tokens before any prefix block can be stored

B

System prompts cannot be cached when tool schemas are omitted from the request

C

Cache reads only activate inside the Message Batches API and never apply to synchronous requests

D

The dynamic timestamp and user ID inside the system prefix change its content before the breakpoint, preventing reuse of that prefix.

Test Your Knowledge

An approved non-sensitive contract classification workload can run asynchronously over the weekend, with enough slack to handle expired or failed requests. It uses an identical 40,000-token rulebook across requests. Which approach should be evaluated for savings?

A

Submit synchronous requests one by one with effort: "max" and no caching so every contract gets fresh attention

B

Use eligible Message Batches with cache_control at the end of the stable rulebook, custom_id correlation, and monitored hit rates and completion.

C

Duplicate the 40,000-token rulebook inside a volatile header with per-contract timestamps to bypass cache TTL limits

D

Split the 50,000 contracts into real-time streaming chat sessions to qualify for the 50% batch discount

Test Your Knowledge

During a 35-turn troubleshooting agent session, the model begins ignoring a critical customer account constraint established on turn 2 because turns 4–30 include huge raw JSON API responses from a logging tool. What context-engineering strategy best prevents this failure?

A

Disable tool-output filtering and switch to temperature=1.0 so the model samples older facts randomly

B

Move the system prompt to the middle of the conversation history so it sits closer to turn 18

C

Trim/project verbose tool outputs to essential fields, compact resolved history into a structured summary, and maintain an anchored case-facts block near the active turn

D

Remove all conversation history after turn 5 without preserving any extracted state

Test Your Knowledge

A customer-facing checkout assistant must score cart fraud risk and reply to the shopper within 1.5 seconds before payment authorization completes. A junior engineer proposes migrating this call to the Message Batches API to save 50% on tokens. Why should the lead architect reject this proposal?

A

Message Batches is asynchronous and does not promise a completion time compatible with the 1.5-second synchronous deadline.

B

The Message Batches API prohibits JSON Schema structured outputs via output_config.format

C

The Message Batches API charges a 2x surcharge on output tokens compared to synchronous calls

D

The Message Batches API drops custom_id fields whenever requests include system prompts

Test Your Knowledge

A team wants to keep the latest confirmed project decisions available across independent Claude API conversations without replaying every historic message. Which feature best fits, if scoped storage and retention are implemented by the application?

A

Client-side memory tool with validated, tenant-scoped storage and retrieval

B

Increasing max_tokens so every old conversation is automatically available

C

Context editing alone, because clearing old tool results permanently stores them for future conversations

D

Prompt caching alone, because cached prefixes act as a searchable durable database

Sections you finish are checked off in the contents.