TechEarl

Cut Your LLM API Bill in Half with Batch Processing (2026)

Every major LLM batch API is 50% off, but the limits and gotchas differ. Claude, OpenAI, and Gemini batch processing compared, Nano Banana image batches, prompt caching that stacks on top, and every other lever that cuts an AI API bill.

Ishan Karunaratne⏱️ 34 min readUpdated
Share thisCopied
Every LLM batch API is 50% off. Claude vs OpenAI vs Gemini batch compared, Nano Banana image batches, prompt caching, and the other levers that cut the bill.

Every major LLM provider runs a batch API that costs 50% of the synchronous price: Anthropic, OpenAI, and Google all halve input and output tokens for work you submit as one job and collect later. Use it whenever you process thousands of items and no human waits on any answer. This guide compares the three batch APIs, covers batch image generation with Nano Banana, prompt caching that stacks on top, and the other levers that cut an AI API bill.

If you are processing thousands of things through an LLM in a loop, and no human is sitting there waiting for any single answer, you are almost certainly paying double. The catch is that the discount is the only thing the providers agree on. The size limits, the file format, what tools run inside a batch, and how image generation is handled all differ, and a couple of those differences will quietly cost you money if you do not know them. And batching is only one lever: the model you pick and the prefix you cache often move the bill more.

Prices, batch limits, and model names were first checked in June 2026; the Anthropic prices, cache rules, and the worked examples were rechecked against Anthropic's pricing page in November 2026. These APIs move fast. I link every provider's pricing page in the Sources at the bottom, so check them before you budget a real job.

Jump to:

A true batch is not a loop

This is the part most people get wrong, so it goes first. A true batch is one request to the provider's batch endpoint carrying many sub-requests, processed asynchronously, billed at half price. It is not a for loop that grabs 100 records and fires 100 ordinary synchronous calls. That second thing is just chunking on your side. It runs at full price, it burns your per-minute rate limit, and it is the exact pattern that produces the surprise bill.

A loop firing 20,000 separate synchronous full-price calls totaling $270, versus one true batch job carrying all 20,000 requests at 50% off for $135.
The loop pays full price 20,000 times. The true batch is one async job at half the rate.

The mental model:

  • Fake batch (full price): your code loops, calling messages.create() (or chat.completions.create()) once per item. You feel like you are "batching" because you process them in groups of 100, but each call is a separate, synchronous, full-price request.
  • True batch (half price): you assemble all the items into one payload, hand it to the batch endpoint, walk away, and come back for the results. The provider schedules the work on its own time, which is why it can afford to discount it.

The trade you are making is latency for cost. Synchronous calls come back in seconds. A batch comes back within 24 hours, usually much sooner, and you give up the ability to react to any single result mid-flight. For anything where the output lands in a database, a spreadsheet, a queue, or a nightly report rather than in front of a waiting user, that trade is free money.

The 50% discount, compared across providers

All three discount input and output tokens by 50%. Everything else is where they differ.

Claude (Anthropic)OpenAIGemini (Google)
Discount50% in and out50%50%
TurnaroundUnder 1h typical, 24h max24h window24h target, often faster
Max per batch100,000 requests / 256 MB50,000 requests / 200 MB2 GB input file
Throughput capnot published2,000 batches/hournot published
Input formatJSON requests array, one custom_id eachJSONL file, upload firstinline (under 20 MB) or JSONL via Files API
Create callmessages.batches.createPOST /v1/batchesbatches.create
Caching stacks with batchyes (prompt caching)yes (automatic caching)yes (context caching)
Server tools in a batchyes (web search, fetch, code execution)limitedlimited
Image generation in a batchno image generationyesyes (Nano Banana)
Results orderunordered, key by custom_idunordered, key by custom_idinline by index, file by key

Two rows are worth dwelling on. The caching row: the batch discount and prompt caching stack, so the savings multiply on any job that shares a big prefix (see the worked math below and the prompt caching section). And the image row: Claude has no image generation (its batch still handles vision inputs, just does not produce images), while OpenAI and Gemini can batch image generation. If your high-volume job is "make 5,000 images," that work goes to Gemini or OpenAI, covered below in batch image generation with Nano Banana.

The one rule worth burning in, and the single most common bug: do not assume results come back in input order. On Claude and OpenAI you match each result to its request by custom_id, never by position; a worker that assumes line 5 of the output matches line 5 of the input will silently scramble your data the first time results come back reordered. Gemini's inline path is the exception, returning responses in request order so you can map by index, while its file path uses a key you assign.

Ten jobs worth batching

