Prompt caching, batching and latency engineering
Where an LLM call spends its time and money, and the three levers that cut both: cache the prefix, batch what nobody waits for, stream what someone does
Your system prompt is 50,000 tokens of documentation followed by the line 'Current time: 14:03:22'. You put a cache_control breakpoint on the system block and send 20 requests, one per second. What does usage report?
An LLM call has a cost in seconds and a cost in dollars, and both are dominated by tokens. This chapter takes the call apart: where latency comes from, what prompt caching stores and when it pays, what the Batch API trades for half price, why streaming changes how long a user thinks they waited, and how to measure all of it honestly. The lab measures it on a 50,000-token prompt built from this repository’s docs.
Where the time goes
A request to a transformer model runs in two phases.
Prefill reads the whole input. Every input token is processed, and because the model already knows all of them, the work runs in parallel across the sequence on the accelerator. Its output is the key-value (KV) cache for the prompt, the internal state attention needs, and the first output token. Prefill time grows with input length; on hosted models a few thousand input tokens are a small fraction of a second and tens of thousands are a noticeable part of the wait.
Decode generates the rest of the output one token at a time. Each token depends on the one before it, so the phase is sequential, and its speed is measured in output tokens per second. A model that writes 80 tokens per second takes about 6 seconds to write a 500-token answer, however short the prompt was.
That gives you the two numbers that describe an interactive call:
| Metric | What sets it | What moves it |
|---|---|---|
| Time to first token (TTFT) | Network, queueing, prefill of the uncached input | Shorter or cached prefix, smaller model, region |
| Output tokens per second | Decode speed of the model and serving stack | Model choice, fast modes, output length |
| Total time | TTFT + output tokens / tokens per second | Asking for less output, all of the above |
Reasoning models add a third phase in the middle: thinking tokens are decode tokens you are billed for and wait for, even when the API does not show their text. On Claude models with adaptive thinking, output_config.effort is the lever: lower effort means fewer thinking tokens, a shorter wait and a smaller bill. For a short classification there is often nothing to think about, and the lab turns thinking off on the one model where that is allowed at low effort.
The arithmetic has a consequence most people miss. For a chat answer of 300 tokens, decode dominates total time and prefill dominates TTFT. Cutting the prompt from 50,000 tokens to a cached prefix improves what the user notices first; cutting the answer from 300 tokens to 100 improves the total. They are separate optimisations.
Prompt caching: what is cached
Prefill of the same prefix produces the same KV state. Prompt caching keeps that state for a while and reuses it when the next request starts with the identical bytes. On the Claude API the cached prefix follows the render order tools, then system, then messages, up to and including a block you mark with cache_control:
system=[
{"type": "text", "text": "You answer questions about the ATLAS docs."},
{"type": "text", "text": DOCS, "cache_control": {"type": "ephemeral"}}, # breakpoint
],
messages=[{"role": "user", "content": question}], # varies; after the breakpoint
The facts that decide whether it works, all from the prompt caching docs:
- Prefix match. One byte different before a breakpoint and the entry misses from that byte on. The usual culprits are a timestamp or request id in the system prompt, JSON serialised with unstable key order, a tool list built from a set, and adding or removing an image. Changing the thinking configuration invalidates the messages part.
- Up to 4 breakpoints per request. Put them at stability boundaries: end of tools, end of the static system prompt, end of the conversation so far. A top-level
cache_controlfield on the request places one automatically on the last cacheable block, which suits multi-turn chat; explicit markers suit a shared prefix with a varying question, where the automatic one would land after the question and write an entry nobody reads. - Minimum length. Shorter prefixes are silently not cached. It is 512 tokens on the current Opus 5.5, Sonnet 5.5, Haiku 5.5 and Fable 5.1 models, but 1,024, 2,048 or 4,096 on several older ones (4,096 on Haiku 4.5 and Opus 4.6). Check the table for the model you use.
- TTL. The default lifetime is 5 minutes, refreshed free on each hit;
"ttl": "1h"buys an hour at a higher write price. The clock starts at the start of the request, so a long generation eats into it. - Availability. A new entry is readable only once the first response that writes it has started streaming. Fire 50 parallel requests with a cold prefix and all 50 pay full price. Send one, wait for its first token, then fan out.
- Scope. Caches are per workspace on the Claude API and are model-specific. Traffic split across two models or two workspaces warms two caches.
Verify with the usage fields, never by assumption. cache_creation_input_tokens is what you wrote this request, cache_read_input_tokens what you read, and input_tokens the uncached remainder after the last breakpoint. Total prompt size is the sum of the three.
Prompt caching: what it costs
Pricing per million tokens, from the pricing page at the time of writing (Haiku 5.5 prices are for prompts up to 100,000 tokens; above that every Haiku 5.5 rate is five times higher):
| Model | Base input | 5-min write | 1-hour write | Cache read | Output |
|---|---|---|---|---|---|
claude-haiku-5-5 |
$0.10 | $0.125 | $0.20 | $0.01 | $0.50 |
claude-sonnet-5-5 |
$2.00 | $2.50 | $4.00 | $0.10 | $10.00 |
claude-opus-5-5 |
$4.00 | $5.00 | $8.00 | $0.20 | $20.00 |
claude-fable-5-1 |
$10.00 | $12.50 | $20.00 | $0.25 | $50.00 |
A write costs 1.25x base for the 5-minute TTL and 2x for the hour. A read costs 0.1x on most models, Haiku 5.5 included, 0.05x on Opus 5.5 and Sonnet 5.5, and 0.025x on Fable 5.x and Mythos 5.x. So the 5-minute cache breaks even on the second request (1.25 + 0.1 is less than 2), and the 1-hour cache on the third. On Sonnet 5.5 the Why’s 60,000-token prefix costs $0.12 per request uncached and $0.006 per cached read, a factor of 20.
Choose the TTL by the gap between requests that share the prefix. Under 5 minutes apart, the default TTL stays warm on its own and is strictly cheaper. Between 5 and 60 minutes, the 1-hour write is the only one that survives. Hours apart, nothing survives and caching only adds the write premium.
Ordering a prompt for cacheability
Write prompts in order of how often each part changes, most stable first:
- Tool definitions, in a fixed order (sort them by name).
- The system prompt: role, rules, reference documents, few-shot examples. No dates, no user names, no request ids.
- The conversation so far.
- The new user message, and anything per-request: the current time, retrieved passages for this question, the user’s account details.
Put a breakpoint after 2, and let automatic caching place one at the end of 3. Anything dynamic you feel tempted to put in the system prompt belongs in 4. If an instruction must change mid-conversation, the current Claude models accept a role: "system" message appended to messages, which adds the instruction without rewriting the cached prefix. The opposite mistake, editing the top-level system prompt per turn, throws away the whole cache every turn.
The same reasoning applies to your own serving stack. vLLM and llama.cpp both reuse KV state for a repeated prefix, and you will see a local version of the effect in the lab’s first step.
Batching offline work
A lot of LLM work has no user waiting: nightly classification, evaluation runs, backfills, summarising yesterday’s tickets. The Message Batches API takes up to 100,000 requests or 256 MB per batch, processes them asynchronously, and charges 50% of standard prices on every token, cache reads and writes included; the discounts multiply. Most batches finish within an hour; a batch that has not finished within 24 hours expires, and results stay downloadable for 29 days.
batch = client.messages.batches.create(requests=[
Request(custom_id=f"p-{pid}", params=MessageCreateParamsNonStreaming(
model="claude-haiku-5-5", max_tokens=256, messages=[...]))
for pid, ... in rows])
# poll client.messages.batches.retrieve(batch.id).processing_status until "ended"
for r in client.messages.batches.results(batch.id): # any order: key by custom_id
...
Three things catch people out. Results come back in any order, so key them by custom_id, never by position. Each request is validated asynchronously, so a malformed one shows up as errored when the batch ends rather than as an exception when you submit; send one request through the normal endpoint first. And a batch has no tool loop: each request is one shot. Because batches can run longer than 5 minutes, use the 1-hour TTL if requests share a large prefix, and treat cache hits inside a batch as best effort.
The rule: if nobody is waiting on the response, it goes in a batch. If somebody is, it never does; 24 hours is an expiry, not a service level.
Streaming for perceived latency
Streaming does not make the model faster. It changes what the user sees: with stream=True (or the SDK’s messages.stream()) text arrives as server-sent events, message_start, then content_block_start, a series of content_block_delta events carrying text_deltas, content_block_stop, message_delta with the stop reason and cumulative output token count, and message_stop. The user starts reading at TTFT instead of at total time. For a 500-token answer at 80 tokens per second, that is the difference between staring at a spinner for 7 seconds and reading after under one.
Streaming has two other benefits. Long outputs on non-streaming requests can hit HTTP timeouts; the SDKs require streaming for very large max_tokens, and get_final_message() gives you the assembled response when you do not care about the individual events. And you can measure TTFT, which a non-streaming call hides inside total time.
What streaming does not fix: a slow prefill (the user still waits for the first token), and anything you do after the model finishes, such as validating structured output before showing it. If you must validate the whole response first, streaming buys you nothing visible; show progress instead.
Model choice is a latency lever
Smaller models decode faster and prefill faster. For classification, extraction and routing, a Haiku-class model often matches a larger one on accuracy at a fraction of the latency and cost, and the choosing-a-model chapter measures that properly. Two further knobs exist on the Claude API: output_config.effort, which trades thinking depth for speed within one model, and fast mode on the Opus models (a beta at premium pricing, up to 2.5x the output speed). Caches are model-specific, so a cascade that routes between models also splits its cache.
Measuring: percentiles, not averages
Latency distributions are skewed. Most requests hit a warm cache and a free server; a few miss the cache, queue behind a burst, or retry once. Ten requests at 0.4 s and one at 6 s average 0.9 s, a number no request experienced. Report p50 for the typical user and p95 or p99 for the unhappy ones, per route and per model, and alert on the tail. The Observability course chapter on histograms and percentiles covers why you cannot average percentiles across instances either.
The tail matters more as calls compose. An agent that makes five model calls in sequence pays five tails; a page that fans out to ten calls in parallel waits for the slowest. The simulation below is the general version of that effect.
// wait for every shard
const parts = await Promise.all(shards.map((s) => s.query(q)));
// latency = the slowest of N callsasync function hedged(q, replicas, delayMs) {
let done = false;
const first = replicas[0].query(q).finally(() => { done = true; });
// send the backup only if the primary is still silent after delayMs
const backup = sleep(delayMs).then(() => (done ? first : replicas[1].query(q)));
return Promise.any([first, backup]); // first answer wins
}
const parts = await Promise.all(shards.map((s) => hedged(q, s.replicas, P95_MS))); Watch the parent request’s p99 while the fan-out grows: each backend is fast at the median and the parent is slow anyway, because it waits for the worst of them. Then turn on hedged requests and see the tail collapse for a few percent more load. The same trade is available for LLM calls with a second request after a deadline, at the price of paying for both.
Log, for every call: model, input tokens, cache read and write tokens, output tokens, TTFT, total time, and stop reason. With those you can compute cost per request, cache hit rate, and latency percentiles, and you can tell a cache regression from a slow model in one query.
Steps 1 and 4 run on the local model and cost nothing. Steps 2, 3 and 5 need the API: prompt caching and the Batch API are features of the hosted service, and the local model has no equivalent you can bill. The model is claude-haiku-5-5; at $0.10 per million input tokens the 20 uncached calls on a 50,000-token prompt cost about $0.10, the cached run about $0.02, and the batch under a cent. Rerunning step 3 on claude-sonnet-5-5 shows a larger TTFT gap and costs about $2.40 for both runs.
1. Build the prefix and see prefill against decode locally.
mkdir -p labs/ai/latency && cd labs/ai/latency # from the root of your checkout
uv add anthropic "psycopg[binary]" # no-ops if labs/ai/pyproject.toml has them
ollama pull llama3.2:3b
cat ../../../docs/*.md ../../../src/content/lessons/*.mdx > corpus.txt
wc -c corpus.txtCreate local_split.py, which sends a 6,000-token slice to Ollama twice and prints the timing fields Ollama returns:
import json, urllib.request, pathlib
text = pathlib.Path("corpus.txt").read_text()[:24000] # about 6k tokens
def gen(prompt):
body = {"model": "llama3.2:3b", "prompt": prompt, "stream": False,
"options": {"num_ctx": 16384, "num_predict": 200}}
req = urllib.request.Request("http://localhost:11434/api/generate", json.dumps(body).encode(),
{"Content-Type": "application/json"})
return json.load(urllib.request.urlopen(req))
for run in (1, 2):
r = gen(text + "\n\nSummarise the text above in three sentences.")
pe, ev = r["prompt_eval_duration"] / 1e9, r["eval_duration"] / 1e9
print(f"run {run}: prefill {r['prompt_eval_count']} tok in {pe:.2f}s "
f"({r['prompt_eval_count']/max(pe,1e-9):.0f} tok/s) | decode {r['eval_count']} tok in {ev:.2f}s "
f"({r['eval_count']/ev:.0f} tok/s)")uv run local_split.pyprompt_eval_count drops to a handful of tokens and prefill time collapses, Ollama reused the KV state of the identical prefix from run 1. That is prompt caching on your own machine; the hosted version below does the same across requests and bills you less for it.2. Cut the prefix to 50,000 tokens. Create build_prefix.py:
import anthropic, pathlib
client = anthropic.Anthropic()
MODEL, TARGET = "claude-haiku-5-5", 50_000
text = pathlib.Path("corpus.txt").read_text()
def count(t):
return client.messages.count_tokens(model=MODEL, system=t,
messages=[{"role": "user", "content": "x"}]).input_tokens
sample = text[:200_000]
per_char = count(sample) / len(sample)
cut = text[: int(TARGET / per_char)]
print("tokens:", count(cut), "chars:", len(cut))
pathlib.Path("prefix.txt").write_text(cut)uv run build_prefix.pytokens: 49xxx or 50xxx. If the corpus is shorter than 50,000 tokens the script prints fewer; add ../../../src/content/chapters/*/*.mdx to the cat in step 1. Keep it under 100,000 tokens: above that Haiku 5.5 bills every token at the higher long-prompt rate.3. Twenty calls without caching, then twenty with a breakpoint. Create measure.py:
import pathlib, statistics, sys, time, anthropic
client = anthropic.Anthropic()
MODEL = sys.argv[2] if len(sys.argv) > 2 else "claude-haiku-5-5"
# $ per million tokens: input, 5-min cache write, cache read, output (Haiku 5.5, prompts <= 100k)
PRICE = {"claude-haiku-5-5": (0.10, 0.125, 0.01, 0.50), "claude-sonnet-5-5": (2.00, 2.50, 0.10, 10.00)}[MODEL]
# Haiku 5.5 accepts disabled thinking at low effort and has no server-side fallback. Sonnet 5.5
# rejects {"type": "disabled"} with a 400, so it thinks briefly at low effort and gets the fallback.
EXTRA = ({"thinking": {"type": "disabled"}} if MODEL.startswith("claude-haiku") else
{"betas": ["server-side-fallback-2026-07-01"], "fallbacks": "default"})
DOCS = pathlib.Path("prefix.txt").read_text()
QUESTIONS = [f"In one sentence: what does the documentation say about {t}?" for t in
["Predict", "the Lab component", "Reading items", "British spelling", "Decide options",
"course modules", "the observability stack", "Grafana", "Postgres", "pgbouncer",
"the shop schema", "Ollama", "cards", "the lint script", "minutes", "projects",
"load generator", "fault injection", "deploying", "simulations"]]
def call(question, cached):
docs = {"type": "text", "text": DOCS}
if cached:
docs["cache_control"] = {"type": "ephemeral"}
t0, ttft = time.perf_counter(), None
with client.beta.messages.stream(
model=MODEL, max_tokens=1000, output_config={"effort": "low"}, **EXTRA,
system=[{"type": "text", "text": "Answer from the documentation below. Be brief."}, docs],
messages=[{"role": "user", "content": question}],
) as stream:
for _ in stream.text_stream:
if ttft is None:
ttft = time.perf_counter() - t0
msg = stream.get_final_message()
u = msg.usage
w, r = u.cache_creation_input_tokens or 0, u.cache_read_input_tokens or 0
cost = (u.input_tokens * PRICE[0] + w * PRICE[1] + r * PRICE[2] + u.output_tokens * PRICE[3]) / 1e6
return ttft or time.perf_counter() - t0, cost, u.input_tokens, w, r
cached = sys.argv[1] == "cached"
rows = [call(q, cached) for q in QUESTIONS] # sequential: a cache entry is readable once written
for i, (t, c, inp, w, r) in enumerate(rows):
print(f"{i:2d} ttft {t:5.2f}s input {inp:6d} write {w:6d} read {r:6d} ${c:.5f}")
ttfts = sorted(r[0] for r in rows)
print(f"\n{'cached' if cached else 'uncached'}: p50 {statistics.median(ttfts):.2f}s "
f"p95 {statistics.quantiles(ttfts, n=20)[18]:.2f}s mean {statistics.mean(ttfts):.2f}s "
f"total ${sum(r[1] for r in rows):.4f}")uv run measure.py uncached
uv run measure.py cachedinput near 50,000 and write 0 read 0, total about $0.10. Cached: row 0 shows write near 50,000 (you paid 1.25x once), rows 1 to 19 show read near 50,000 and input of a few dozen tokens, total around $0.015. The cached p50 TTFT is lower than the uncached one because prefill of the 50,000 tokens is skipped; row 0 is as slow as an uncached call or slower. With 20 samples the p95 is close to the maximum; that is why production dashboards need hundreds of samples per window before a tail percentile means anything. Run uv run measure.py uncached claude-sonnet-5-5 and cached claude-sonnet-5-5 if you want the gap on a larger model (about $2.40 for the pair).4. Stream against non-stream, locally. Create perceived.py:
import json, time, urllib.request
def post(stream):
body = {"model": "llama3.2:3b", "stream": stream, "options": {"num_predict": 400},
"prompt": "Explain prompt caching to a new engineer in about 300 words."}
return urllib.request.urlopen(urllib.request.Request(
"http://localhost:11434/api/generate", json.dumps(body).encode(), {"Content-Type": "application/json"}))
t0 = time.perf_counter(); post(False).read()
print(f"non-stream: first word visible after {time.perf_counter()-t0:.2f}s (the whole answer)")
t0, first = time.perf_counter(), None
for line in post(True):
if first is None and json.loads(line).get("response", "").strip():
first = time.perf_counter() - t0
print(f"stream: first word after {first:.2f}s, done after {time.perf_counter()-t0:.2f}s")uv run perceived.py5. Submit 100 classification jobs as a batch. Create batch.py, which asks the model to put 100 shop products into one of the shop’s categories and compares cost and accuracy:
import os, sys, time, anthropic, psycopg
from anthropic.types.message_create_params import MessageCreateParamsNonStreaming
from anthropic.types.messages.batch_create_params import Request
client = anthropic.Anthropic()
MODEL = "claude-haiku-5-5"
with psycopg.connect(os.environ.get("SHOP_DSN", "postgres://atlas:atlas@localhost:5432/shop")) as db:
cats = [r[0] for r in db.execute("select distinct category from products order by 1")]
rows = db.execute("select id, name, category from products order by random() limit 100").fetchall()
instructions = "Categories: " + ", ".join(cats) + "\nReply with the one category that fits the product. Category name only."
reqs = [Request(custom_id=f"p-{pid}", params=MessageCreateParamsNonStreaming( # Haiku, and batches take no fallbacks
model=MODEL, max_tokens=256, thinking={"type": "disabled"}, output_config={"effort": "low"},
system=instructions, messages=[{"role": "user", "content": name}]))
for pid, name, _ in rows]
batch = client.messages.batches.create(requests=reqs)
t0 = time.time()
while (b := client.messages.batches.retrieve(batch.id)).processing_status != "ended":
print(f"{time.time()-t0:5.0f}s {b.processing_status} {b.request_counts.processing} processing"); time.sleep(10)
truth = {f"p-{pid}": cat for pid, _, cat in rows}
tin = tout = right = 0
for r in client.messages.batches.results(batch.id): # any order: key by custom_id
if r.result.type != "succeeded":
print(r.custom_id, r.result.type); continue
m = r.result.message
tin, tout = tin + m.usage.input_tokens, tout + m.usage.output_tokens
right += next(b.text for b in m.content if b.type == "text").strip() == truth[r.custom_id]
std = (tin * 0.10 + tout * 0.50) / 1e6
print(f"done in {time.time()-t0:.0f}s, accuracy {right}/100, tokens in {tin} out {tout}")
print(f"standard price ${std:.5f}, batch price ${std/2:.5f}")uv run batch.pyin_progress, then ended, usually within minutes for a batch this small (it can take longer under load). Accuracy is high but not 100: the loader builds names from category words, and the misses are worth reading. The batch price is exactly half the standard one, a fraction of a cent here and thousands of dollars at a million jobs a night. Note what you gave up: the synchronous loop would have finished in under a minute.measure.py, change the first system block to f"Answer from the documentation below. Be brief. Request time: {time.time()}" and rerun cached. Every row now shows write near 50,000 and read 0, and the total is higher than the uncached run, because you pay the 1.25x write premium twenty times and read nothing back. The timestamp sits before the breakpoint. Move it into the user message and the reads come back. This is the Why’s incident, reproduced for about thirteen cents.Template
# Latency and cost budget: <route or product>, <date>
Owner: <engineer or engineering manager>. Approver: <head of engineering>, with <finance lead>.
Decision needed: <what, from whom, by when>.
## 1. Target
- Route: <name>. Who waits: <user>.
- Target: p95 time to first token under <seconds>, measured as <how>.
- Assumed traffic: <requests a day, hours, gap between requests sharing a prefix>.
## 2. Before and after
| Measure | Before | After | Source (lab step, chapter figure or assumption) |
| p50 and p95 TTFT | | | |
| Input tokens billed at full price per request | | | |
| Cost per request | | | |
| Cost per day | | | |
## 3. What is cached, and why
| Prefix part | Size in tokens | Why it is stable | Breakpoint | TTL, and why |
## 4. What is batched, and why
| Job | Why nobody waits | Volume | Price standard vs batch |
## 5. What could break the cache
| Cause | How you would see it (cache_read_input_tokens) | Guard |
## 6. Rollback
Watch <metric>. If <threshold>, <action>. Switched off by <role>.
## 7. How this could be wrong
<one way, and what would show it>
## 8. Out of scope and sign-off
Out of scope: <what this budget does not cover>.
Prepared <name, date>. Approved <name, date>. WORKED EXAMPLE
At a real company the engineer who owns the support assistant writes this budget, and the head of engineering approves it with finance. This one uses the chapter’s own support bot: 60,000-token handbook, claude-sonnet-5-5.
Header. Owner: the engineer who owns the support assistant. Approver: the head of engineering, with the finance lead. Dated 20 November 2026. Decision needed: whether to ship the prompt reordering this week.
Target. Route: the support assistant, a customer waiting. Target: p95 time to first token under 2 seconds (assumed; the lab prints no seconds, so the real figure comes from your own measure.py run). Assumed: 40,000 conversations a day, one request each for this sum, spread over 09:00 to 18:00, about one a second.
Before and after.
| Measure | Before | After |
|---|---|---|
| Prefix cost per request | $0.12 (60,000 uncached tokens) | $0.006 (cached read) |
| Prefix cost per day | $4,800 (derived: 40,000 x $0.12) | $240 (derived: 40,000 x $0.006) |
| Streaming, 500-token answer | about 7 s to first word | under 1 s |
Assumed worst case for writes: a miss every 5 minutes round the clock, 288 writes at $0.15 each, $43.20 a day.
Cached. The handbook, in one block with one breakpoint at its end; stable because the customer’s name and today’s date move into the user message. Default 5-minute TTL: daytime gaps are seconds.
Batched. Nightly ticket summaries: nobody waits. The lab’s batch of 100 jobs cost exactly half the standard price, under a cent.
Could break the cache. A timestamp or name before the breakpoint (write every call, no reads, as the lab’s break step shows); reordered tools; a new image. Each shows as cache_read_input_tokens at zero.
Could be wrong. The 40,000-a-day figure is an assumption. A real run showing reads below 90% of requests would show it.
Decision. Approve the reordering this week. Rollback: if the read share falls under 90% for a day, the owning engineer switches the breakpoint off.
Out of scope. Replacing the handbook with retrieval, and model choice.
Now you
You are the engineering manager on Crustwell’s finance systems team. Crustwell sells instant noodles, a malt drink and biscuits, and its distributors prepay before the warehouse releases stock. Your distributor-support assistant answers distributors’ questions from a long trade-terms handbook sent with every request on claude-haiku-5-5; take the handbook as the lab’s 50,000-token prefix. A nightly job reads the day’s distributor order emails and sorts them by product line; the accounts-receivable lead reads the result in the morning, and nobody waits for it. Last month an engineer put the distributor’s name on the first line of the system prompt, and the bill rose. Use the lab: measure.py uncached and cached give the before and after cost and TTFT, batch.py gives the half-price figure, and the break step shows what a name before the breakpoint does. State the request volume, working hours and email count as assumptions, because the lab prints none. Write the budget that the head of finance and the accounts-receivable lead read to decide whether to ship the reordering and the nightly batch.
Self-check
Your support bot sends a 60,000-token handbook in the system prompt on claude-sonnet-5-5. Traffic runs 09:00 to 18:00 with a request every few seconds, and drops to a few per hour overnight. The system prompt begins with the customer's name and today's date, and the cache hit rate is zero. Finance wants the bill cut this month. What do you do first?
- DOC Prompt caching
The reference for everything in the caching sections: breakpoints, minimum lengths per model, TTLs, pricing multipliers and the invalidation table. Read the invalidation table and the concurrency note twice; skim the per-language examples.
- DOC Batch processing
Limits, lifecycle, result types and the interaction with caching. Read the limitations list before designing a nightly job; the per-language code is interchangeable.
- DOC Optimizing for cost and intelligence
Measured numbers for caching, batching, effort and model choice on real agent workloads, including cost per solved task. The best antidote to optimising per-token price instead of per-task cost.
- DOC Pricing
The current table for base input, cache writes and reads, output and batch rates per model. Check it before quoting any figure from this chapter; prices change.
- DOC Streaming messages
The event sequence and delta types you consume when streaming, and the SDK helpers that assemble the final message. Read the event types section; skip the languages you do not use.
- PAPER The Tail at Scale Jeffrey Dean and Luiz André Barroso, 2013
Why rare slow responses dominate the latency of systems that fan out, and the techniques (hedged and tied requests) that tame them. Short, and the reason you report p99. Read: the whole paper; it is eight pages.
- TALK How NOT to Measure Latency Gil Tene, 2016
Coordinated omission, why averages lie and how load generators hide the tail. Watch the first half before you trust any latency benchmark, including the one in this lab.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.