◉CLAUDE LABJP
●CC 2.1.332 — No new Claude Code release over the weekend. 2.1.332 (11/25) is still current●ANALYTICS — A fix to search counts in the Enterprise Analytics API may raise numbers from 11/17 onward●SONNET 4.5 — Today, 11/30, is Sonnet 4.5's last day on the Claude API. Move to claude-sonnet-5-5●USAGE — Some users report weekly usage jumping right after upgrading to a higher plan●NEW — New: Does what a Project remembers carry over into your everyday chats?●BILLING — More readers are looking for what to check when a payment won't go through●CC 2.1.332 — No new Claude Code release over the weekend. 2.1.332 (11/25) is still current●ANALYTICS — A fix to search counts in the Enterprise Analytics API may raise numbers from 11/17 onward●SONNET 4.5 — Today, 11/30, is Sonnet 4.5's last day on the Claude API. Move to claude-sonnet-5-5●USAGE — Some users report weekly usage jumping right after upgrading to a higher plan●NEW — New: Does what a Project remembers carry over into your everyday chats?●BILLING — More readers are looking for what to check when a payment won't go through
Articles/API & SDK
⬡ API & SDK/2026-04-28Intermediate

Four Infrastructure Levers That Cut Claude API Latency Before You Touch the Model

Before you downgrade Sonnet to Haiku to chase faster responses, the network and request shape around your Claude API calls usually has more headroom. Here are four infrastructure levers — region selection, connection pooling, prompt caching, and streaming — with code and measurement notes.

claude-api85latencyperformance4infrastructure4production111

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 instead

Moving 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 at cache_read_input_tokens and cache_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.

Share

Thank You for Reading

Claude Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.

  • ✦Copy-paste ready implementation code
  • ✦New advanced guides published daily
  • ✦$5/mo or $10 for lifetime access
View Membership →

If you found this article helpful, a small tip ($1.50) would mean a lot to us. Your support helps keep this site ad-free and covers server and hosting costs.

Related Articles

⬡ API & SDK2026-04-23
Running Claude API Parallel Tool Use in Production — Controlling Concurrency, Designing for Partial Failure, and Cutting Latency
Claude API's parallel tool use can halve perceived latency, but partial failures and duplicate writes arrive just as fast. Concurrency control with asyncio.gather and a Semaphore, three partial-failure policies, idempotency, observability, and a way to measure your real parallel degree.
⬡ API & SDK2026-05-26
Stabilizing Claude API Structured Responses in Production — Notes on tool_use, JSON Schema, and Layered Validation
Getting Claude to return JSON takes a few lines. Keeping that JSON usable in production is a different problem. Here is the layered design I landed on after running a wallpaper classification pipeline through Claude API, built around tool_use, JSON Schema, and domain validation.
⬡ API & SDK2026-05-22
Why tool_result could not be submitted Keeps Coming Back, and How to Build a Recovery Handler That Actually Holds
Run a Claude agent long enough and one day it starts: 'tool_result could not be submitted', back to back, and retries change nothing. The error message hides four completely different root causes. Here is what I learned debugging it on the always-on agent jobs I run as an indie developer, with the TypeScript recovery handler I now ship in production.