The tell is always the same: nobody is waiting for any one answer. Here are the workloads where this shows up, lightest to heaviest.

Everyday (agencies, site owners, solo developers)

  1. Bulk content enrichment in a CMS. Rewriting, summarizing, or extracting structured fields across thousands of posts or products. The WordPress version of this is its own guide: processing hundreds of WordPress posts with AI at half the cost.
  2. Product-catalog work. Generating descriptions, pulling attributes (material, fit, dimensions) into structured fields for an e-commerce catalog.
  3. SEO meta generation. Drafting titles and meta descriptions for a whole site at once.
  4. Support-ticket and review classification. Tagging a backlog by sentiment, topic, and urgency to route or report on it.
  5. Document extraction. Pulling parties, dates, amounts, and clauses out of tens of thousands of PDFs into a database.
  6. Content-library translation. Localizing a help center or catalog into several languages with a shared glossary.

Heavier (platform and ML teams)

  1. LLM-as-judge evaluation runs. Scoring thousands of model outputs against a rubric for an eval harness or an A/B test.
  2. Synthetic data generation. Producing labeled examples, test cases, or Q&A pairs to train or evaluate another model.
  3. Codebase-wide analysis. Generating docstrings, file summaries, or migration notes across an entire repository, one request per file.
  4. Research over a scraped corpus. Summarizing or extracting entities from thousands of pages, papers, or transcripts.

If a job in your stack matches the shape (high volume, latency-tolerant, output goes somewhere other than a live user), it belongs in a batch.

The cost math on a real job

Take a concrete job: enrich 20,000 records, roughly 2,000 input tokens and 500 output tokens each, on Claude Sonnet 4.6. Sonnet's standard rate is $3 per million input tokens and $15 per million output; the batch rate is half that, $1.50 and $7.50.

ApproachInputOutputTotal
Naive synchronous loop20,000 × 2,000 × $3/M = $12020,000 × 500 × $15/M = $150$270
True batch (50% off)$60$75$135

Batching alone halves it, exactly as advertised. Now stack caching. If 1,200 of those 2,000 input tokens are a shared prefix (the same instructions and schema on every record), a cache read costs 10% of base input, and that read also gets the batch discount on top, because the two stack. The 800 uncached tokens per record still cost $24 at the batch rate, so the input side drops from $60 to roughly $28 to $50 depending on your hit rate (about $28 at a 98% hit rate, about $50 at 30%, before the cache-write premium), and cache hits inside a batch are best-effort (typically 30% to 98%), so use the 1-hour cache TTL since batches can run past the 5-minute window. The caching mechanics are covered in the prompt caching section.

The headline is not "batching is cheaper." It is that the model you pick and the work you avoid usually move the bill more than batching does. The same 20,000 records on Haiku 4.5 (batch rate $0.50 in, $2.50 out) land at about $45 before caching. Anthropic's own docs put 10,000 support tickets on Haiku at about $37. Reach for the right tier first (Haiku, Sonnet, or Opus), then batch, then cache. All of the levers, in order, are in how to cut your AI API bill.

Two gotchas that cost you money

These are the things the comparison table hints at and the docs bury.

Web search is not batched. Server tools, including web search, do run inside a batch (Claude runs the same server-side agentic loop in batch mode that it does synchronously). But the batch discount applies only to input and output tokens. Web search is billed as a usage fee, $10 per 1,000 searches, and that fee is not discounted. So on an enrichment job that does one web search per record, batching halves the token cost but the search fee sits on top, unbatched. For 20,000 records that is $200 in search fees regardless of how you submit the work.

