The usual load test is one request body, copied thousands of times by a pool of workers, reported in requests per second. Against an LLM endpoint it produces a reassuring chart that says little about launch day: every request asks for the same work, a cache has seen the prompt before, and the workers slow down whenever the server does, so the test eases off exactly when it should push.

LLM endpoints differ in three ways. Work per request varies widely, since cost grows with input and output tokens and real traffic mixes short questions with long documents. The response is a stream, so latency is at least two numbers: time to the first token and time to the last. And capacity is usually limited in tokens (GPU throughput on your own stack, or a provider's token quotas) more than in requests. Below is a load test built around those facts: a workload sampled from real traffic, an open-loop arrival schedule, and metrics taken from the stream.

Build the workload from your logs, not from one prompt

Start from what production sends. If you log token counts per call, export a few thousand recent calls from a normal week as rows of feature, input length, output length and the (redacted) prompt. Keep the per-feature mix: if 70% of calls are autocomplete and 5% are document summarization, keep those shares, because the 5% may hold most of the tokens.

Three details decide whether that sample behaves like real traffic.

Output length. You can't make a model produce exactly N tokens, but you can cap it at the logged output length for that row, which keeps outputs in the right range. If your prompts tend to produce short answers anyway, the test will under-generate, so compare the achieved output distribution with the logged one and report any gap.

Prefix sharing. Many serving stacks and providers cache shared prompt prefixes. A test that sends the same system prompt every time will get a better hit rate than production if real requests carry per-tenant instructions, retrieved documents or conversation history. A test that randomizes everything will get a worse one. Replaying real (redacted) prompts keeps the real amount of sharing. If you have to generate synthetic prompts, keep production's structure: same system prompt per feature, varied content after it.

Data handling. Real prompts may contain personal data, so redact them or keep only length and structure with neutral filler text. Run against staging or a dedicated test quota, never a production key shared with live users: a successful load test is designed to exhaust limits.

Arrive open-loop, or the test hides its own failures

Most simple load generators are closed-loop: N workers each send a request, wait, then send the next. When the server slows, every worker waits longer, fewer requests go out, and the server gets relief that real users, who don't wait for each other, would never give it. This is known as coordinated omission, and it is severe for LLM endpoints, where one slow response can last tens of seconds.

An open-loop generator fixes this by deciding arrival times in advance, independent of how fast the server answers. A common model for independent users is a Poisson process: gaps between arrivals drawn from an exponential distribution, which Python's standard library provides as random.expovariate(rate). Each request is launched at its scheduled time whether or not earlier ones have finished, and latency is measured from the scheduled time, not from when the client finally got around to sending. If the generator itself falls behind, that delay counts against the result instead of disappearing.

One trap undoes all of this: a client-side connection pool. In httpx, the default limit is 100 connections. When more requests than that are in flight, the rest wait inside the client for a free connection, which brings closed-loop behavior back in a place you aren't looking. Either remove the limit or size it well above the peak concurrency you expect, and record how far each request's actual start lagged behind its scheduled start so you can see when the generator, not the server, is the bottleneck.

Measure the stream, not just the response

For a streaming endpoint, record at least these per request:

  • Time to first token (TTFT), from scheduled start to the first content chunk. Users feel it most, and server queuing shows up there first.
  • Total time to the end-of-stream marker.
  • Output chunks (or tokens, if your API reports usage at the end of the stream), so you can compute generation speed as output divided by (total minus TTFT).
  • Outcome, split into classes: success, HTTP status by code (429 and 5xx mean different things), client timeout, transport error, and truncated stream, meaning the connection closed before the end marker. A truncated stream often arrives with a 200 status, so a test that only checks status codes counts it as a success.

Here is a compact open-loop runner using asyncio and httpx. The request body and the end-of-stream marker are placeholders. Match them to your own endpoint, which here is assumed to stream server-sent events (lines starting with data:).

import asyncio, random, time
import httpx

URL = "https://staging.example.internal/v1/generate"  # staging or a dedicated test quota
END_MARKER = "data: [DONE]"                           # whatever your stream ends with

async def one_call(client, case, t_sched, t0, out):
    lag = time.perf_counter() - t_sched              # generator lag, should stay near 0
    ttft, chunks, status = None, 0, "ok"
    try:
        async with client.stream("POST", URL, json={
            "prompt": case["prompt"],
            "max_output_tokens": case["output_tokens"],
            "stream": True,
        }) as resp:
            if resp.status_code != 200:
                status = f"http_{resp.status_code}"
            else:
                finished = False
                async for line in resp.aiter_lines():
                    if not line.startswith("data:"):
                        continue
                    if line.strip() == END_MARKER:
                        finished = True
                        break
                    if ttft is None:
                        ttft = time.perf_counter() - t_sched
                    chunks += 1
                if not finished:
                    status = "truncated_stream"
    except httpx.TimeoutException:
        status = "timeout"
    except httpx.TransportError:
        status = "transport_error"
    out.append({"feature": case["feature"], "status": status, "lag": lag,
                "ttft": ttft, "total": time.perf_counter() - t_sched,
                "chunks": chunks, "at": t_sched - t0})

async def run(workload, rate_per_s, duration_s, seed=1):
    rng = random.Random(seed)
    timeout = httpx.Timeout(120.0, connect=5.0)      # default 5 s read timeout is too short
    limits = httpx.Limits(max_connections=None)      # no hidden client-side queue
    out, tasks = [], []
    async with httpx.AsyncClient(timeout=timeout, limits=limits) as client:
        t0 = time.perf_counter()
        t_next = t0
        while t_next - t0 < duration_s:
            t_next += rng.expovariate(rate_per_s)
            await asyncio.sleep(max(0.0, t_next - time.perf_counter()))
            tasks.append(asyncio.create_task(
                one_call(client, rng.choice(workload), t_next, t0, out)))
        await asyncio.gather(*tasks)
    return out

Why the details matter: the fixed seed makes the arrival schedule and the case selection repeatable, so two runs against two configurations get the same traffic. TTFT and total are both measured from t_sched, so generator lag can't hide server queuing. The timeout override exists because httpx's read timeout applies to each wait for data with a 5-second default, and under load a long prompt can easily take longer than that to produce its first chunk. Without the override you would record client timeouts that production, with its own settings, would never see.

Where this runner falls short: counting data: lines measures chunks, not tokens, and some APIs put several tokens in one chunk, so use the usage numbers from the final event if your API sends them. A single Python process also has a ceiling on how many concurrent streams it can parse. If lag climbs while the server looks healthy, the generator is saturated, and you need more processes or machines, each running a share of the rate.

Ramp the rate and read the knee

Run fixed-rate steps (say five minutes each at increasing rates) rather than one long run at a guessed number. For each step, report per feature: p50 and p95 TTFT, p95 total time, generation speed, and the rate of each failure class. Percentiles per feature matter because a slowdown in summarization can hide inside a healthy-looking overall median.

What you are looking for is the knee: the step where p95 TTFT starts climbing much faster than the arrival rate. That is usually where requests begin to queue, whether in your inference server's batch scheduler or behind a provider's throughput limit. Note the arrival rate and token throughput there. Token throughput at the knee is the number that carries over to capacity planning, since request rate alone changes whenever the traffic mix does. Then decide your operating limit with headroom below the knee, and check what happens past it: do excess requests get a fast 429 that your client can back off from, or do they hang until a timeout? A fast, explicit rejection is far easier to build a product around.

A result is only valid for its inputs. A longer system prompt, a faster or slower model, or a shifted traffic mix all move the knee, so version the workload file and seed next to the results and rerun when they change.

Checklist

  • Workload sampled from redacted real logs, per-feature mix and prefix structure preserved.
  • Output caps from logged lengths; achieved output distribution checked against them.
  • Open-loop Poisson arrivals, fixed seed, latency measured from scheduled start.
  • No hidden client connection limit; generator lag recorded; read timeout raised.
  • Per request: TTFT, total time, generation speed, outcome class (truncated streams are failures).
  • Stepped ramp with per-feature percentiles; knee reported in tokens per second.
  • Past the knee: fast rejections, not slow hangs.
  • Staging or a dedicated quota only.

Further reading