Measure TTFT and prompt cache performance
Measure TTFT and cache usage separately so you can tell whether an AI feature is slow because of input processing, prefix reuse, or generation.
A single “slow AI” report usually blends two different delays: the time before the model starts returning text, and the time it spends finishing the answer. If you treat them as one number, you can optimize the wrong part of the feature and still leave the user staring at a spinner.
The useful approach is to measure TTFT from the first request byte to the first nonempty streamed text, then pair that with prompt-cache usage for requests that share an exact prefix. When the output workload stays the same, the comparison tells you whether the visible wait is mostly prefix processing or mostly generation.
What the reader is actually trying to disentangle
A slow AI feature can hide two different waits behind one spinner. The request may spend most of its time preparing a long prompt prefix, or it may start quickly and then spend most of its time generating the answer. Those are not the same problem, and they do not respond to the same fix. If you only look at total wall-clock time, a prompt that is expensive to process can look just like a model that is slow to generate.
The useful split is to measure time to first token separately from the time it takes to finish the response. In the streamed Responses API guidance, TTFT is the interval from sending the request until the first nonempty `response.output_text.delta`. End-to-end latency is the whole wait through model work, tool calls, retries, and rendering. That distinction matters because a fast first token with a long tail points you toward output size or reasoning cost, while a slow first token points you toward the prompt, retrieval, or prefix reuse.
The example in this article keeps the measurement boundary narrow on purpose. It does not try to prove that the provider route, model tier, or browser rendering path caused a result. It shows how to record the parts that you can observe directly, and how to compare two requests that should produce the same output workload so the remaining difference is easier to interpret.
/**
* Measures a streamed Responses-style event sequence with an injected clock.
* This measures application-observed timings; it does not prove a provider's
* cache routing or cache lifetime behavior.
*/
export async function measureStreamingResponse({ stream, now }) {
if (!stream || typeof stream[Symbol.asyncIterator] !== "function") {
throw new TypeError("stream must be an async iterable");
}
if (typeof now !== "function") {
throw new TypeError("now must be a function");
}
const startedAt = now();
let firstTextAt = null;
let completedUsage = null;
for await (const event of stream) {
if (
event?.type === "response.output_text.delta" &&
typeof event.delta === "string" &&
event.delta.length > 0 &&
firstTextAt === null
) {
firstTextAt = now();
}
if (event?.type === "response.completed") {
completedUsage = event.response?.usage ?? null;
}
}
const finishedAt = now();
const details = completedUsage?.input_tokens_details ?? {};
return {
ttftMs: firstTextAt === null ? null : firstTextAt - startedAt,
endToEndMs: finishedAt - startedAt,
inputTokens: completedUsage?.input_tokens ?? null,
cachedTokens: details.cached_tokens ?? 0,
outputTokens: completedUsage?.output_tokens ?? null,
};
}
/**
* Compares two measurements for the same requested output budget/workload.
* A positive ttftSavedMs is an observed difference, not proof that cache reuse
* caused it. Real cache behavior must be verified from provider usage fields.
*/
export function compareIdenticalWorkloads({ withoutCache, withCache }) {
for (const [name, measurement] of Object.entries({ withoutCache, withCache })) {
if (
!measurement ||
!Number.isFinite(measurement.ttftMs) ||
!Number.isFinite(measurement.endToEndMs) ||
!Number.isFinite(measurement.outputTokens)
) {
throw new TypeError(`${name} must contain finite TTFT, end-to-end, and output token measurements`);
}
}
if (withoutCache.outputTokens !== withCache.outputTokens) {
throw new RangeError("identical-workload comparison requires equal outputTokens");
}
return {
outputTokens: withCache.outputTokens,
cachedTokensWithoutCache: withoutCache.cachedTokens ?? 0,
cachedTokensWithCache: withCache.cachedTokens ?? 0,
ttftSavedMs: withoutCache.ttftMs - withCache.ttftMs,
generationMsWithoutCache: withoutCache.endToEndMs - withoutCache.ttftMs,
generationMsWithCache: withCache.endToEndMs - withCache.ttftMs,
};
}
SourcesOpenAI latency optimization guide (opens a new tab)OpenAI prompt caching guide (opens a new tab)
Measure the first nonempty delta, not the first event
Streaming does not help if you mark the clock at the wrong event. A Responses stream can include empty deltas before any visible text arrives, so the event boundary that matters is the first nonempty `response.output_text.delta`. The OpenAI latency guide names that exact point because it corresponds to the moment the user can finally read something. For a debugging comparison, that is the signal that tells you whether the blank screen is caused by pre-generation work or by the model’s visible output phase.
The supplied fixture models that distinction directly. Its `measureStreamingResponse()` helper starts the clock before iteration, ignores empty text deltas, and stops counting TTFT at the first delta with actual text. It also records the completed usage object when a `response.completed` event arrives, so the measurement keeps the timing and token accounting together. That combination is useful because latency without token counts is hard to interpret, and token counts without timing do not tell you where the wait happened.
The key limitation is equally important: a TTFT number from one request does not explain why the wait happened. It only says when the first visible text appeared. If the first token is late, you still have to check prompt length, cache reuse, retrieval work, and any other pre-generation steps separately. This article keeps those responsibilities separate instead of pretending the timing itself reveals the cause.
Read cache signals as evidence, not as a promise
Prompt caching helps only when the rendered prefix matches an eligible exact prefix, and the API exposes that reuse through `usage.input_tokens_details.cached_tokens`. That field is the evidence you want when comparing two requests with the same workload. If the second request shows cached input tokens and its TTFT drops, you have a plausible sign that prefix processing became cheaper. If cached tokens stay at zero, you have not observed reuse, even if the prompt looks similar to a human.
The prompt-caching guide makes another point that is easy to miss: cached input does not change how the model generates output tokens. The same prefix can reduce the work needed before generation starts, but it does not guarantee identical outputs or faster token emission after the first token. That is why the article’s comparison helper separates `ttftSavedMs` from the time after the first token. A request can benefit from cache reuse and still spend the same amount of time generating the answer once generation begins.
That separation helps prevent a common diagnostic mistake. If the first response is slow and the second response is faster, you may be tempted to credit the whole difference to the cache. But if the output workload changed, the comparison has already stopped being clean. The exact same output length and task shape need to stay constant, or the numbers stop isolating the part you wanted to understand.
SourcesOpenAI prompt caching guide (opens a new tab)OpenAI latency optimization guide (opens a new tab)
Compare identical output workloads, not just similar prompts
The most useful comparison is between two requests that should produce the same output budget and the same task, one with cache reuse and one without it. The helper in the supplied example refuses to compare requests whose `outputTokens` differ, because a different output workload changes the meaning of the timing difference. That guard is intentional. A request that emits more text often needs more time after the first token, and that extra time has nothing to do with whether the prefix was reused.
The comparison also keeps the interpretation honest by splitting the observed wait into two pieces: TTFT savings and the time after the first token. In the fixture, the cached request and uncached request have the same `outputTokens`, but different TTFT values. The helper then reports that the generation-time segment is unchanged. That result does not prove a provider invariant; it only shows how to read the measurements so you do not mistake a prefix win for a generation win.
This is where the article’s debugging posture matters. A measurement method is only useful if it rejects the wrong comparison. If you allow one request to answer a shorter prompt, or one model call to stream a shorter completion, you no longer know whether the wait shrank because the prefix became cheaper or because the model simply had less to say. The comparison must keep the output workload fixed before its interpretation is meaningful.
SourcesOpenAI latency optimization guide (opens a new tab)OpenAI prompt caching guide (opens a new tab)
What the small fixture proves, and what it does not
The supplied code is deliberately small enough to read as a measurement contract. It proves that a stream with empty deltas before visible text should not count as a text start, that completed usage data can be captured alongside timings, and that the comparison helper rejects mismatched output workloads. Those are useful guarantees for an application-owned test because they keep the measurement logic from drifting as the feature evolves.
It does not prove provider-side routing, cache lifetime, or browser rendering. A passing Node test can only show what your own measurement code records from a controlled event sequence. The OpenAI guides describe cache reuse, cache write and read accounting, and streamed TTFT measurement; they do not claim that a local simulation can establish the provider’s machine-level behavior. That boundary is important because a local fixture is evidence for your parser and your dashboard math, not for the provider’s internal scheduler.
That limitation should shape how you use the result. If TTFT falls and cached tokens rise, you can say prefix processing became cheaper for that request shape. If TTFT stays high while output stays short, you still need to investigate retrieval, prompt size, tool calls, or the client’s own pre-model work. The test tells you whether your instrumentation can separate those cases; it does not choose the fix for you.
How to use the numbers in practice
Once you can see TTFT and cached input together, the next step is to classify the bottleneck instead of guessing. A high TTFT with cached tokens near zero points toward prompt size, unstable prefixes, or missing cache reuse. A high TTFT with cached tokens present points toward work that happens before the first token but after the prefix match, such as retrieval, tool preparation, or application-side preprocessing. A low TTFT with a long total response points toward output size, visible verbosity, or reasoning time after generation begins.
That classification is why the guide recommends recording median and p95 separately. Median tells you what most users see, while p95 reveals the slow path that makes the interface feel unreliable. If you only look at averages, a few fast cache hits can hide the slower uncached requests that matter most. If you only look at one request, you can misread a transient cache miss as a structural problem. The better habit is to group like with like: same model, same task, same output length, same service tier, and then compare cache-hit and cache-miss runs within that group.
The final operational rule is simple: fix the part that changed first. If prefix processing dominates, shrink or stabilize the prompt and watch cached_tokens. If generation dominates, trim the requested output, lower verbosity where supported, or reduce reasoning effort for routine tasks. The measurements do not replace judgment, but they keep the judgment anchored to the wait the user actually feels.
import test from "node:test";
import assert from "node:assert/strict";
import { compareIdenticalWorkloads, measureStreamingResponse } from "./main.mjs";
function clock() {
let time = 0;
return { now: () => time, set: (nextTime) => { time = nextTime; } };
}
function timedStream(events, setTime) {
return (async function* () {
for (const { at, event } of events) {
setTime(at);
yield event;
}
})();
}
test("measures TTFT at the first nonempty text delta and records cache usage", async () => {
const c = clock();
const stream = timedStream([
{ at: 12, event: { type: "response.output_text.delta", delta: "" } },
{ at: 40, event: { type: "response.output_text.delta", delta: "Hello" } },
{ at: 95, event: { type: "response.completed", response: { usage: {
input_tokens: 1200,
output_tokens: 20,
input_tokens_details: { cached_tokens: 900 },
} } } },
], c.set);
const result = await measureStreamingResponse({ stream, now: c.now });
assert.deepEqual(result, {
ttftMs: 40,
endToEndMs: 95,
inputTokens: 1200,
cachedTokens: 900,
outputTokens: 20,
});
});
test("returns a null TTFT when a stream completes without visible text", async () => {
const c = clock();
const stream = timedStream([
{ at: 10, event: { type: "response.output_text.delta", delta: "" } },
{ at: 30, event: { type: "response.completed", response: { usage: {
input_tokens: 10,
output_tokens: 0,
input_tokens_details: { cached_tokens: 0 },
} } } },
], c.set);
const result = await measureStreamingResponse({ stream, now: c.now });
assert.equal(result.ttftMs, null);
assert.equal(result.endToEndMs, 30);
});
test("rejects a cache comparison when the output workloads differ", () => {
assert.throws(
() => compareIdenticalWorkloads({
withoutCache: { ttftMs: 300, endToEndMs: 900, outputTokens: 30, cachedTokens: 0 },
withCache: { ttftMs: 100, endToEndMs: 700, outputTokens: 31, cachedTokens: 500 },
}),
{ name: "RangeError", message: "identical-workload comparison requires equal outputTokens" },
);
});
test("separates observed TTFT savings from post-first-text generation time", () => {
const comparison = compareIdenticalWorkloads({
withoutCache: { ttftMs: 300, endToEndMs: 900, outputTokens: 30, cachedTokens: 0 },
withCache: { ttftMs: 100, endToEndMs: 700, outputTokens: 30, cachedTokens: 500 },
});
assert.deepEqual(comparison, {
outputTokens: 30,
cachedTokensWithoutCache: 0,
cachedTokensWithCache: 500,
ttftSavedMs: 200,
generationMsWithoutCache: 600,
generationMsWithCache: 600,
});
});
SourcesOpenAI prompt caching guide (opens a new tab)OpenAI latency optimization guide (opens a new tab)