Web fetch is free, so prefer it when you can. If your job already has a candidate URL (you know the company's domain, you just need the page content), web_fetch costs nothing beyond the tokens for the content it pulls in. It is web_search, the discovery step, that costs $10 per 1,000. Restructuring a job to fetch a known URL instead of searching for an unknown one can erase the one line item that batching could not touch.

Which model for which job

Batching does not change which model you should use, and the model choice is often the bigger lever. Anthropic's own guidance lines up with what the work demands:

ModelBatch inputBatch outputBest for
Haiku 4.5$0.50$2.50Simple, high-volume, low-ambiguity work: classification, tagging, format normalization, pulling a phone number out of existing text. The default for "20,000 of something easy."
Sonnet 4.6$1.50$7.50The workhorse: enrichment that needs judgment, rewriting, structured extraction from messy input. Most directory and catalog jobs.
Opus 4.8$2.50$12.50Genuinely hard per-item reasoning, nuanced moderation, complex multi-field synthesis, or judge-style evaluation where the verdict quality matters. Overkill for most bulk enrichment.

(Prices per million tokens, batch rate, which is half the synchronous rate.)

A useful habit: run a sample of 50 records through Haiku and Sonnet, eyeball the difference, and only move up a tier if the cheaper one actually fails the task.

A runnable Node example

Here is the full Claude batch lifecycle in Node with the official SDK: build the requests, submit one batch, poll until it ends, then stream the results and key them by custom_id. The same three-step shape (create, poll, retrieve by id) applies to OpenAI's POST /v1/batches and Gemini's batches.create, with different field names.

javascript
import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic();

// Your records to enrich. In real life these come from a DB query.
const records = await loadRecords(); // [{ id, content }, ...]

// te-prefixed helpers keep the example's own functions namespaced.
function teBuildRequest(record) {
  return {
    custom_id: String(record.id), // the key you match results on later
    params: {
      model: "claude-sonnet-4-6",
      max_tokens: 1024,
      system: [
        {
          type: "text",
          text: ENRICH_INSTRUCTIONS, // stable prefix, same every record
          cache_control: { type: "ephemeral", ttl: "1h" },
        },
      ],
      messages: [{ role: "user", content: record.content }],
    },
  };
}

// 1. Submit ONE batch carrying every record (not a loop of calls).
const batch = await client.messages.batches.create({
  requests: records.map(teBuildRequest),
});
console.log(`Submitted ${records.length} requests as batch ${batch.id}`);

// 2. Poll until processing ends (minutes to hours; no open connection needed).
async function tePollUntilDone(batchId) {
  while (true) {
    const b = await client.messages.batches.retrieve(batchId);
    if (b.processing_status === "ended") return b;
    console.log(`  ${b.request_counts.processing} still processing...`);
    await new Promise((r) => setTimeout(r, 60_000));
  }
}
await tePollUntilDone(batch.id);

// 3. Stream results and key them by custom_id. Order is NOT guaranteed.
for await (const entry of await client.messages.batches.results(batch.id)) {
  const recordId = entry.custom_id; // never trust position
  if (entry.result.type === "succeeded") {
    const text = entry.result.message.content[0].text;
    await saveEnrichment(recordId, text);
  } else if (entry.result.type === "errored") {
    console.error(`  ${recordId} failed:`, entry.result.error);
  }
}

Three things to notice. The custom_id is the only safe link between a result and the record it belongs to. The shared instructions carry a cache_control marker with the 1-hour TTL, so a large enough stable prefix is cached across the batch (it has to clear the model's cache minimum to qualify). And there is no inner loop of API calls: one create, one retrieve loop, one results stream.

The same three-step shape works on the other two providers. OpenAI uploads a JSONL file first, then creates the batch against it:

javascript
import OpenAI from "openai";
import fs from "fs";
const client = new OpenAI();

// requests.jsonl: one { custom_id, method, url, body } object per line.
const file = await client.files.create({
  file: fs.createReadStream("requests.jsonl"),
  purpose: "batch",
});
const batch = await client.batches.create({
  input_file_id: file.id,
  endpoint: "/v1/chat/completions",
  completion_window: "24h",
});
// Poll client.batches.retrieve(batch.id) until status === "completed",
// then read client.files.content(batch.output_file_id) and key by custom_id.

Gemini takes inline requests directly (or a JSONL file for larger runs):

javascript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});

let job = await ai.batches.create({
  model: "gemini-2.5-flash",
  src: records.map((r) => ({ contents: [{ parts: [{ text: r.content }] }] })),
});
// Poll ai.batches.get({ name: job.name }) until job.state is terminal,
// then read job.dest.inlinedResponses (in request order).

Cut LLM API costs with prompt caching

Prompt caching lets the provider remember the prefix of a prompt across calls, so a repeated system prompt, tool definitions, or RAG context is billed at a fraction of full input cost. On Anthropic, cache hits cost 10% of base input and writes cost 1.25x, so any prefix reused within the TTL is a net win. OpenAI caches automatically for prompts above 1,024 tokens, billing cached tokens at roughly 10% of base input. On Gemini, context caching is explicit and the 2.5 family discounts cached tokens by roughly 90%. It works with or without a batch, and inside one it stacks with the 50% discount.

When caching pays off

