# How much latency does an AI gateway add? A measurement method

URL: https://infro.io/blog/how-much-latency-does-an-ai-gateway-add-a-measurement-method
Author: INFRO Editorial (https://infro.io/blog/editorial)
Publisher: INFRO
Published: 2026-11-22
Last modified: 2026-11-22
Last reviewed: 2026-11-22 (next review due 2027-05-21)
Topic: Routing and reliability
Format: Methodology

> Measure gateway overhead as the paired difference between the same request sent direct to the provider and through the gateway, reported at p50, p95 and p99 with a confidence interval. Use OpenTelemetry spans to place each millisecond, and exclude failover and cache hits from the overhead figure.

Key takeaways:
- Gateway overhead is a difference between two latency distributions, so measure it with paired direct and gateway requests rather than reading one dashboard number.
- Stop the clock at the first content delta and keep failover attempts, response-cache hits and errors out of the overhead figure; report them separately.
- Report added p50, p95 and p99 with a bootstrap confidence interval, and fail the budget on the upper bound, not the point estimate.
- Use trace context propagation so the client span, gateway span and provider call land in one trace, and treat cross-host span arithmetic as approximate because of clock skew.
- Re-run the test whenever you change guardrails, routing rules, region or connection pooling, since each changes what the hop does.

## What the question really asks

"How much latency does the gateway add?" sounds like a single number. It is not. A request through a gateway has the same provider call inside it, and provider time to first token (TTFT) varies far more from request to request than a gateway hop does. If you compare the average of last week's gateway traffic with some provider benchmark, the provider's own variance swamps the answer.

What you can state is a difference: for the same request, how many milliseconds later does the first useful chunk arrive when it goes through the gateway than when it goes direct? That is a distribution of differences, and it needs three things: a clean definition of the clock, a way to separate gateway time from provider time, and a rule for turning the result into pass or fail.

This article gives that method. It assumes you already measure TTFT from the client; if not, start with [measuring time to first token](https://infro.io/blog/measure-time-to-first-token), which covers where the clock starts and stops.

## Define the two quantities

Use one clock, on the client, and two quantities.

- **Time to first content (TTFC):** from the moment the client issues the request, before DNS and TLS, to the first delta that carries content or a tool call. Not the headers and not a role-only chunk.
- **Gateway overhead:** TTFC through the gateway minus TTFC direct to the same provider account and model, for the same request.

OpenTelemetry's GenAI attribute registry defines `gen_ai.response.time_to_first_chunk` as seconds from when the client issues the generation request to when the first chunk is received in the response stream.[1] That is the right start, but a chunk is not a token. If the first chunk is role-only, the attribute stops early. Record your own first-content time next to it, as a custom attribute, and compute overhead from that.

For non-streaming calls the equivalent is total latency, since nothing arrives before the full body. Measure it separately; do not mix the two in one percentile.

## Split the hop into places a millisecond can hide

A gateway request has several segments, and they respond to different fixes.

| Segment | What is in it | Who controls it |
| --- | --- | --- |
| Client to gateway | DNS, TCP, TLS, connection pool wait, request upload | Your network, region choice, connection reuse |
| Gateway work | Authentication, limit and policy checks, routing choice, any guardrail scan | Gateway configuration |
| Failed attempts | Each upstream failure before the first token, in full | Provider health, timeouts |
| Provider | Queueing, prompt processing, any reasoning before output | The provider and the prompt |
| Gateway to client | Relaying chunks back, any buffering | Gateway streaming behaviour, your proxies |

Only the second and fifth rows are the gateway's own work, and the first is the cost of adding a network leg. The third is a reliability feature rather than overhead, and the fourth is not the gateway's at all.

One fact from the failover contract matters here: when a connection fails before the first token, INFRO moves to the next one, and the client sees only a slightly higher time to first token.[2] A recovered request therefore looks like a slow request. If you leave those in, the gateway appears to add hundreds of milliseconds at the tail when it actually prevented an error. Exclude requests with failover attempts from the overhead figure and report them as their own line.

## Make the traces answer where the time went

A distributed trace is a set of spans sharing a trace ID, each with a parent, a start and an end.[3] Context propagation is what lets spans from different processes join one trace: the caller sends a trace ID and span ID, the callee creates a span with that parent. The default propagator uses the W3C `traceparent` header.[4]

So the plan is to start a client span for each call, inject `traceparent` into the request, and let the gateway nest its spans inside your trace. INFRO's docs say a W3C `traceparent` supplies the trace ID when nothing else does, and that INFRO's OpenTelemetry spans nest inside your own trace.[5] The exported spans carry operational metadata such as request ID, model, route, timing, token counts and estimated cost, sent as OTLP/HTTP to a collector you configure.[6] The docs do not list the gateway's internal span names, so this method does not depend on them: it uses the gateway span's start and end only as supporting evidence.

```python
import time
from opentelemetry import trace, propagate

tracer = trace.get_tracer("latency-probe")

def timed_chat(client, base_label, body):
    """One streaming call; returns first-content ms or None."""
    with tracer.start_as_current_span("chat") as span:
        span.set_attribute("probe.path", base_label)  # "direct" or "gateway"
        span.set_attribute("gen_ai.request.model", body["model"])
        headers = {}
        propagate.inject(headers)  # adds traceparent
        t0 = time.perf_counter()
        first_content_ms = None
        stream = client.chat.completions.create(
            **body, stream=True, extra_headers=headers
        )
        for chunk in stream:
            delta = chunk.choices[0].delta if chunk.choices else None
            if delta and (delta.content or delta.tool_calls):
                first_content_ms = (time.perf_counter() - t0) * 1000
                span.set_attribute("probe.first_content_ms", first_content_ms)
                break
        stream.close()
        return first_content_ms
```

The `probe.*` attributes are your own names, not OpenTelemetry conventions. For the direct path the provider may ignore `traceparent`; that is fine, because the client span still holds the number you need.

Two limits of span arithmetic. First, the gap between your client span's start and the gateway span's start includes network transit, but it is only meaningful if the hosts' clocks agree. Treat it as a hint, not a measurement. Second, trace delivery from the gateway is best effort and happens outside the response path, with one retry on a server error or network failure.[6] A missing gateway span is possible, so never use span counts as a request count. Count requests from the request log.

## Collect paired samples

Run both paths from the same host, at the same time, with the same prompts.

1. Build a prompt set that matches production: the same system prompt and a spread of input lengths. Group by input-size band, because longer prompts take longer to process before the first token and mixing sizes blurs the comparison.
2. For each prompt, send the direct call and the gateway call back to back, alternating which goes first. Alternating stops a warm connection or a warm provider cache from always favouring one side.
3. Use the same provider account, model snapshot and region on both paths. If the gateway routes to a different region than your direct call, you are measuring geography, not the hop.
4. Configure the gateway as production does: same guardrails, routing rules and policy checks. An empty gateway understates the cost.
5. Keep connection behaviour realistic. A client that opens a new TLS connection per call to the gateway but reuses one to the provider will show an overhead that production, with pooling, never pays. Pool both, and also run a cold-connection pass if your clients are short-lived.
6. Turn the response cache off for the test or exclude hits afterwards. Chat spans carry a cache status attribute, `infro.cache.status`, with values `hit`, `miss`, `bypass`, `uncacheable` or `disabled`.[6] A hit never reaches the provider, so it is faster than direct and would pull the overhead down.
7. Record failover attempts per request. The request export includes `ttft_ms`, `latency_ms` and `fallback_attempts` columns, so you can filter gateway-side rows to those with zero attempts.[5]

Run it long enough to cover busy and quiet periods. A one-hour test at 2 a.m. tells you nothing about a provider's afternoon queueing.

## Compute the overhead with an interval

Take the paired differences, then report percentiles of the gateway distribution minus percentiles of the direct distribution, with a bootstrap interval that resamples pairs.

```python
import math, random

def pct(sorted_vals, p):
    k = max(0, math.ceil(p / 100 * len(sorted_vals)) - 1)
    return sorted_vals[k]

def added_at(direct, gateway, p):
    return pct(sorted(gateway), p) - pct(sorted(direct), p)

def overhead(direct, gateway, p, n_boot=2000, seed=7):
    """direct[i] and gateway[i] are the same prompt, measured together."""
    assert len(direct) == len(gateway)
    rng = random.Random(seed)
    n = len(direct)
    point = added_at(direct, gateway, p)
    boots = []
    for _ in range(n_boot):
        idx = [rng.randrange(n) for _ in range(n)]
        boots.append(added_at([direct[i] for i in idx],
                              [gateway[i] for i in idx], p))
    boots.sort()
    return point, boots[int(0.025 * n_boot)], boots[int(0.975 * n_boot)]

for p in (50, 95, 99):
    est, lo, hi = overhead(direct_ms, gateway_ms, p)
    print(f"p{p}: added {est:.0f} ms (95% CI {lo:.0f} to {hi:.0f})")
```

Run this per input-size band and per streaming mode, over successful requests only. Keep errors out of the percentiles and count them separately, because a fast error flatters every latency number.

## Which percentiles to report

| Report | Why |
| --- | --- |
| Added p50 | The typical request; what most users feel |
| Added p95 | The slow-but-common case; where connection and queueing effects begin to show |
| Added p99 | The tail; only with enough pairs for the interval to be useful |
| Failover share and its extra TTFT | Reliability cost, kept apart from overhead |
| Error rate on each path | Shows whether the gateway changed failures, not just speed |

Do not report a mean. A hop that adds 20 ms to most requests and 400 ms to a few has a small mean and an unhappy tail. Do not report p99.9 unless you have thousands of pairs; at a few hundred it is one or two points.

One more subtlety: the difference of percentiles is not the percentile of the differences. If you want the latter, compute per-pair differences and take their percentiles. Both are legitimate; say which you used. The difference of percentiles answers "how much later is the gateway's p99 than the direct p99", which is what an SLO compares.

## Turn it into a pass/fail budget

A budget a product owner can sign has a number, a percentile, a population and a rule about uncertainty.

> **Example: Illustrative budget for a streamed chat feature**
> These figures are made up to show the shape of the rule. Set yours from your feature's own latency target.
> 
> | Metric | Budget | Population |
> | --- | --- | --- |
> | Added p50 time to first content | at most 30 ms | Zero failover attempts, no cache hits, prompts under 2k tokens |
> | Added p95 time to first content | at most 80 ms | Same |
> | Added p99 time to first content | at most 200 ms | Same, at least 2,000 pairs |
> | Failover share | reported, no budget | All requests |
> 
> Pass: the upper end of the 95% interval is at or below the budget for every row. Fail: any upper bound exceeds its budget. Inconclusive: the interval straddles the budget; collect more pairs before deciding.

Failing on the upper bound means a noisy test cannot pass by luck. If the interval is too wide to be useful, the remedy is more pairs, not a looser budget.

## Failure modes that corrupt the answer

- **Different paths, different regions.** A gateway in another region adds the round trip to every request. State the regions in the report.
- **Warm cache on one side.** Provider prompt caches reward repeated prefixes. Alternate order and vary prompts, or the second caller always wins.
- **Clock skew in span arithmetic.** Compare durations within one process. Use cross-host start times only as hints.
- **Buffering between you and the gateway.** A proxy that buffers server-sent events delays the first chunk and gets blamed on the gateway. Test from a client that talks to the gateway without that proxy.
- **Testing an empty configuration.** Guardrails, allowlists and routing rules run in the hop. Re-run the test when you change them.
- **Drift.** Provider load changes through the day and across weeks. Keep the paired probe running at low volume, and alert on the added p95 rather than on raw TTFT.

## Reading the gateway side with INFRO

If you already run INFRO, the request log gives you the gateway-side columns used above, and OpenTelemetry export sends spans to your own collector from the request path on every plan, so the client span and the gateway span can sit in one trace.[6] The export columns, including `ttft_ms` and `fallback_attempts`, are documented under [request traces](https://infro.io/docs/observability/traces), and the OpenTelemetry setup under [exports](https://infro.io/docs/observability/exports). The paired direct-versus-gateway comparison still has to run from your own client, because only the client sees both paths on one clock.

## Checklist

- [ ] One client-side clock, started before DNS and stopped at first content, not first chunk.
- [ ] Paired direct and gateway calls, alternating order, same account, model and region.
- [ ] Production gateway configuration, including guardrails and routing rules.
- [ ] Failover attempts and cache hits excluded from overhead, reported on their own.
- [ ] Added p50, p95 and p99 per input-size band, each with a bootstrap interval.
- [ ] A written budget that fails on the interval's upper bound.
- [ ] The probe left running at low volume, with an alert on added p95.

## Questions

### Can I read gateway overhead straight from the gateway's own latency field?

Only if you know where that field starts and stops its clock. A gateway-side figure usually excludes the network between your application and the gateway and the connection setup you pay on that leg. The paired client-side measurement includes both, which is what the product owner's user actually waits for.

### How many requests do I need for a p99 overhead figure?

Enough that the tail has more than a handful of points in it. With 200 pairs, p99 rests on two observations, so the bootstrap interval will be wide. Collect more pairs, or report p95 and say p99 is not yet established.

## Sources

1. Gen AI attributes (registry) — OpenTelemetry. https://opentelemetry.io/docs/specs/semconv/registry/attributes/gen-ai/ (accessed 2026-11-22)
2. Failover & fallbacks — INFRO. https://infro.io/docs/features/fallbacks (accessed 2026-11-22)
3. Traces — OpenTelemetry. https://opentelemetry.io/docs/concepts/signals/traces/ (accessed 2026-11-22)
4. Context propagation — OpenTelemetry. https://opentelemetry.io/docs/concepts/context-propagation/ (accessed 2026-11-22)
5. Request traces — INFRO. https://infro.io/docs/observability/traces (accessed 2026-11-22)
6. Exports & OpenTelemetry — INFRO. https://infro.io/docs/observability/exports (accessed 2026-11-22)
