How do you reduce the cost and latency of an LLM app?

Learning path, stage 5 of 5: Shipping to production · question 3 of 10

Send fewer tokens, pay less per token, and wait less for each one. Cache repeated prompt prefixes, trim context, use the cheapest model that passes your evals for each step, stream output, run independent calls in parallel, batch work that isn't urgent, and cap output length. Judge cost per completed task, not per request.

Cost levers

  • Prompt caching for stable system prompts, tools and documents. A large discount on cached reads.
  • Model routing: small models for classification and extraction, big models only for hard reasoning.
  • Effort or reasoning level: low for simple routes, high only where evals show a gain.
  • Batch APIs for offline jobs (evals, backfills). Anthropic's Message Batches API costs 50% less; most batches finish within an hour, and every batch within 24 hours.
  • Shrink inputs: retrieve fewer, better chunks. Summarise long history. Return short tool results.
  • Cap outputs: a sensible max_tokens, and ask for concise answers.

Latency levers

  • Streaming for perceived speed (time to first token).
  • Parallel tool calls and sub-tasks.
  • Caching also cuts time to first token on long prompts.
  • Fewer round trips: combine steps, avoid needless agent loops.
  • Faster model or speed tiers where available.

Measure

Log tokens, cache hits, latency percentiles and cost per feature. Optimise the biggest line first.

Sources

Code example

tsx
1// Offline work through the Message Batches API (async, discounted).
2import Anthropic from "@anthropic-ai/sdk";
3
4const client = new Anthropic();
5
6export async function summariseAll(docs: { id: string; text: string }[]) {
7 const batch = await client.messages.batches.create({
8 requests: docs.map((d) => ({
9 custom_id: d.id,
10 params: {
11 model: "claude-haiku-5-5",
12 max_tokens: 300,
13 messages: [{ role: "user", content: `Summarise in 2 sentences:\n${d.text}` }],
14 },
15 })),
16 });
17
18 let status = batch.processing_status;
19 while (status !== "ended") {
20 await new Promise((r) => setTimeout(r, 30_000));
21 status = (await client.messages.batches.retrieve(batch.id)).processing_status;
22 }
23
24 const out = new Map<string, string>();
25 for await (const r of await client.messages.batches.results(batch.id)) {
26 if (r.result.type === "succeeded") {
27 const text = r.result.message.content.flatMap((b) => (b.type === "text" ? [b.text] : [])).join("");
28 out.set(r.custom_id, text); // results come back in ANY order: key by custom_id
29 }
30 }
31 return out;
32}

To run it: follow the one-time setup guide, add npm i @anthropic-ai/sdk zod @opentelemetry/api vitest, save the code as a .ts file and run npx tsx file.ts. Anything marked declare is a part you supply.

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the AI Agents & LLMs set.

Open in study app