Claude Sonnet 4.6 is $3 per million input tokens and $15 per million output. Prompt caching adds $3.75 per million tokens written to the cache (1.25x input) and $0.30 per million read from it (10% of input). Take a RAG chatbot with a 10,000-token system prompt plus retrieved context (mostly stable), a 200-token user message, and a 500-token response:

  • No caching: 10,200 × $3/M = $0.0306 input + 500 × $15/M = $0.0075 output = $0.0381 per call.
  • Cache write call: 10,000 × $3.75/M + 200 × $3/M + 500 × $15/M = $0.0375 + $0.0006 + $0.0075 = $0.0456, slightly more than no cache.
  • Cache hit calls: 10,000 × $0.30/M + 200 × $3/M + 500 × $15/M = $0.003 + $0.0006 + $0.0075 = $0.0111 per call.

Break-even is 2 calls within the cache TTL. After that you save $0.027 per call (71% cheaper); at 1,000 calls an hour that is $27 an hour on a single endpoint. Caching does not pay off for endpoints with under 1,024 tokens of stable prefix, or for one-shot workloads where the prompt never repeats.

What to cache and what not to

Cache anything stable across requests: system prompts, tool definitions (the JSON schemas for the tools the model can call), RAG context that repeats across a conversation or across users, few-shot examples, and conversation history in long sessions (Anthropic supports incremental caching where each new turn extends the cache). Do not cache user messages, per-call dynamic data like a timestamp or request ID, or outputs.

The ordering rule: stable prefix first, dynamic content last. The cache works on a contiguous prefix, so a system prompt that ends with Current time: ${now} is uncacheable. Move that timestamp into the user message instead.

Anthropic, OpenAI and Gemini caching compared

Anthropic uses an explicit cache_control marker on the content blocks you want cached; everything up to the marker is cached. You can place up to 4 cache breakpoints in a single request, so the system prompt, the tool definitions, and the RAG context can be cached independently. The default TTL is 5 minutes, refreshed on each hit; for context reused over hours, set cache_control: { type: "ephemeral", ttl: "1h" }.

OpenAI caches automatically, no marker needed. Any prompt of 1,024 tokens or longer that matches a recently seen prefix gets a discount on the cached portion, and current models bill cached tokens at roughly 10% of base input. Cache writes cost nothing extra and there is no TTL control: the cache lives for a provider-determined window. The prompt-structure rule is the same: stable first, dynamic last, prefix above 1,024 tokens.

Gemini context caching is explicit and uses a separate API: you upload the stable context, get back a cache name, and reference it in later requests. On the 2.5 family cached tokens cost roughly 10% of base input, plus a storage fee billed per MTok-hour for as long as the cache is kept alive. That suits long-lived, slowly changing context (a whole legal document, a manual); Anthropic's TTL-based caching suits high-frequency reads.

python
from google import genai

client = genai.Client()
cached = client.caches.create(
    model="gemini-2.5-pro",
    config={"contents": ["{{long_stable_context}}"], "ttl": "3600s"},
)
response = client.models.generate_content(
    model="gemini-2.5-pro",
    contents=["{{dynamic_user_message}}"],
    config={"cached_content": cached.name},
)

Prompt caching code in JavaScript and Python

Two cache breakpoints with the Anthropic SDK, one on the system prompt and one on the RAG context. Both refresh on a hit.

javascript
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();

const SYSTEM_PROMPT = `You are a helpful technical writer...
(thousands of tokens of stable instructions and examples)
`;

const RAG_CONTEXT = await fetchKnowledgeBase();

async function teAsk(userMessage) {
  return client.messages.create({
    model: "claude-sonnet-4-6",
    max_tokens: 1024,
    system: [
      {
        type: "text",
        text: SYSTEM_PROMPT,
        cache_control: { type: "ephemeral" },
      },
    ],
    messages: [
      {
        role: "user",
        content: [
          {
            type: "text",
            text: RAG_CONTEXT,
            cache_control: { type: "ephemeral" },
          },
          { type: "text", text: userMessage },
        ],
      },
    ],
  });
}
python
from anthropic import Anthropic
client = Anthropic()

SYSTEM_PROMPT = """You are a helpful technical writer..."""
RAG_CONTEXT = fetch_knowledge_base()

def te_ask(user_message: str):
    return client.messages.create(
        model="claude-sonnet-4-6",
        max_tokens=1024,
        system=[
            {"type": "text", "text": SYSTEM_PROMPT, "cache_control": {"type": "ephemeral"}}
        ],
        messages=[
            {
                "role": "user",
                "content": [
                    {"type": "text", "text": RAG_CONTEXT, "cache_control": {"type": "ephemeral"}},
                    {"type": "text", "text": user_message},
                ],
            }
        ],
    )

Check the usage field on the response: cache_creation_input_tokens is what was written, cache_read_input_tokens is what was read from the cache. Watch both in your monitoring to confirm caching is actually firing.

