ByteCosts
context-proxy-latency-ttft.mdx

AI Coding Agents

Measure LLM proxy latency against prefill savings

An LLM proxy adds work before a response reaches the client, but compression can shorten the prompt and reduce the time the model spends processing it. Measure time to first content and total latency on matched direct and proxied requests, group runs by actual cache behavior, and use your observed time saved per token to estimate a break-even.

Compare the clocks behind published numbers

A gateway overhead metric can start and stop inside the gateway. A developer waiting for a coding agent cares about elapsed time from dispatch to the first usable content, and then about how long the full response takes. This guide uses time to first token (TTFT) to mean the first nonempty text event the client observes. The event can carry a chunk of text. If users are waiting for a tool action, define an equivalent first tool event and keep its results in a separate cohort. The clock you choose determines which delays can appear in the result.

Source as of November 30, 2026What the source measured or documentedWhat it leaves open
LiteLLM short-prompt chat testThe vendor reported 8 ms p95 gateway overhead at 1,170 requests per second across four instances. The mock OpenAI endpoint isolates the gateway workload. Overhead comes from the x-litellm-overhead-duration-ms response header.Actual model prefill and client-observed TTFT for your workload.
LiteLLM per-pod testIn the November 20, 2026 v1.110.0 run, regular-request p99 overhead at 100, 150, and 200 combined requests per second was 47, 91, and 651 ms. Streaming p99 overhead at those loads was 45, 93, and 645 ms.The overhead header excludes the full streaming duration. The mock provider also leaves real model and network behavior unmeasured.
Headroom production telemetryHeadroom self-reported 52 ms median, 309 ms P90, and 4,172 ms P99 proxy overhead. Its separate compression microbenchmark times the compress() SDK call.The production page gives no precise bounds for its overhead clock. The SDK timing covers only the compression call.
Portkey READMEPortkey advertises under 1 ms of latency. Treat it as an unverified marketing claim.The README gives no benchmark method, clock boundaries, load, or percentile for the figure.
OpenAI latency guideNew input in a long prompt can delay the first token. The guide recommends comparing TTFT on requests with and without cache hits.A universal prefill speed or a latency percentage for a particular prompt.
Anthropic prompt caching guideAnthropic says long documents generally see improved time to first token with caching. It describes the same latency behavior for its five-minute and one-hour caches.A numeric speedup or a gain for a particular proxy.

The LiteLLM per-pod figures show why the launch decision needs a latency distribution. The p99 overhead under the published workload grew as more requests hit the same pod. Headroom’s production figures also spread substantially from the middle to the tail. Each result belongs to its own workload and clock. For a comparable decision, measure the same endpoints from one client with the same start and stop events. LiteLLM benchmarks, Headroom benchmarks, Portkey README, OpenAI latency guide, Anthropic prompt caching

Pair direct, pass-through, and compressed requests

Use the same original prompt in all three routes. Send it unchanged on the direct path. On the pass-through control path, do the work of deciding what to shorten and discard the transformation, then send the original. On the compressed path, keep that transformation. The pass-through control lets you estimate proxy and compression work while holding upstream input fixed. If your gateway only offers a bypass that skips compression, measure the complete compressed path against direct, then use a separate direct prompt-length sweep to estimate the input savings.

Run the comparison for realistic inputs with different structures. A tool result containing repeated package build output is a separate case from a source file with identifiers and line numbers that the agent needs to edit. For each prompt, hold model, output budget, tool definitions, region, and streaming settings fixed. Send the same task and use the same acceptance check in each arm. Alternate route order so one path doesn’t always run first. Once a serial sample is working, repeat under representative concurrency and track timeouts, retries, and failures alongside successful response times.

Split cold and warm observations before computing a summary. Preserve a stable prefix for warm trials and verify actual cached token counts instead of inferring hit status from the order of requests. A compressed prompt can have fewer input tokens and still arrive slower if the change discards a warm prefix. OpenAI’s Responses latency guide points to usage.input_tokens_details.cached_tokens for this check. For a live implementation, collect total and cached input on all paths and use the break-even calculation only within comparable cache conditions. Where a proxy actually changes cache behavior, keep those end-to-end results visible as a separate operational comparison. OpenAI latency guide, measure prompt cache hit rate

