AiCredits
Latency Metrics

Monitoring LLM Latency: p50 vs p95 and Why Both Matter

Why a p50-only dashboard hides broken UX, how to measure TTFT and total latency for deepseek-v4-flash in Python, and when p95 should page your team.

Published 2026-11-19 Updated 2026-11-19 8 min

Averages Hide the Requests Your Users Remember

If you log one number per LLM call and average it, you are measuring a request nobody actually had. An endpoint can look perfectly healthy on an average-latency chart while one in twenty calls drags on long enough for a user to refresh the page, retry, or leave. LLM traffic is heavy-tailed by nature: output length changes call to call, prompt sizes vary, retries stack up, and short queueing events hit a small slice of requests. A mean smooths all of that into a figure that describes no real request in your system.

Percentiles fix the framing. p50, the median, is the request your typical user gets. p95 is the request your unluckiest one-in-twenty user gets. On a healthy system they move together. When p50 is flat and p95 climbs, something is degrading the tail while the middle looks fine — the classic signature of retry storms, oversized prompts, cold connections, or a capacity squeeze.

Measure Three Things, Not One

Before percentiles mean anything, you need the right quantity. For streaming chat APIs, "latency" splits into at least three numbers that fail in different ways.

  • TTFT (time to first token): from request sent to the first content chunk. This is what users perceive as responsiveness, and for streaming UIs it dominates perceived speed.

  • Generation time / tokens per second: from first token to last. Long outputs are slow by design — cap max_tokens before you blame the provider.

  • Total duration: the end-to-end number your timeout budget and retry logic actually care about.

  • Outcome and retry count, logged next to every timing. A fast failure is not a fast success, and a p95 built out of retried requests hides the real cause.

A Runnable p50/p95 Harness for deepseek-v4-flash

This script streams 30 requests, records TTFT and total duration per call, and prints p50, p95 and max. It uses only the OpenAI SDK and the standard library, so it runs unchanged in CI or as a cron job against your own prompt set.

import math
import os
import time

from openai import OpenAI

client = OpenAI(
    api_key=os.environ["AICREDITS_API_KEY"],
    base_url="https://api.aicreditsapi.com/v1",
)

PROMPT = "Summarize what an API gateway does in three sentences."


def percentile(values, p):
    """Linear-interpolated percentile; p in 0..100."""
    if not values:
        return float("nan")
    ordered = sorted(values)
    k = (len(ordered) - 1) * (p / 100.0)
    lo, hi = math.floor(k), math.ceil(k)
    if lo == hi:
        return ordered[lo]
    return ordered[lo] * (hi - k) + ordered[hi] * (k - lo)


def one_call(model="deepseek-v4-flash"):
    start = time.perf_counter()
    ttft = None
    chars = 0
    stream = client.chat.completions.create(
        model=model,
        messages=[{"role": "user", "content": PROMPT}],
        stream=True,
        max_tokens=200,
    )
    for chunk in stream:
        if not chunk.choices:
            continue
        delta = chunk.choices[0].delta.content
        if delta:
            if ttft is None:
                ttft = time.perf_counter() - start
            chars += len(delta)
    return {"ttft": ttft, "total": time.perf_counter() - start, "chars": chars}


samples = []
for i in range(30):
    try:
        samples.append(one_call())
    except Exception as exc:  # keep the run going; count failures separately
        print(f"request {i} failed: {type(exc).__name__}")

ttfts = [s["ttft"] for s in samples if s["ttft"] is not None]
totals = [s["total"] for s in samples]

print(f"n={len(samples)}  failures={30 - len(samples)}")
for label, vals in (("TTFT", ttfts), ("total", totals)):
    if not vals:
        continue
    print(
        f"{label:>5}  p50={percentile(vals, 50):.2f}s  "
        f"p95={percentile(vals, 95):.2f}s  max={max(vals):.2f}s"
    )

Read the numbers together. If p50 and p95 drift upward in step, the change is systemic — prompt growth, a different model, a new region. If p50 is tight and p95 sits several times higher, your tail is contaminated, and the fix is usually in the client: retries without jitter, uncapped max_tokens, or connection churn. Note that with 30 samples, p95 is effectively your second-worst request — a smoke signal, not a stable metric. Grow the window before you set alerts on it.

p50 vs p95: What Each Metric Actually Tells You

MetricWhat it capturesWhere it misleads
Mean / averageOverall throughput feelOne long request can dominate it; describes no real user
p50 (median)The typical requestBlind to the tail — can look great while a slice of users is failing
p95Near-worst experience; the tailNoisy at low sample counts; does not say which request type caused it
p99Outage-adjacent outliersNeeds many samples; often dominated by retries and client bugs
TTFT p95Perceived responsiveness while streamingSays nothing about how long the full answer takes
Total p95Timeout budget and retry pressureIncludes output length you control via max_tokens

The Sample-Size Trap

Percentiles are order statistics, and order statistics are unstable when n is small. With 20 requests, p95 is essentially "the second slowest call you happened to make" — rerun the test and it swings wildly without anything changing on the server. Log the sample count next to every percentile and only alert when the count is high enough to mean something.

Two habits help. Aggregate over a rolling time window (say the last 15–30 minutes) rather than per-minute buckets, and keep p50, p95 and sample count on the same panel so you can separate a real regression from a thin bucket. If your traffic is genuinely low, alert on the p95 of a long window plus an absolute max-latency threshold instead of a per-minute p95.