The 5-minute vs 1-hour TTL

  • 5-minute TTL: the write costs 1.25x input, a hit costs 10% of input on most models (5% on Opus 5.5 and Sonnet 5.5). Best when the same prefix is hit every few seconds: chat sessions and tightly scoped agents.
  • 1-hour TTL: the write costs 2x input, a hit costs the same as on the 5-minute cache. Best when the prefix is hit a few times an hour: RAG over a slowly changing knowledge base, low-traffic chatbots, and Batch API jobs, which can run well past 5 minutes.

The deciding number is the gap between reuses, not a fixed call rate. Every cache hit refreshes the entry's lifetime at no charge, so if the prefix comes back within 5 minutes each time, the 5-minute cache stays warm indefinitely and the cheaper write wins. Once the gaps stretch past 5 minutes, the 5-minute entry expires between calls and every call pays a fresh 1.25x write, while the 1-hour entry pays one 2x write and then cheap hits for the rest of the hour. Anthropic's own math puts the 1-hour write in profit after two reads, so for reuse every 5 to 60 minutes the 1-hour TTL is usually the cheaper choice.

Prompt caching pitfalls

  • Cache misses you cannot explain. Almost always a non-deterministic detail early in the prompt: timestamps, randomized IDs, per-user personalization. Diff the prefix byte for byte across two consecutive calls.
  • Caching a prefix that contains the user message. No two calls share that prefix, so cache writes pile up without ever being read.
  • Forgetting the tool definitions. A long, stable tool list is one of the biggest savings, but only if it comes before any dynamic content.
  • Counting cache writes as savings. A write costs more than no cache at all. If every call has a new prefix, caching adds cost. Only turn it on when at least 2 calls per TTL window share a prefix.
  • Switching models. The cache is per model. Moving an endpoint from claude-sonnet-4-6 to an Opus model invalidates everything, and the new model writes its cache from scratch.

Batch image generation with Nano Banana

Google's Batch API runs Nano Banana image generation at 50% off, the same discount it gives text. Nano Banana 2.5 Flash drops from $0.039 to $0.0195 per image, and the larger models halve the same way. It matters here because Claude has no image generation, so batch image work goes to Gemini or OpenAI. I run my own blog's cover images through exactly this pipeline, so the numbers below are what I actually pay.

The test is the same as text: nobody is waiting for any single image. Product imagery for a catalog of thousands of items, variations (five backgrounds, three crops, two color treatments across a set of base assets), a content wave's worth of covers, social cards or banners, per-video or per-article thumbnails, and image sets for training or benchmarking another model all land in a bucket or a CDN, not in front of a waiting user.

Nano Banana per-image pricing

Nano Banana is Google's family of Gemini image-generation models: gemini-2.5-flash-image (Nano Banana), gemini-3.1-flash-image (Nano Banana 2), and gemini-3-pro-image (Nano Banana Pro). It is priced per image, and the newer models price by output resolution, so the range covers 0.5K up to 4K outputs.

ModelStandardBatch (50% off)
Gemini 2.5 Flash Image (Nano Banana)$0.039 / image$0.0195 / image
Gemini 3.1 Flash Image (Nano Banana 2)$0.045 to $0.151$0.022 to $0.076
Gemini 3 Pro Image (Nano Banana Pro)$0.134 to $0.24$0.067 to $0.12

5,000 images on 2.5 Flash Image is $195 synchronous, $98 batched. On the Pro model at 4K it is $1,200 synchronous, $600 batched. The discount is flat, so the model and resolution choice is what sets the absolute number.

A Node example for image batches

It is still a true batch, not a loop: one async job carrying every prompt, returned within 24 hours (usually much sooner; Gemini expires any job not finished within 48). The Gemini Batch API takes inline requests (under 20 MB) or a JSONL file via the Files API. Here is the inline path with the Google GenAI SDK; the exact image-config fields are in the Gemini docs linked in Sources.

javascript
import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({});

// Your prompts, in order. In a real run these come from a queue or a DB.
const prompts = await loadPrompts(); // [{ key, text }, ...]

// Inline requests: an array of GenerateContentRequest objects.
const requests = prompts.map((p) => ({
  contents: [{ parts: [{ text: p.text }] }],
  config: { responseModalities: ["IMAGE"] },
}));

// 1. Submit ONE batch job carrying every prompt (not a loop of calls).
let job = await ai.batches.create({ model: "gemini-2.5-flash-image", src: requests });
console.log(`Submitted ${requests.length} prompts as ${job.name}`);