Write down where the proxy can spend the saved time before you tune thresholds. For an inline gateway, include the time the caller spends waiting for a usable stream event. If you can also record gateway processing time, keep it beside the client timings so you can tell where a regression starts. To compare a tool-side hook and a gateway, use an equivalent task and clock for both. The proxy, hook, and MCP comparison walks through where each approach can change the input.

Run the streaming benchmark locally

The reference implementation uses Python 3’s standard library. A fake server process receives requests over a pipe and flushes newline-delimited JSON events back over another pipe. This is a local benchmark protocol. The event names and input count belong to the fixture, and the included code makes no network calls. Keep these files in the same directory. For real traffic, adapt the event reader to the client you already use and run the same pairing and summary logic. Preserve the arrival timestamp at the original client boundary, since buffering before events reach the harness changes what the clock measures.

Save the event reader as stream.py. It starts timing just before writing the request, ignores empty text and readiness events for TTFT, and stops the total clock on completion. An explicit error or a stream that ends before completion fails the run. This is a serial fixture with blocking pipes. When adapting it, set a deadline for the full response and record interrupted trials as failures instead of treating their last event as completion.

import json
from dataclasses import dataclass
from time import perf_counter


@dataclass(frozen=True)
class Sample:
    ttft_ms: float
    total_ms: float
    input_tokens: int


def measure(server, route, prompt):
    request = json.dumps({"route": route, "prompt": prompt})
    start = perf_counter()
    server.stdin.write(request + "\n")
    server.stdin.flush()
    first = None
    for line in server.stdout:
        received = perf_counter()
        event = json.loads(line)
        if event["kind"] == "text" and event.get("text") and first is None:
            first = received
        if event["kind"] == "done":
            count = event["input_tokens"]
            if first is None or type(count) is not int or count < 0:
                raise ValueError("invalid completed stream")
            return Sample((first - start) * 1000, (received - start) * 1000, count)
        if event["kind"] == "error":
            raise RuntimeError(f"{route}: {event['message']}")
        if event["kind"] not in ("ready", "text"):
            raise ValueError("unexpected stream event")
    raise ValueError("stream ended before completion")

In bench.py, the median and nearest-rank p95 summarize each route. The break-even calculation uses differences inside each matched group of requests. median_added_ms is pass-through TTFT minus direct TTFT. median_saved_ms is pass-through TTFT minus compressed TTFT. Divide the latter by the number of tokens removed to estimate milliseconds saved per token for that prompt and cache condition. Then divide the nonnegative median overhead by that observed rate and round up to a whole token. The helper returns no threshold when token removal yields no positive measured time saving.

import argparse
import json
import subprocess
import sys
from dataclasses import asdict
from itertools import cycle, permutations
from math import ceil
from statistics import median

from stream import measure

ROUTES = ("direct", "pass", "compressed")


def percentiles(values):
    ordered = sorted(values)
    return {"p50": median(ordered), "p95": ordered[ceil(0.95 * len(ordered)) - 1]}


def summarize(rows):
    return {
        route: {
            metric: percentiles([getattr(row[route], metric) for row in rows])
            for metric in ("ttft_ms", "total_ms")
        }
        for route in ROUTES
    }


def break_even(rows):
    removals = set()
    overhead, saved, net = [], [], []
    for row in rows:
        direct, passthrough, compressed = (row[route] for route in ROUTES)
        if direct.input_tokens != passthrough.input_tokens:
            raise ValueError("pass route changed input token count")
        removals.add(passthrough.input_tokens - compressed.input_tokens)
        overhead.append(passthrough.ttft_ms - direct.ttft_ms)
        saved.append(passthrough.ttft_ms - compressed.ttft_ms)
        net.append(compressed.ttft_ms - direct.ttft_ms)
    if len(removals) != 1:
        raise ValueError("analyze fixed token removals per prompt and cache cohort")
    removed = removals.pop()
    median_overhead, median_saved = median(overhead), median(saved)
    ms_per_token = median_saved / removed if removed > 0 and median_saved > 0 else None
    return {
        "removed_tokens": removed,
        "median_added_ms": median_overhead,
        "median_saved_ms": median_saved,
        "median_proxy_minus_direct_ms": median(net),
        "ms_saved_per_removed_token": ms_per_token,
        "break_even_tokens": ceil(max(0, median_overhead) / ms_per_token) if ms_per_token else None,
    }

