The first time I tried to speed up Claude API, I went straight for a smaller model: Opus to Sonnet, then Sonnet to Haiku. It did not go well. Responses came a little sooner, but answer quality started to wobble, and I spent more time staring at the screen second-guessing output.
Only after I added measurements did I see that a good share of the wait lived outside the model. This post walks through four infrastructure levers I try before any model downgrade, with the code and the measurements that go with them.
Why "make the model faster" misses part of the budget
A Claude API request spends time across roughly four segments:
- Client to the Anthropic gateway (network in)
- Auth and queueing inside the gateway
- Model inference
- Network on the way back
Most tuning advice fixates on inference. But the farther your servers are from the region serving the model, the longer the two network legs get, and the longer your input, the more time goes to processing it before the first token. That is why a faster model sometimes barely changes what users feel.
Real numbers vary a lot with region, time of day and input length, so I won't quote milliseconds here. I'd rather show how to measure each segment yourself.
1. Region choice: physical distance still matters
Claude is reachable through Anthropic's direct API, AWS Bedrock and Google Vertex AI, and each is offered in different regions. Picking one closer to your servers tends to shrink Time To First Byte (TTFB). If your compute runs in Japan, Bedrock in Tokyo is a natural candidate.
# bedrock_client.py
# Calls Claude through Bedrock in ap-northeast-1 (Tokyo).
# Typically yields the lowest TTFB when your compute is in Japan.
import boto3
import json
bedrock = boto3.client(
"bedrock-runtime",
region_name="ap-northeast-1", # pick the region closest to your compute
)
def ask_claude(prompt: str) -> str:
body = json.dumps({
"anthropic_version": "bedrock-2023-05-31",
"max_tokens": 1024,
"messages": [{"role": "user", "content": prompt}],
})
resp = bedrock.invoke_model(
modelId="anthropic.claude-sonnet-4-6-v1:0",
body=body,
)
payload = json.loads(resp["body"].read())
return payload["content"][0]["text"]
# To check: call the same prompt 20 times per region and compare median TTFB.
# Swap modelId for one that is enabled in your own account.
# Newer models may require a cross-region inference profile ID insteadMoving regions does not speed up everything, though. Check three things before you migrate:
- Is the model you want offered in that region?
- Are pricing and quotas the same as on the direct API?
- Are the features you rely on (tool use, caching, newer models) available there at the same time?
Bedrock and the direct API can differ in when models and features land, so confirm against the AWS documentation. Then compare median TTFB over about 20 calls per region before you decide.
2. Connection pooling to skip repeated handshakes
If every request opens a fresh TCP connection and TLS handshake, that cost is added each time. Node.js fetch and Python requests in their default setups often fail to reuse connections.
The Anthropic SDK reuses connections internally. If you wrote a thin fetch-based client yourself, setting keep-alive explicitly helps.
// claude-client.ts
// Reuses a pooled connection via undici's Agent.
// Most impactful for batch jobs that fire many sequential requests.
import Anthropic from "@anthropic-ai/sdk";
import { Agent } from "undici";
const dispatcher = new Agent({
keepAliveTimeout: 60_000, // hold each connection for up to 60s
keepAliveMaxTimeout: 300_000, // cap at 5 minutes
connections: 32, // pool up to 32 concurrent sockets
pipelining: 1,
});
const client = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY!,
fetch: (url, init) =>
// @ts-expect-error: inject undici dispatcher into fetch
fetch(url, { ...init, dispatcher }),
});
export async function chat(prompt: string) {
return client.messages.create({
model: "claude-sonnet-4-6",
max_tokens: 1024,
messages: [{ role: "user", content: prompt }],
});
}
// To check: record average latency over 100 sequential requests,
// before and after adding the dispatcher.A single call will not show much difference. It pays off in batch jobs and agent runs, where requests follow each other closely and the savings add up.
3. Prompt caching to cut repeated input processing
If you ship a long system prompt or a big reference document on every call, prompt caching is the easiest lever to reach for. On a cache hit, re-processing of the shared prefix is skipped, so both time to first token and input-token cost go down.
The trick is to put what never changes first and what changes last, because the cache only applies to an identical prefix.
- Top: system instructions (cached)
- Middle: reference documents or RAG context (cached)
- Bottom: the per-user question (not cached)
// cached_messages.ts
// Two cache breakpoints — system instructions and a long reference block.
// Subsequent calls within the cache TTL skip most input processing.
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY! });
export async function answer(question: string, longContext: string) {
return client.messages.create({
model: "claude-sonnet-4-6",
max_tokens: 1024,
system: [
{
type: "text",
text: "You are an assistant fluent in our internal docs. Always cite sources.",
cache_control: { type: "ephemeral" }, // cache up to here
},
{
type: "text",
text: longContext, // tens of thousands of tokens
cache_control: { type: "ephemeral" }, // and up to here
},
],
messages: [{ role: "user", content: question }],
});
}
// To check: on warm calls, response.usage.cache_read_input_tokens should
// account for most of the input.Three conditions are worth knowing:
- The cached prefix has a per-model minimum token count. A prompt that is too short will not be cached even with
cache_control. - The default lifetime is 5 minutes and is refreshed on each hit. For services with sparse traffic, entries expire before they help.
- Whether it worked is visible in
usage: look atcache_read_input_tokensandcache_creation_input_tokens.
Minimums and lifetime options can change, so check the official Prompt caching documentation for current values before you implement.
4. Streaming to show the first character sooner
What users perceive as speed depends more on when the first character appears than on when the full answer arrives. For chat UIs and writing assistants, where output runs long, I recommend stream.
// streaming.ts
// Yields tokens to the client as Claude produces them.
// Drastically improves perceived latency without changing the model.
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY! });
export async function* streamAnswer(prompt: string) {
const stream = await client.messages.stream({
model: "claude-sonnet-4-6",
max_tokens: 1024,
messages: [{ role: "user", content: prompt }],
});
for await (const event of stream) {
if (event.type === "content_block_delta" && event.delta.type === "text_delta") {
yield event.delta.text;
}
}
}
// To check: log time-to-first text_delta and time-to-full-response separately.Streaming makes disconnects, reconnects and timeouts a little more complicated. Before going live, cut the connection on purpose and watch what happens. I've collected the details in diagnosing Claude API streaming cutoffs.
Optimization without measurement is just a feeling
All four levers can help, but without measurement you end up with "it feels faster, I think." I always record three values:
- TTFB (time until the first token)
- Total completion time (time until the last token)
- The share of input tokens that hit the cache
You can emit these as span attributes, as covered in the Claude API OpenTelemetry observability guide. With before-and-after records for each lever, you can tell which ones did nothing.
Measure first: a small script for the median of 20 runs
I keep saying to measure before deciding, so here is the rough script I start from. It streams the same prompt 20 times and records when the first text arrives and when the last text arrives.
import statistics
import time
import anthropic
client = anthropic.Anthropic()
MODEL = "claude-sonnet-4-6" # swap in the model ID you want to measure
def measure(prompt: str) -> tuple[float, float]:
start = time.perf_counter()
first = None
with client.messages.stream(
model=MODEL,
max_tokens=512,
messages=[{"role": "user", "content": prompt}],
) as stream:
for _ in stream.text_stream:
if first is None:
first = time.perf_counter() - start
total = time.perf_counter() - start
return first or total, total
samples = [measure("Explain the benefit of HTTP keep-alive in under 100 words.") for _ in range(20)]
ttfb = [s[0] for s in samples]
total = [s[1] for s in samples]
print(f"TTFB median={statistics.median(ttfb):.2f}s max={max(ttfb):.2f}s")
print(f"TOTAL median={statistics.median(total):.2f}s max={max(total):.2f}s")I look at the median rather than the mean because a single outlier is enough to move the mean. I run it before and after each lever, in the same time window. Numbers differ by environment, so I am not printing any here.
Early on I skipped this and judged by the "it feels faster" right after a change. I only noticed when I re-measured at a different hour. A before/after comparison that was not taken in the same window with the same prompt does not count as evidence. That is the line I keep now.
A first step you can take today
Adding all four at once isn't realistic. This is the order I usually follow.
First, measure current TTFB and total time. Next, put a cache breakpoint on the system prompt. Once the effect shows, move on to region, connection pooling and streaming. Keeping that order tells you which lever actually worked and saves a lot of backtracking.
Change the model last. I still hold to that line. Swapping models moves answer quality too, so I take the speed that infrastructure can give first. A good start is measuring TTFB for one request you already send.