// 2. Poll until a TERMINAL state. Handle all four, or a cancelled or expired
//    job loops forever.
const DONE = new Set([
  "JOB_STATE_SUCCEEDED",
  "JOB_STATE_FAILED",
  "JOB_STATE_CANCELLED",
  "JOB_STATE_EXPIRED",
]);
while (!DONE.has(job.state)) {
  await new Promise((r) => setTimeout(r, 30_000));
  job = await ai.batches.get({ name: job.name });
  console.log(`  state: ${job.state}`);
}

// 3. Inline responses come back in REQUEST ORDER, so map each one to its
//    prompt by index and save the image.
const responses = job.dest?.inlinedResponses ?? [];
responses.forEach((r, i) => {
  const part = r.response?.candidates?.[0]?.content?.parts?.find((p) => p.inlineData);
  if (part) saveImage(prompts[i].key, Buffer.from(part.inlineData.data, "base64"));
});

For runs over the 20 MB inline limit, write the requests to a JSONL file, one { "key": ..., "request": {...} } object per line, upload it with the Files API, and pass the file to batches.create instead of an inline array. Each result line then carries its key, so match by key, and do not assume that path preserves order.

How I batch my blog covers

This site's covers are generated with Nano Banana, and I batch them. When a content wave needs five or ten new covers, I write a small JSONL queue of { slug, prompt } lines, submit it as one batch, and download the rendered PNGs when the job finishes, each landing in its slug's folder by key. The wrapper script handles the resumable upload, the poll, and the download; the paid step is the only thing batched, and everything after it (composing the card layout, rendering responsive variants) is free local work.

A real number: four covers went out as one batch on gemini-3-pro-image and came back in about three minutes, for roughly $0.27 batched against about $0.54 synchronous. Small dollars at four images, but it is a flat 50% every time and it scales linearly. For a single cover I want to tweak and ship in one sitting, I still use the synchronous path and pay full price, because the saving is not worth a wait on one image.

OpenAI image batches and image caveats

OpenAI's Batch API also discounts image generation by 50%, through the same POST /v1/batches flow pointed at the image endpoint, with results keyed by custom_id. Per-image pricing depends on the GPT Image model and output size, and the lineup shifts (the original gpt-image-1 was shut down on 23 October 2026), so price the specific model against OpenAI's current rate card before a large run.

  • Resolution drives the bill. On Nano Banana 2 and Pro, price scales with output size. Generate at the size you will actually use rather than defaulting to 4K.
  • Safety filtering still applies. Some prompts will be refused or return no image; handle the empty response per request so one rejection does not stall the collect step.

How to cut your AI API bill: every lever

Most large AI API bills are not large because the models are expensive, but because the workload runs at the most expensive settings: the top-tier model when a cheaper one would do, full price when half was available, the same instructions paid for on every call instead of cached once. Six levers move an LLM bill, and they compound rather than add. Apply them in roughly this order; the early ones are bigger and cheaper to implement.

LeverTypical savingEffortWhere
Right-size the model3x to 5xlowHaiku vs Sonnet vs Opus
Cut output tokensvaries, often largelowbelow
Cut input tokensvariesmediumbelow
Prompt cachingup to 90% on the shared prefixlow to mediumprompt caching
Batch processing50% on tokenslowthe batch comparison
Skip unnecessary tool feesremoves a line itemlowthe gotchas

Right-size the model

Almost always the biggest lever, and the one people reach for last. On Claude, Opus 4.8 is $5 per million input tokens and $25 output, Sonnet 4.6 is $3 and $15, and Haiku 4.5 is $1 and $5, a 5x spread on input. The mistake is defaulting every workload to the smartest model "to be safe." Classification, tagging, extraction, and format normalization usually run fine on the cheapest tier: start on Haiku, sample the output, and move up only when the cheaper model genuinely fails.

Cut the tokens, both directions

Output tokens are billed at 3x to 5x the input rate, so they are the higher-value target. Cap max_tokens to what the task needs and ask for terse output explicitly. If you only need a category label, a JSON object, or a yes/no, say so; a three-paragraph explanation when you needed one word is paying output rate for waste.

Input tokens add up when you stuff context "just in case." Retrieve the few documents that matter instead of pasting the whole knowledge base, and trim few-shot examples to the ones that change behavior. If the same large context repeats across calls, that is a caching problem, not a trimming problem. One note for 2026: the newer Opus and Gemini tokenizers can count up to about 35% more tokens than older models for the same text, so re-measure with a token counter before assuming an old budget still holds.

Skip tool fees and trim long-running agents

