Skip to content

Routing and reliabilityMethodology

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

A product owner asks what the gateway costs in milliseconds, and the honest answer is a difference between two distributions, not a number off a dashboard. This method separates gateway overhead from provider time to first token, using OpenTelemetry spans and paired requests, and ends in a budget that passes or fails.

By INFRO Editorial

Published

9 min read

Luminous routing paths connecting one application node to many AI model endpoints

In short

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, 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.

SegmentWhat is in itWho controls it
Client to gatewayDNS, TCP, TLS, connection pool wait, request uploadYour network, region choice, connection reuse
Gateway workAuthentication, limit and policy checks, routing choice, any guardrail scanGateway configuration
Failed attemptsEach upstream failure before the first token, in fullProvider health, timeouts
ProviderQueueing, prompt processing, any reasoning before outputThe provider and the prompt
Gateway to clientRelaying chunks back, any bufferingGateway 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.

timed_call.py
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.

overhead.py
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

ReportWhy
Added p50The typical request; what most users feel
Added p95The slow-but-common case; where connection and queueing effects begin to show
Added p99The tail; only with enough pairs for the interval to be useful
Failover share and its extra TTFTReliability cost, kept apart from overhead
Error rate on each pathShows 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.

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 (opens in a new tab), and the OpenTelemetry setup under exports (opens in a new tab). 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 readers ask

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.

From the team that builds it

Where this shows up in INFRO

INFRO is a control plane in front of the provider accounts you already hold. The capabilities below are the parts of it this article touches, each with the documentation that defines its behaviour.

  • OpenTelemetry export

    Available with a plan

    Spans pushed to your own collector from the request path, with the endpoint and headers set in the console. Included on every plan.

    Read the documentation for OpenTelemetry export
  • Request traces and payload logs

    Available with a plan

    Per-request timing detail, with prompt and completion logging off by default and a retention window you choose.

    Read the documentation for Request traces and payload logs
  • Usage, request and FOCUS exports

    Available with a plan

    GET /v1/usage and GET /v1/requests on any gateway key, the request log and usage series as CSV, plus a FOCUS v1.4 Cost and Usage dataset as JSON or CSV, so AI spend lands in your FinOps platform beside the rest of your cloud cost.

    Read the documentation for Usage, request and FOCUS exports
  • Automatic failover

    Available with a plan

    A route that times out or 5xxs before the response starts is retried elsewhere without your client seeing it.

    Read the documentation for Automatic failover
  • Response cache

    Available with a plan

    Opt-in, exact-match cache for chat completions. An identical request inside the time-to-live you set is answered from the cache and never reaches your provider, so your provider does not bill it. Every plan; the longest time-to-live depends on the plan. No semantic matching.

    Read the documentation for Response cache

INFRO accounts are self-serve. Provider usage is billed to you by your providers; INFRO charges a software subscription and takes 0% of model spend. See plans.

Sources

Numbered in order of first citation. Each was opened and checked against the claim on the date shown.

  1. 1.Gen AI attributes (registry) (opens in a new tab) — OpenTelemetry. Accessed Nov 22, 2026.
  2. 2.Failover & fallbacks (opens in a new tab) — INFRO. Accessed Nov 22, 2026.
  3. 3.Traces (opens in a new tab) — OpenTelemetry. Accessed Nov 22, 2026.
  4. 4.Context propagation (opens in a new tab) — OpenTelemetry. Accessed Nov 22, 2026.
  5. 5.Request traces (opens in a new tab) — INFRO. Accessed Nov 22, 2026.
  6. 6.Exports & OpenTelemetry (opens in a new tab) — INFRO. Accessed Nov 22, 2026.

About this article

Read the OpenTelemetry pages on traces, context propagation and the GenAI attribute registry, and INFRO's docs on request traces, OpenTelemetry export and failover, on 2026-11-22. No latency figures from any vendor are quoted; every number in the body is labelled illustrative. Gateway-internal span names were not confirmed in the docs and are not described.

Last checked against its sources on . The next review is due by . No separate named reviewer is recorded for this article.

How articles are written, sourced and corrected is set out in the editorial standards.