Performance and Latency
Independent educational resource, not an official Anthropic course. Facts about the API, prices and limits were checked against Anthropic's documentation on 15 November 2026 and the code was run against a local mock of the API, not the live service. Check the linked official pages before relying on a number, and test with your own key.
Users don't experience "latency" as one number. They experience a blank screen for three seconds, then text, or a spinner for twenty seconds, then everything at once. The same total time feels completely different. This lesson separates the things you can change: which model, how much you send, how much you ask for, whether you stream, what you can reuse and what you can do in parallel. Everything here is measured or tested, and where the documentation is the source, we say so.
What you'll learn
- Time to first token versus total time, and why streaming matters.
- The biggest levers: model choice, prompt length, output length.
- Prompt caching and response caching, and what each can and can't do.
- Running calls in parallel without breaking your rate limits.
- When to batch instead.
Before you start
Measure first
Anthropic's latency guidance starts with a warning that's easy to ignore: first engineer a prompt that works well without constraints, then optimise for speed. Cutting latency too early can stop you discovering what top quality looks like. When you do measure, two numbers matter:
- Time to first token (TTFT): how long until the first piece of the reply arrives. This is what makes an interface feel responsive, if you stream.
- Total time: until the whole reply is done.
The helper below streams a request and reports both. We ran it against a local mock server that sends two chunks 50 milliseconds apart, and the test confirms the first-token time is smaller than the total, which is the whole point of streaming. With the real API the numbers will be different, so measure on your own traffic:
"""Speed: cache what repeats, stream what a person waits for, bound what runs in parallel, batch what can wait."""
import hashlib
import json
import re
import threading
import time
from collections import OrderedDict
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, field
from gateway import Gateway, Reply
class ResponseCache:
"""Exact-match cache for answers that don't depend on who is asking. Keys include everything that changes the answer."""
def __init__(self, max_items: int = 500, ttl: float = 600.0, clock=time.monotonic):
self.max_items, self.ttl, self.clock = max_items, ttl, clock
self._data: OrderedDict[str, tuple[float, Reply]] = OrderedDict()
self._lock = threading.Lock()
self.hits = self.misses = 0
@staticmethod
def key(model: str, system, prompt: str, max_tokens: int) -> str:
blob = json.dumps([model, system, prompt, max_tokens], sort_keys=True, ensure_ascii=False)
return hashlib.sha256(blob.encode()).hexdigest()
def get(self, key: str) -> Reply | None:
with self._lock:
item = self._data.get(key)
if item and self.clock() - item[0] <= self.ttl:
self._data.move_to_end(key)
self.hits += 1
return item[1]
if item:
del self._data[key]
self.misses += 1
return None
def put(self, key: str, reply: Reply) -> None:
with self._lock:
self._data[key] = (self.clock(), reply)
self._data.move_to_end(key)
while len(self._data) > self.max_items:
self._data.popitem(last=False)
def cached_ask(gateway: Gateway, cache: ResponseCache, prompt: str, *, system=None, personal: bool = False, max_tokens: int | None = None) -> tuple[Reply, bool]:
"""Returns (reply, from_cache). Anything about a specific person must pass personal=True and is never cached."""
mt = max_tokens or gateway.max_tokens
if personal:
return gateway.ask(prompt, system=system, max_tokens=mt), False
k = cache.key(gateway.model, system, prompt, mt)
if (hit := cache.get(k)) is not None:
return hit, True
reply = gateway.ask(prompt, system=system, max_tokens=mt)
cache.put(k, reply)
return reply, False
def cacheable_system(text: str, ttl: str | None = None) -> list[dict]:
"""A system prompt with an explicit prompt-cache breakpoint. Matching is exact, so keep this text identical between
requests, and note prompts shorter than the model's minimum are simply not cached (the API returns no error)."""
block = {"type": "text", "text": text, "cache_control": {"type": "ephemeral", **({"ttl": ttl} if ttl else {})}}
return [block]
def stream_timing(client, *, model: str, prompt: str, max_tokens: int = 300, clock=time.monotonic) -> dict:
"""Measure time to first token and total time while streaming. Perceived speed is mostly the first number."""
start = clock()
first = None
parts = []
with client.messages.stream(model=model, max_tokens=max_tokens, messages=[{"role": "user", "content": prompt}]) as stream:
for piece in stream.text_stream:
if first is None:
first = clock() - start
parts.append(piece)
final = stream.get_final_message()
return {"text": "".join(parts), "ttft_s": first, "total_s": clock() - start, "stop_reason": final.stop_reason}
class RateLimiter:
"""Token bucket: at most `per_minute` calls, smoothly. Keeps you under your own limits instead of discovering them via 429s."""
def __init__(self, per_minute: int, clock=time.monotonic, sleep=time.sleep):
self.rate, self.capacity = per_minute / 60.0, max(1, per_minute // 6)
self.tokens, self.clock, self.sleep = float(self.capacity), clock, sleep
self.updated = clock()
self._lock = threading.Lock()
def acquire(self) -> None:
while True:
with self._lock:
now = self.clock()
self.tokens = min(self.capacity, self.tokens + (now - self.updated) * self.rate)
self.updated = now
if self.tokens >= 1:
self.tokens -= 1
return
wait = (1 - self.tokens) / self.rate
self.sleep(wait)
def fan_out(items: list, fn, *, max_concurrency: int = 4, limiter: RateLimiter | None = None) -> list:
"""Run fn over items in parallel, in order, with a cap on concurrency. Exceptions come back as values so one bad
item doesn't lose the rest."""
def one(item):
if limiter:
limiter.acquire()
try:
return fn(item)
except Exception as e: # noqa: BLE001
return e
with ThreadPoolExecutor(max_workers=max_concurrency) as pool:
return list(pool.map(one, items))
CUSTOM_ID = re.compile(r"^[a-zA-Z0-9_-]{1,64}$")
def batch_requests(items: dict[str, str], model: str, max_tokens: int = 300, system=None) -> list[dict]:
"""Build Message Batches requests. Each custom_id must match the documented pattern; results can come back in any
order, so you match on custom_id."""
out = []
for cid, prompt in items.items():
if not CUSTOM_ID.match(cid):
raise ValueError(f"custom_id {cid!r} must be 1-64 letters, digits, hyphens or underscores.")
params = {"model": model, "max_tokens": max_tokens, "messages": [{"role": "user", "content": prompt}]}
if system:
params["system"] = system
out.append({"custom_id": cid, "params": params})
return out
def collect_batch(results) -> dict:
"""Sort batch results into answers and problems. Only 'succeeded' has a message; the others are not billed."""
done, problems = {}, {}
for r in results:
kind = r.result.type
if kind == "succeeded":
done[r.custom_id] = "".join(b.text for b in r.result.message.content if b.type == "text")
elif kind == "errored":
problems[r.custom_id] = "errored"
else:
problems[r.custom_id] = kind # canceled or expired
return {"answers": done, "problems": problems}
@dataclass
class Deadline:
"""One time budget for a whole request. Pass it down so each step knows how long it may take."""
seconds: float
clock: callable = time.monotonic
start: float = field(default=0.0)
def __post_init__(self):
self.start = self.clock()
def remaining(self) -> float:
return max(0.0, self.seconds - (self.clock() - self.start))
def expired(self) -> bool:
return self.remaining() <= 0
The levers, in order of effect
1. Choose the right model
The most direct lever. The documentation points to Claude Haiku 5.5 as the fastest option for speed-critical work and says its main control for speed and cost is the effort setting, with low the cheapest and fastest level. Their example sets output_config={"effort": "low"} and leaves room in max_tokens for thinking. Check the models page for the current options, since the lineup changes. Then use your evaluation set (lesson 8.6) to confirm that the faster model is good enough for the job. Use a small model for classification and screening, and keep the larger one for writing.
2. Send less, ask for less
Fewer input tokens and fewer output tokens both mean faster replies. The documentation suggests being clear but concise in prompts, asking directly for shorter responses and using max_tokens as a hard limit. It notes that asking for an exact word count doesn't work well because models count tokens, so ask for a number of sentences or paragraphs. It also warns that max_tokens cuts a reply off mid-word, so it's a blunt tool best for short, answer-first outputs. Our service sets max_tokens to 800 and treats a cut-off reply as "needs a person" instead of sending half an answer.
3. Stream what a person is waiting for
Streaming doesn't make the model faster, but the user sees text almost at once. Use it for anything a person reads as it arrives. Don't stream what your code must validate whole first, like our JSON drafts, since you can't validate half a JSON object. A reasonable pattern is to validate, then reveal.
Prompt caching
If every request starts with the same large block (a long system prompt, tool definitions, reference documents), the API can cache that prefix. From the documentation:
- You mark a cache breakpoint with
cache_control, either on individual content blocks or, on supported platforms, as one top-level field that moves forward automatically. You can set up to four breakpoints.
- The default lifetime is five minutes, refreshed each time the cached content is used. A one-hour option exists (
"ttl": "1h") at a higher write price.
- Prompts shorter than the model's minimum cacheable length are simply processed without caching and no error is returned. The minimums vary by model, from 512 to 4,096 tokens in the version of the page we read.
- Matching is exact. The order is tools, then system, then messages, and a change at one level invalidates that level and everything after it. Changing a tool definition invalidates everything.
- Check the response's usage:
cache_read_input_tokens and cache_creation_input_tokens. If both are zero, nothing was cached.
Our cacheable_system helper builds a system block with the breakpoint. Practical rules: put stable text first and changing text last, never put timestamps or request IDs in the cached part, and confirm with the usage fields that you're getting hits. Caching also cuts cost (lesson 8.10), and cached input tokens don't count toward your input-tokens-per-minute rate limit, which raises your effective throughput.
Response caching
A separate idea: if you've already answered this exact question, don't ask again. ResponseCache is an exact-match cache with a time limit and a size limit, keyed on the model, system prompt, prompt and max_tokens together, so any change gives a different key. Two firm rules:
- Never cache anything personal.
cached_ask has a personal flag that bypasses the cache entirely. An answer built from one customer's order must never be served to another.
- Short lifetimes for anything that changes. A returns-policy answer can live for hours. An order status can't.
We tested: the second identical question is a hit and makes no API call; personal questions never hit; the oldest entries are evicted at the size limit; entries expire; and five different inputs make five different keys.
Parallel work
If a task has independent parts, such as classifying fifty messages, run them concurrently. fan_out runs calls in a thread pool with a cap, returns results in order and returns exceptions as values so one failure doesn't lose the rest. Pair it with a RateLimiter (a token bucket) so you stay under your own requests-per-minute rather than discovering your limit through 429s. The API itself uses a token bucket, so capacity replenishes continuously, and the documentation advises ramping up gradually: a sharp jump in usage can trigger a ramp-limit 429 even while you're under your limits, so start scheduled jobs at a low rate and spread requests evenly.
When it can wait: batches
For work that doesn't need an immediate answer, such as nightly summaries or evaluation runs, the Message Batches API processes requests asynchronously at 50 percent of standard prices. From the documentation: a batch holds up to 100,000 requests or 256 MB, most finish within an hour, results are available when everything has finished or after 24 hours (batches expire if not done in 24 hours), and results stay downloadable for 29 days. Each request has a custom_id (1 to 64 letters, digits, hyphens or underscores) and results may not come back in request order, so match on that ID. Result types are succeeded, errored, canceled and expired; only the first is a message, and the others aren't billed. Our batch_requests and collect_batch helpers validate IDs and sort results. We tested them with constructed result objects, not a live batch.
Deadlines
A request that must answer in ten seconds should know it. Deadline is a tiny object you create once and pass down. Each step asks remaining() and decides whether to try the model, skip an optional screen or return a fallback. It's simple, and it stops a chain of reasonable timeouts adding up to an unreasonable wait.
Real-world use case (illustrative scenario)
This scenario is an invented example to show how the ideas fit together. It is not a case study and its details are not measured results.
A shop's chat feature feels sluggish: median replies take six seconds. The team measures first and finds the screening call takes 1.2 seconds, drafting takes 4 and everything else is negligible. They move screening to a small model with a 60-token limit, stream the visible reply after validation, and cache the shop's policies in the system block. Then they measure again before declaring success. The point isn't these particular numbers; it's the order: measure, change one thing, measure again.
Mistakes to avoid
- Optimising before you have a working, evaluated prompt.
- Putting changing text at the start of a cached prefix, so it never hits.
- Caching answers that depend on who is asking.
- Unlimited parallelism that trips your rate limits.
- Using batches for anything a person is waiting on.
Security notes
A shared cache is a way for one user's data to leak to another. Keep personal data out of cached prefixes and out of the response cache. Prompt caches are isolated per organisation (and per workspace on the first-party API), per the documentation, but your own in-process cache is entirely your responsibility.
Cost and speed
Speed and cost move together here: shorter prompts, shorter outputs, smaller models, cached prefixes and batches all reduce both. The main exception is parallelism, which saves time but not money.
Key takeaways
- Measure TTFT and total time. Streaming improves the first, not the second.
- Model choice, prompt length and output length are the big levers; use evals to check quality.
- Prompt caching needs a stable, long enough, exactly matching prefix; verify with the usage fields.
- Cache only non-personal answers, with sensible lifetimes.
- Rate-limit your own parallelism and ramp up gradually. Use batches for work that can wait.
Lesson recap: measure first, pull the big levers, then cache and scale carefully.
Quick quiz
- What does streaming improve, and what doesn't it improve?
- How do you know prompt caching worked?
- Why should changing text go at the end of a cached prompt?
- Why must personal answers never go in a shared cache?
- Why match batch results on
custom_id?
Answers and explanations
- It improves perceived speed by showing the first tokens sooner (time to first token). It doesn't make the total generation faster.
- The usage shows non-zero
cache_read_input_tokens (or cache_creation_input_tokens on the first write). If both are zero, nothing was cached.
- Matching is exact up to the breakpoint, so anything that changes earlier in the prompt invalidates the cache from that point on.
- Another user could be served the first user's answer, which is a data leak.
- Batch results may come back in any order, so the ID is the only reliable way to match each result to its request.
Official references and further reading
Related tutorials