Server-side tools carry usage fees on top of tokens, and the batch discount does not touch them: web search on Claude is $10 per 1,000 searches, web fetch is free beyond its tokens, and code execution is free when paired with web search or fetch, otherwise billed by container-hour after a monthly free allowance. Know which steps carry a per-call fee and design them out where the answer was already in hand.

For agents that run many turns, the cost is dominated by re-sending a growing history every turn. Context editing (clearing stale tool results) and compaction (summarizing old turns) keep that history from ballooning, and tuning the effort or thinking budget keeps the model from over-reasoning on simple steps. Treat these as the advanced tier once the first five levers are in place.

Stacking the levers: one worked example

The same job as above: 20,000 records, about 2,000 input and 500 output tokens each, 1,200 of the input tokens a shared prefix.

  • Naive: Opus, synchronous, no cache. 20,000 × (2,000 × $5/M + 500 × $25/M) = $200 input + $250 output = $450.
  • Right-size to Sonnet. $3 / $15 = $120 + $150 = $270.
  • Right-size to Haiku where the task allows it, at $1 / $5 = $40 + $50 = $90.
  • Batch it (50%). $45.
  • Cache the 1,200-token prefix. The shared input drops to roughly 10% of its cost on hits. Output stays at $25 and the 800 uncached input tokens per record stay at $8, so the total lands around $34 to $42 depending on hit rate (about $34 at 98%, about $42 at 30%, before the cache-write premium).

That is $450 down to about $35, more than a 10x cut, with most of it coming from picking the right model rather than any single clever trick. Batching and caching are real, but they are the polish on top of the model choice, not a substitute for it.

Caveats before you ship

  • Results are unordered. Key by custom_id. This is the bug that scrambles data silently. (Gemini inline requests are the exception: they keep request order.)
  • Cache hits in a batch are best-effort. Because the provider runs requests concurrently and in any order, you will see hit rates anywhere from 30% to 98%. Use the 1-hour TTL and put identical cache_control blocks on every request to maximize them.
  • Server-tool batches can return pause_turn. A batch worker runs more agentic-loop iterations per turn than a synchronous request, but a long tool-using turn can still come back paused. If a result has stop_reason: "pause_turn", the turn did not finish; resubmit the paused assistant content to continue it.
  • Handle every terminal job state. A Gemini poll loop that only waits for success never exits on a cancelled or expired job.
  • Half price is the floor, not the ceiling of savings. Stacking caching and right-sizing the model usually beats the batch discount on its own.
  • Image jobs go elsewhere. Claude has no image generation. Batch image generation runs on Gemini Nano Banana or OpenAI.

What to do next

The levers that stack hardest with batching are on this page: prompt caching and right-sizing the model. For the tier decision in depth, choosing between Claude Haiku, Sonnet, and Opus is often a bigger win than batching itself.

And the applied walk-throughs:

FAQ

All three providers quote a 24-hour completion window, and all three usually finish well inside it. Anthropic says most batches end in under an hour, and Gemini expires any job not finished within 48 hours. The number to plan around is the 24-hour ceiling, not the typical time, because the whole point of batching is that you are not waiting. Image batches follow the same window.

Yes. Anthropic, OpenAI, and Google all bill batch input and output tokens at 50% of their synchronous rate. The discount is the one thing they fully agree on. What differs is the batch size limits, the file format, which server tools run inside a batch, and whether image generation is supported.

No. The batch discount applies to input and output tokens only. Server-tool usage fees, like the $10 per 1,000 web searches on Claude, are billed on top at full rate even inside a batch. Web fetch, by contrast, has no per-call fee, so prefer fetching a known URL over searching for an unknown one when you can.

Yes, and the discounts stack. A cached-token read costs 10% of base input on most models (less on the newest ones), and that read still gets the batch discount on top. The first cache write costs more (1.25x to 2x input on Claude), but you pay it once. Because batch requests run concurrently, cache hits are best-effort (commonly 30% to 98%). Use the 1-hour cache TTL, since a batch can run longer than the default 5-minute window, and put identical cache markers on every request.

They are not in the wrong order, they are in no order. Claude and OpenAI return batch results in whatever sequence the work finished, which has nothing to do with input order. Always attach a unique custom_id to each request and match results back by that id. Reading results by position is the single most common batch bug.

Right-size the model. It is usually the largest single saving (a 3x to 5x price spread between tiers) and the lowest effort, since it is a one-line change. Default everything to the cheapest tier that passes the task, then move up only where the cheaper model genuinely fails.