Guardrails That Shrink the Tail

Most LLM tail latency is self-inflicted. These changes usually matter more than switching models.

  • Stream everything user-facing and render tokens as they arrive. You cannot fix TTFT by making total latency faster.

  • Set max_tokens deliberately. An uncapped completion is an uncapped latency budget.

  • Put stable instructions and reference material first in the prompt, variable content last. Providers that support prompt caching reward stable prefixes with cheaper, faster repeats — cache hits cost less than fresh input (current rates at aicreditsapi.com/deepseek-prices).

  • Use a request timeout shorter than your user's patience, then retry once with backoff and jitter. Log attempts as a metric: retries are a latency multiplier, not a fix.

  • Route by need. deepseek-v4-flash is the default for high-volume, latency-sensitive paths; deepseek-v4-pro is stronger and costs more, so reserve it for requests whose difficulty justifies the extra time — and measure it separately, because mixing models in one bucket produces a bimodal chart that neither p50 nor p95 summarizes well.

  • Reuse one client instance. Building a new HTTP client per request adds handshake time to every call and inflates p95 for free.

Instrument the Retry Path Too

This wrapper caps the time budget per attempt and records each try, so a bad tail becomes attributable instead of mysterious.

import os
import time

from openai import APIConnectionError, APITimeoutError, OpenAI, RateLimitError

client = OpenAI(
    api_key=os.environ["AICREDITS_API_KEY"],
    base_url="https://api.aicreditsapi.com/v1",
)

RETRYABLE = (APITimeoutError, APIConnectionError, RateLimitError)


def call_with_budget(prompt, timeout=20.0, max_attempts=2):
    trace = []
    for attempt in range(1, max_attempts + 1):
        start = time.perf_counter()
        try:
            response = client.chat.completions.create(
                model="deepseek-v4-flash",
                messages=[{"role": "user", "content": prompt}],
                timeout=timeout,
            )
            trace.append(
                {"attempt": attempt, "ok": True, "seconds": round(time.perf_counter() - start, 3)}
            )
            return response, trace
        except RETRYABLE as exc:
            trace.append(
                {
                    "attempt": attempt,
                    "ok": False,
                    "error": type(exc).__name__,
                    "seconds": round(time.perf_counter() - start, 3),
                }
            )
            if attempt == max_attempts:
                raise
            time.sleep(0.4 * attempt)
    raise RuntimeError("unreachable")


response, trace = call_with_budget("Name three uses for a message queue.")
retries = len(trace) - 1  # emit this next to your latency percentiles
print(trace, retries)
print(response.choices[0].message.content)

Ship the trace to your logs and emit retries as a counter. When p95 jumps, compare it against retry counts for the same window. If they move together, your tail is client-side and no provider change will fix it.

A flat p50 with a climbing p95 is not a provider problem until you have ruled out your own retries.

Where AiCredits Fits

AiCredits serves DeepSeek models through an OpenAI-compatible endpoint at https://api.aicreditsapi.com/v1, payable by card or PayPal with no Chinese phone number or bank account required — which matters if your monitoring runs from an overseas CI runner or server. Both deepseek-v4-flash and deepseek-v4-pro work with the same SDK, so the harnesses above run unchanged: swap the model string and compare the two distributions side by side. Off-peak usage costs less than peak, and cached input costs less than fresh input, both of which change how far your load-testing budget stretches. Current rates live at aicreditsapi.com/deepseek-prices.

FAQ

Should I alert on p50 or p95?

Both, for different reasons. A p50 regression means your typical request got slower — usually a systemic change such as prompt growth or a model switch. A p95 regression with a flat p50 means the tail got worse: retries, queueing, or a subset of heavy requests. Alert on p95 for user-facing expectations and on p50 for change detection.

How many samples before p95 is trustworthy?

More than most teams assume. Percentile estimates need a few hundred samples in the window before they stop jumping around; below roughly 50, p95 is close to your max. Track the sample count alongside the percentile and widen the window when traffic is low.

Why does p95 spike while p50 stays flat?

Usually client-side or workload-specific: retry storms, a subset of very long prompts, uncapped max_tokens, cold connections, or one noisy client. Segment by prompt type and retry count before blaming the provider.

Does streaming change how I should measure latency?

Yes. Report TTFT and total duration as separate series. TTFT reflects perceived responsiveness, total duration reflects timeout and retry budgets. Averaging 'time to complete' alone makes streaming apps look slower than they feel.

Do flash and pro need separate dashboards?

Yes. deepseek-v4-flash and deepseek-v4-pro differ in strength, speed and cost. Mixing them in one percentile bucket produces a bimodal distribution that neither p50 nor p95 summarizes well — tag every sample with the model name.

Is p99 worth tracking at all?

For high-volume endpoints it catches outage-adjacent behavior worth knowing about. For low-volume internal tools it is mostly noise. Always pair it with the sample count so nobody reads meaning into three slow calls.

Try Lint in 2 seconds

Wrote something? Paste it here for a free grammar check. No account needed.

More Tools →

Related Tools

Was this article helpful?

| Share on X Reddit Copy link

服务器宕机了?别等用户告诉你

Wakeless 梦哨 帮你 30 秒监控网站 / API / SSL 证书,宕机秒级告警到邮箱、飞书、Slack。免费档 30 个监控,永久免费,无需信用卡。

免费开始监控 →
💬
反馈意见 / Feedback ×