Append the runner below to the same file. It starts the fixture before the timed trials, cycles through route orders, and keeps raw timings and token counts so you can inspect individual prompts and paired differences. Run it separately for each prompt and cache cohort. In a live adapter, run a controlled length sweep before treating the break-even as useful beyond the measured prompt pair. Near the threshold, small fluctuations can change the sign of the result, so check several nearby reductions.

def run(fixture, prompt, repeats):
    if repeats < 1:
        raise ValueError("repeats must be positive")
    orders = cycle(permutations(ROUTES))
    with subprocess.Popen(
        [sys.executable, "-uB", fixture], stdin=subprocess.PIPE,
        stdout=subprocess.PIPE, text=True, encoding="utf-8",
    ) as server:
        if server.stdout.readline() != '{"kind": "ready"}\n':
            raise ValueError("fixture failed to start")
        rows = [
            {route: measure(server, route, prompt) for route in next(orders)}
            for _ in range(repeats)
        ]
    return {
        "latency": summarize(rows),
        "break_even": break_even(rows),
        "samples": [{route: asdict(sample) for route, sample in row.items()} for row in rows],
    }


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("fixture")
    parser.add_argument("prompt")
    parser.add_argument("--repeats", type=int, default=24)
    args = parser.parse_args()
    print(json.dumps(run(args.fixture, args.prompt, args.repeats), indent=2))

Save the server as fake_stream.py. It treats each whitespace-separated word as a toy token and removes words equal to noise only in the compressed route. Both proxy routes simulate identical processing work. The sleeps create a controlled delay per remaining word before the first text event, plus a fixed delay before completion. These fixture choices make it possible to exercise the timing boundary and arithmetic locally.

import json
import sys
from time import sleep


def event(**data):
    print(json.dumps(data), flush=True)


def serve(request):
    route = request["route"]
    if route not in ("direct", "pass", "compressed", "truncated"):
        event(kind="error", message="unknown route")
        return True
    words = request["prompt"].split()
    if route in ("pass", "compressed"):
        kept = [word for word in words if word != "noise"]
        sleep(0.004)
        if route == "compressed":
            words = kept

    event(kind="ready")
    sleep(len(words) * 0.001)
    event(kind="text", text="ok")
    if route == "truncated":
        return False
    sleep(0.003)
    event(kind="done", input_tokens=len(words))
    return True


if __name__ == "__main__":
    event(kind="ready")
    for line in sys.stdin:
        if not serve(json.loads(line)):
            break

Save this test as test_bench.py alongside the benchmark and server. It covers percentile and break-even calculations with fixed inputs, then runs the local streams through the same reader. It checks completion ordering, route-specific token counts, and the handling of a truncated or rejected stream without requiring exact timings from the operating system.

import subprocess
import sys
import unittest

from bench import break_even, percentiles, run
from stream import Sample, measure


class BenchmarkTest(unittest.TestCase):
    def test_percentiles_and_threshold(self):
        self.assertEqual(percentiles(range(1, 21)), {"p50": 10.5, "p95": 19})
        rows = [{
            "direct": Sample(20, 23, 20),
            "pass": Sample(25, 28, 20),
            "compressed": Sample(15, 18, 10),
        }]
        result = break_even(rows)
        self.assertEqual(result["break_even_tokens"], 5)
        self.assertEqual(result["median_proxy_minus_direct_ms"], -5)
        rows[0]["compressed"] = Sample(25, 28, 10)
        self.assertIsNone(break_even(rows)["break_even_tokens"])
        rows[0]["pass"] = Sample(25, 28, 19)
        with self.assertRaisesRegex(ValueError, "changed input token count"):
            break_even(rows)

    def test_local_streams(self):
        result = run("fake_stream.py", "check parser noise noise", 2)
        with subprocess.Popen(
            [sys.executable, "-uB", "fake_stream.py"], stdin=subprocess.PIPE,
            stdout=subprocess.PIPE, text=True, encoding="utf-8",
        ) as server:
            self.assertIn("ready", server.stdout.readline())
            with self.assertRaisesRegex(RuntimeError, "unknown route"):
                measure(server, "unknown", "check parser")
            with self.assertRaisesRegex(ValueError, "ended before completion"):
                measure(server, "truncated", "check parser")
        self.assertEqual(len(result["samples"]), 2)
        for row in result["samples"]:
            self.assertEqual(
                [row[route]["input_tokens"] for route in ("direct", "pass", "compressed")],
                [4, 4, 2],
            )
            for sample in row.values():
                self.assertGreaterEqual(sample["ttft_ms"], 0)
                self.assertGreater(sample["total_ms"], sample["ttft_ms"])