Not if you cut the right tokens. Capping max_tokens to what the task needs and asking for terse output removes waste, not substance. Trimming retrieved context to the documents that actually matter usually improves quality, because the model is not distracted by irrelevant material. The quality risk is in over-trimming few-shot examples or instructions the model relies on, so cut, measure, and keep what changes behavior.

Sometimes, but it is usually the smallest lever and the most disruptive to pull. The price spread between equivalent tiers across Anthropic, OpenAI, and Google is far narrower than the spread between tiers within one provider, and switching providers means re-testing quality and re-tuning prompts. Right-sizing, caching, and batching within your current provider almost always beat a provider swap.

Yes, modestly. On Anthropic, cache hits reduce time-to-first-token by 20 to 50% on prompts with large stable prefixes, because the model does not have to re-process the cached tokens. Output generation speed is unchanged.

No. The cache is keyed on the exact model identifier, so switching models invalidates it and the next call writes a fresh cache for the new model. If you route one endpoint across several models (Sonnet for most queries, Opus for hard ones), each model keeps its own cache, and each needs enough requests within a TTL window to amortize its write.

The savings per cached token are now comparable: both bill cached tokens at roughly 10% of base input. The difference is the API surface. Anthropic's explicit markers give you precise control over what gets cached and a choice of TTL, while OpenAI's automatic caching needs nothing at all, which suits low-volume workloads.

Yes, and tool definitions are one of the best things to cache. Long tool schemas can be tens of thousands of tokens combined. On Anthropic, place the cache_control marker after the tool definitions in the tools array. On OpenAI, tool definitions are part of the prompt prefix and are cached automatically above the 1,024-token threshold.

No, on any of the major providers. Caches are scoped per organization and per API key; another customer's cache is never readable from your account. For multi-tenant apps where users see different RAG contexts, keep the per-user content outside the cached region, or the savings collapse.

Yes. Nano Banana 2.5 Flash Image is $0.039 per image synchronously and $0.0195 batched, an exact halving. The larger Nano Banana 2 and Pro models follow the same 50% reduction, priced by output resolution.

No. Claude is text only and has no image generation. Batch image work goes to Gemini (Nano Banana) or OpenAI (GPT Image). Claude's Batch API is excellent for text jobs, but it cannot produce images.

Start with 2.5 Flash Image at $0.0195 per image batched; it handles most product, thumbnail, and editorial work. Move up to Nano Banana 2 (3.1 Flash) or Pro (3 Pro Image) only when you need the higher fidelity or larger output sizes, since those price by resolution and cost several times more per image.

Sources

Authoritative references this article was fact-checked against.

TagsLLMBatch APIClaudeOpenAIGeminiPrompt CachingNano BananaCost OptimizationAI

Found this useful? Pass it on.

Copied

Ishan Karunaratne

Systems and Network Architect · Chief Technology Officer

Systems and network architect and Chief Technology Officer with more than two decades designing, building, and running production software, cloud and network architecture, Linux systems, and the bare metal underneath them, and lately working AI into the stack. A US Army veteran who served in Operation Iraqi Freedom. What I write here is drawn from the full arc of that work, across architecture, engineering, and operations, not any single job.

Keep reading

Related posts

Update WordPress from a Google Sheet: an Apps Script push to a REST endpoint, a service-account pull, two-way sync, and recipes for fields, SEO and images.

Update WordPress From a Google Sheet With a REST Endpoint

Edit posts in a Google Sheet and have the changes land in WordPress: a secret-gated MU-plugin REST endpoint with an Apps Script push, a service-account pull over WP-CLI, onEdit and two-way sync, a multi-site controller, and recipes for custom fields, SEO meta, directories, menus, events and featured images.

Use sudo iotop -o to find the process hammering your disk: -o, -b, -a, -P, -d, plus pidstat for per-process CPU, memory and I/O, and nvtop for GPUs.

iotop: Find Which Process Is Hammering Your Disk

sudo iotop -o sorts running processes by live disk I/O so you can see which one is hammering the drive, with the flags for batch mode, accumulated totals, and the read/write split. Plus pidstat -u, -r and -d for a sampled per-process trace of CPU, memory, and I/O, and nvtop for live GPU usage on NVIDIA, AMD, and Intel cards.

acf/save_post patterns with code: derived fields, taxonomy sync, search-index refresh, meta mirroring, validation, and refreshing posts on saved_term.

Useful Things You Can Do with acf/save_post

acf/save_post is the hook that fires after ACF saves a post's custom fields. Useful patterns: derived field computation, taxonomy sync, search-index refresh, ACF-to-meta mirroring, validation, audit logging, refreshing posts when a taxonomy term changes (saved_term). Plus the gotchas.