#Latency: time to first token and throughput
AddedFor a model call there are two latencies that matter, and they have different causes. Time to first token (TTFT) is how long until the first output token arrives. It's made of network time, queueing at the provider, and prefill: the model reading your entire prompt before it can write anything, which grows with the number of uncached input tokens (and, with thinking on, the reasoning the model does before its first visible word). Generation time is the output length divided by the output speed (tokens per second). Total latency is roughly TTFT + output tokens ÷ output speed.
The mental model: a reader who must finish the brief before speaking, then talks at a steady pace. A longer brief delays the first word; a longer answer delays the last. Streaming doesn't make either faster; it lets the user hear the first word as soon as it's spoken. So the levers sort into: make the brief shorter or pre-read (fewer input tokens, prompt caching), make the answer shorter (output is usually the biggest term), talk faster (a smaller model, or Anthropic's fast mode on Opus 5.5, which its docs describe as up to 2.5× higher output tokens per second at premium prices), think less (lower effort), and do independent calls in parallel instead of one after another.
// A latency model. Every number below is an ASSUMPTION for illustration: measure your own (TTFT and output speed
// vary by model, load, prompt length and effort).
const assume = {
networkMs: 60,
queueMs: 150,
prefillMsPer1kTokens: 40, // uncached input tokens the model must read before the first output token
cachedPrefillMsPer1kTokens: 4, // cached prefixes are mostly skipped
thinkingMs: 0,
outputTokensPerSec: 70,
};
function latency({ inputTokens, cachedTokens = 0, outputTokens, thinkingMs = assume.thinkingMs, speedup = 1 }) {
const ttft = assume.networkMs + assume.queueMs + ((inputTokens - cachedTokens) / 1000) * assume.prefillMsPer1kTokens +
(cachedTokens / 1000) * assume.cachedPrefillMsPer1kTokens + thinkingMs;
const generation = (outputTokens / (assume.outputTokensPerSec * speedup)) * 1000;
return { ttft: Math.round(ttft), total: Math.round(ttft + generation) };
}
const show = (label, r) => console.log(`${label.padEnd(44)} TTFT ${String(r.ttft).padStart(5)} ms total ${String(r.total).padStart(6)} ms`);
const base = { inputTokens: 12000, outputTokens: 600 };
show("baseline: 12K prompt, 600-token answer", latency(base));
show("prompt caching (10K of 12K cached)", latency({ ...base, cachedTokens: 10000 }));
show("ask for 200 tokens instead of 600", latency({ ...base, outputTokens: 200 }));
show("2.5x output speed (fast mode upper bound)", latency({ ...base, speedup: 2.5 }));
show("higher effort: +4 s of thinking", latency({ ...base, thinkingMs: 4000 }));
// Three independent calls (e.g. classify, extract, summarise the same ticket): sequential vs parallel.
const each = latency({ inputTokens: 2000, outputTokens: 150 }).total;
console.log(`three independent calls: sequential ${3 * each} ms, parallel ${each} ms (plus a little contention)`);baseline: 12K prompt, 600-token answer TTFT 690 ms total 9261 ms
prompt caching (10K of 12K cached) TTFT 330 ms total 8901 ms
ask for 200 tokens instead of 600 TTFT 690 ms total 3547 ms
2.5x output speed (fast mode upper bound) TTFT 690 ms total 4119 ms
higher effort: +4 s of thinking TTFT 4690 ms total 13261 ms
three independent calls: sequential 7299 ms, parallel 2433 ms (plus a little contention)assumelists every number the model relies on, and the comment says they're assumptions. That's the honest way to reason about latency in a design discussion: state the inputs, then measure the real ones for your model and prompts (theusageand timestamps you log give you both).- The baseline (12,000 input tokens, 600 output) spends most of its time generating: 600 tokens at 70 per second is over 8 seconds, against about 0.7 s of TTFT. That's typical: output length dominates total latency.
- Prompt caching cuts TTFT (the cached 10,000 tokens are mostly skipped), so the first word appears sooner, but the total barely moves because generation dominates. Caching is a TTFT and cost lever more than a total-latency lever.
- Asking for 200 tokens instead of 600 cuts the total from about 9.3 s to 3.5 s. Shorter answers (a tighter format, structured output, no preamble) are usually the biggest latency win, and the biggest cost win too.
- A 2.5× faster output speed shrinks only the generation term. Thinking adds straight to TTFT: 4 seconds of reasoning before the first visible token is 4 seconds of a blank screen unless the UI shows that the model is working.
- Three independent calls done one after another cost three full latencies; with
Promise.allthey cost about one. If steps don't depend on each other, never chain them.
Streaming is the perceived-latency fix. With streaming, the user waits TTFT and then reads along; without it, they wait for the total. For chat, stream always. For structured output that your code needs whole (a JSON object to render), stream anyway to avoid timeouts but show progress, or split the work so something useful arrives early. Also watch tail latency: p95 and p99 matter more than the average, because a long-output or retried request is what users remember. Log TTFT and total per request (OpenTelemetry's GenAI conventions have a gen_ai.response.time_to_first_chunk attribute for this) and chart percentiles per feature.
Promise.all over SDK calls really does send them concurrently. This example counts how many requests are in flight at once inside the scripted transport.
import Anthropic from "@anthropic-ai/sdk";
// Scripted replies (see "How these examples run")
let inFlight = 0, maxInFlight = 0;
async function fetch(url, init) {
inFlight++; maxInFlight = Math.max(maxInFlight, inFlight);
const task = JSON.parse(init.body).system;
await new Promise((r) => setTimeout(r, 30)); // every scripted reply takes 30 ms
inFlight--;
const text = { classify: "billing", extract: '{"order":"A-1042"}', summarise: "Customer was charged twice for A-1042." }[task];
return Response.json({ id: `msg_01Par${task}`, type: "message", role: "assistant", model: "claude-haiku-5-5", content: [{ type: "text", text, citations: null }],
stop_reason: "end_turn", stop_sequence: null, stop_details: null, container: null, diagnostics: null,
usage: { input_tokens: 80, output_tokens: 12, cache_creation_input_tokens: 0, cache_read_input_tokens: 0, cache_creation: null, output_tokens_details: { thinking_tokens: 0 }, server_tool_use: null, inference_geo: "global", service_tier: "standard", speed: "standard" } });
}
const client = new Anthropic({ apiKey: "sk-ant-test", fetch });
// End of scripted replies
const ticket = "I was charged twice for order A-1042.";
const run = (system) => client.messages.create({ model: "claude-haiku-5-5", max_tokens: 200, system, messages: [{ role: "user", content: ticket }] })
.then((r) => r.content[0].text);
let t = performance.now();
for (const task of ["classify", "extract", "summarise"]) await run(task);
const sequentialMs = performance.now() - t;
console.log(`sequential: max in flight ${maxInFlight}`);
maxInFlight = 0; t = performance.now();
const [category, fields, summary] = await Promise.all(["classify", "extract", "summarise"].map(run));
const parallelMs = performance.now() - t;
console.log(`parallel: max in flight ${maxInFlight}`);
console.log({ category, fields, summary });
console.log(`parallel was at least twice as fast: ${sequentialMs > 2 * parallelMs}`);sequential: max in flight 1
parallel: max in flight 3
{
category: 'billing',
fields: '{"order":"A-1042"}',
summary: 'Customer was charged twice for A-1042.'
}
parallel was at least twice as fast: true- The scripted transport counts requests in flight and makes each one take 30 ms, standing in for a real model call.
- The
for … awaitloop sends one request, waits for its answer, then sends the next: at most one in flight, and three latencies in total. Promise.all([...].map(run))starts all three requests immediately; the transport sees three in flight at once, and the total is about one latency.- The results come back in the order of the input array, regardless of which finished first, so destructuring
[category, fields, summary]is safe. - Parallelism has limits: each request still counts against your requests-per-minute and tokens-per-minute limits, and hundreds of parallel calls need a concurrency cap (Rate limits, queues and backpressure). The timing check prints true/false instead of milliseconds because real timings vary.
You can't improve what you don't measure, and averages hide the problem. Every streamed call should record three timestamps: request sent, first content delta, and stream end. From them you get TTFT, generation time and output tokens per second. This model computes them from a recorded event log (timestamps in milliseconds, as your tracing would capture them) and then summarises a day of requests by percentile.
// 1. Per-request metrics from stream timestamps (a recorded log, so the numbers are fixed).
const log = [
{ t: 0, type: "request_sent" },
{ t: 412, type: "message_start" },
{ t: 655, type: "content_block_delta" }, // first visible text
{ t: 7210, type: "message_delta", output_tokens: 512 },
{ t: 7214, type: "message_stop" },
];
const first = log.find((e) => e.type === "content_block_delta").t;
const end = log.at(-1).t, out = log.find((e) => e.type === "message_delta").output_tokens;
console.log(`TTFT ${first} ms, generation ${end - first} ms, ${(out / ((end - first) / 1000)).toFixed(1)} output tokens/s, total ${end} ms`);
// 2. A day of requests: seeded, most fast, some long answers, a few retried after a 529.
function mulberry32(seed) { return () => { seed |= 0; seed = (seed + 0x6d2b79f5) | 0; let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; }
const rand = mulberry32(11);
const totals = Array.from({ length: 2000 }, () => {
let ms = 600 + rand() * 400 + (rand() < 0.15 ? 9000 + rand() * 6000 : 2000 + rand() * 2000); // 15% long answers
if (rand() < 0.02) ms += 1000 + 8000; // 2% retried once: ~1 s backoff plus a full second attempt
return ms;
});
const sorted = [...totals].sort((a, b) => a - b);
const pct = (p) => Math.round(sorted[Math.min(sorted.length - 1, Math.floor((p / 100) * sorted.length))]);
const mean = Math.round(totals.reduce((a, b) => a + b, 0) / totals.length);
console.log(`mean ${mean} ms | p50 ${pct(50)} ms | p90 ${pct(90)} ms | p95 ${pct(95)} ms | p99 ${pct(99)} ms`);TTFT 655 ms, generation 6559 ms, 78.1 output tokens/s, total 7214 ms
mean 5384 ms | p50 4014 ms | p90 12321 ms | p95 13827 ms | p99 15347 ms- TTFT is measured to the first
content_block_delta, not tomessage_start:message_startarrives before any text and, with thinking on, the first visible text can come much later. Measure what the user sees. - Output speed is output tokens divided by the time between the first and the last token. Here 512 tokens over about 6.5 seconds is under 80 tokens per second; track it per model and per route, since it moves with load.
- The simulated day has a realistic shape: most requests take a few seconds, 15% are long answers, and 2% hit a 529 and pay a backoff plus a second attempt.
- The mean sits well above the median, and p95 and p99 are several times the median. The long answers and the retries live in the tail, and the tail is what users remember ("it sometimes takes forever").
- So dashboards show p50, p95 and p99 per route, split by TTFT and total. To shrink the tail: cap output length, cut retries' cost with a lower timeout plus a fallback model, and stream so even slow requests show progress.
Latency regressions arrive quietly. A prompt change that makes answers 40% longer adds seconds to every request and nobody notices until a dashboard does; a model upgrade with a different default effort changes TTFT; a provider having a busy hour raises queueing time for everyone. Alert on p95 TTFT and p95 total per route against a rolling baseline, and log output tokens per request so you can tell "the model got slower" (tokens per second fell) from "we asked for more" (output tokens rose).
A RAG chat route has a 40,000-token prompt (system prompt, tool definitions and retrieved documents) and 300-token answers. Which of these reduces time to first token, and which only reduces total time? (a) Prompt caching on the system prompt and tools (6,000 tokens). (b) Asking for 150-token answers. (c) Retrieving 5 documents instead of 10. (d) Fast mode.
Show answer
(a) and (c) reduce TTFT; (b) only reduces total time; (d) mainly speeds up generation, so it mostly reduces total time.
- TTFT includes prefill: reading every uncached input token before the first output token. (a) turns 6,000 tokens into cache reads, which are much faster to process, so TTFT drops.
- (c) halves the retrieved documents, removing perhaps 15,000+ uncached input tokens from prefill; TTFT drops noticeably (and quality must be re-checked).
- (b) doesn't change the input at all, so the first token arrives at the same time; the answer just finishes sooner.
- (d) Anthropic describes fast mode as higher output tokens per second, so it shortens generation. It isn't documented as a TTFT feature, so don't promise it as one.
- For a long-prompt route, the TTFT levers are fewer and cached input tokens; the total-time levers are shorter outputs and faster generation.