if __name__ == "__main__":
    unittest.main()

Run python3 -B -m unittest -v from the file directory. For a benchmark run, execute python3 -B bench.py fake_stream.py "check parser $(printf 'noise %.0s' {1..18})" --repeats 24 in a shell with brace expansion. Each repetition sends all three routes the same prompt. The report contains times in milliseconds. Use the raw samples to recompute the statistics if you need confidence intervals or want to determine whether the ordering of requests affected the result.

Read the result as a local break-even estimate

The table shows one run of 24 matched repetitions on an arm64 Mac using Python 3.13.14, with the fake provider communicating over subprocess pipes. The direct and pass-through paths processed 20 fixture tokens each and the compressed path processed two. Repeat runs can shift the median overhead by a few milliseconds and move the calculated break-even by several fixture tokens. The observed quantiles are rounded to one decimal place.

RouteTTFT p50TTFT p95Total p50Total p95
Direct23.0 ms29.8 ms27.5 ms33.6 ms
Pass-through28.6 ms35.5 ms33.2 ms39.0 ms
Compressed8.0 ms9.2 ms12.2 ms13.5 ms

The measured median paired overhead was 4.0 ms. The median paired saving was 21.0 ms across 18 fixture tokens removed, or about 1.17 ms per token. Using the unrounded values, the threshold rounded up to four fixture tokens. The observed compressed-minus-direct median was −15.3 ms, so the first text event arrived about 15 ms sooner on the compressed path. The paired median comes from within-repetition differences and generally differs from subtracting route medians. All of these timings include the local fixture and scheduling behavior. The fixture’s simulated delay supplies the token-to-time relationship, so use your own measurements for a provider.

For a live benchmark, graduating from the fixture requires real provider input counts downstream of the proxy. Record cached and uncached portions, repeat at the typical prompt lengths, and estimate the slope for each useful input class from the actual change in TTFT. Keep conditions such as cache hits and model settings fixed while learning that slope. Inspect p95 from the complete compressed path directly. A median token break-even by itself can miss the queueing and processing delays that show up on slower requests.

A p95 based on a short local run is useful for verifying the report shape. For a launch decision, collect enough completed runs at the concurrency your clients produce and report failures separately. Sample slow prompts as well as common ones. If the gateway buffers text, the client may observe a later first event even when upstream generation started earlier. Keep that delay in the reported TTFT because it affects when the user sees progress. A separate upstream timestamp can help you diagnose that gap.

Decide which requests should use the proxy

Set an acceptance check before you compare timings. On a failing test, require the exact failing case, assertion, and location to remain recoverable. On a repository edit, require the same patch validation whether the tool output went through compression or straight into the model. Include retry cost if a compressed response forces the agent to fetch the original content. Measure time to an accepted edit alongside TTFT and full response latency when the job spans multiple calls.

Keep a retrievable original when the compressed result leaves open a question the agent may need to answer. Exercise that recovery on the same tasks you timed. For example, let the agent request the original test output when the filtered result omits a nearby assertion, and count the second read in the task’s latency. Reversible context compression describes the design trade-off.

Use the proxy on request classes where measured compression repays the overhead, the tail stays within your latency target, and the agent still has the evidence it needs. Short tool results may have too little removable input to repay the extra work. When repetitive test logs are the main source of excess input, try filtering at the tool boundary with the test-output triage filter. Compare that path using the same clocks. Use the SQLite cost telemetry guide to connect the per-request timings to tool calls, retries, and accepted outcomes.

Sources

How this note was produced

Drafted with AI assistance from committed ByteCosts pricing snapshots and deterministic cost formulas. Figures are grounded in the linked sources (last updated 2026-11-30). Read our editorial & automation policy, inspect the methodology, or report a discrepancy.

Measure LLM proxy latency against prefill savings. ByteCosts. Updated 2026-11-30. https://bytecosts.com/blog/context-proxy-latency-ttft/

Sources