How do you benchmark time-to-first-token (TTFT) and tokens-per-second across cloud LLM endpoints? | A1Lab@HamzaM to AI & LLMEnglish • 4 days ago

How do you benchmark time-to-first-token (TTFT) and tokens-per-second across cloud LLM endpoints?

message-square
0

How TTFT and Tokens-Per-Second Benchmarking Works Across Cloud Endpoints

Benchmarking streaming LLM endpoints requires separating the prefill phase (network round-trip + queueing + prompt ingestion) from the decode phase (autoregressive token generation) using monotonic high-resolution timers (performance.now()).

  • Time-to-First-Token (TTFT): Measured from request dispatch (t_start) to the arrival of the first non-empty output token (t_first_token)—ignoring empty role/metadata initialization frames or [DONE] markers so initial connection headers do not artificially deflate latency.
  • Output Tokens-Per-Second (TPS / Decode Speed): Calculated over the decode window (total_output_tokens / (t_last_token - t_first_token)) rather than end-to-end latency, isolating generation speed from prompt prefill time.
  • Inter-Token Latency (ITL / TPOT): Measures the average gap between consecutive output tokens ((t_last_token - t_first_token) / (output_tokens - 1)), highlighting jitter or multi-tenant GPU contention during streaming.
  • Authoritative server token counts: Because one SSE chunk can contain multiple tokens or multi-token unicode characters, enabling stream_options: { include_usage: true } captures exact completion_tokens (including reasoning tokens) from the provider’s final usage chunk.

Steps to Benchmark Cloud LLM Endpoints Accurately

  1. Standardize prompt shapes and output budgets: Run identical input prompt lengths (for example, short 200-token chat prompts vs. 8k-token RAG prompts) with fixed max_tokens and temperature: 0, because TTFT scales directly with input token length.
  2. Warm up connections and run controlled concurrency sweeps: Discard initial TLS/connection-pool warmup calls, then test single-stream (concurrency = 1) and realistic production concurrency levels (5, 20, 50) to observe queueing and throughput degradation.
  3. Record high-resolution timestamps on meaningful chunks: Start performance.now() immediately before fetch/SDK invocation, capture t_first_token on the first chunk carrying actual content, reasoning, or tool_calls delta, and capture t_last_token on the final content chunk before [DONE].
  4. Compute percentiles (p50, p95, p99) across endpoints: Aggregate across multiple runs per provider/region and report median and tail percentiles (p95/p99) rather than single-run averages, since multi-tenant cloud endpoints exhibit periodic queueing spikes.

TypeScript Example: Multi-Endpoint Streaming TTFT & TPS Harness

import OpenAI from "openai";

interface EndpointTarget {
  name: string;
  baseURL?: string;
  apiKey: string;
  model: string;
}

interface SampleMetrics {
  ttftMs: number;
  decodeMs: number;
  endToEndMs: number;
  outputTokens: number;
  decodeTokensPerSec: number;
  itlMs: number;
}

function percentile(values: number[], p: number): number {
  const sorted = [...values].sort((a, b) => a - b);
  const idx = Math.min(sorted.length - 1, Math.floor((p / 100) * sorted.length));
  return sorted[idx];
}

async function measureSingleStream(
  client: OpenAI,
  model: string,
  messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[],
  maxTokens: number
): Promise<SampleMetrics> {
  const tStart = performance.now();
  let tFirstToken: number | null = null;
  let tLastToken: number | null = null;
  let serverOutputTokens = 0;
  let contentChunks = 0;

  const stream = await client.chat.completions.create({
    model,
    messages,
    max_tokens: maxTokens,
    temperature: 0,
    stream: true,
    stream_options: { include_usage: true },
  });

  for await (const chunk of stream) {
    if (chunk.usage?.completion_tokens) {
      serverOutputTokens = chunk.usage.completion_tokens;
    }

    const delta = chunk.choices[0]?.delta;
    const hasTokenPayload =
      Boolean(delta?.content) ||
      Boolean(delta?.tool_calls?.length) ||
      Boolean((delta as { reasoning_content?: string } | undefined)?.reasoning_content);

    if (hasTokenPayload) {
      const now = performance.now();
      if (tFirstToken === null) {
        tFirstToken = now;
      }
      tLastToken = now;
      contentChunks++;
    }
  }

  const tEnd = performance.now();
  if (tFirstToken === null || tLastToken === null) {
    throw new Error(`No output tokens received from model \${model}`);
  }

  const outputTokens = serverOutputTokens > 0 ? serverOutputTokens : contentChunks;
  const ttftMs = tFirstToken - tStart;
  const decodeMs = Math.max(1, tLastToken - tFirstToken);
  const endToEndMs = tEnd - tStart;
  const decodeTokensPerSec = (outputTokens / decodeMs) * 1000;
  const itlMs = outputTokens > 1 ? decodeMs / (outputTokens - 1) : 0;

  return {
    ttftMs,
    decodeMs,
    endToEndMs,
    outputTokens,
    decodeTokensPerSec,
    itlMs,
  };
}

export async function benchmarkEndpoints(
  targets: EndpointTarget[],
  messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[],
  runsPerTarget = 10,
  maxTokens = 256
) {
  for (const target of targets) {
    const client = new OpenAI({
      apiKey: target.apiKey,
      baseURL: target.baseURL,
    });

    // Warmup run (excluded from stats)
    await measureSingleStream(client, target.model, messages, 32);

    const samples: SampleMetrics[] = [];
    for (let i = 0; i < runsPerTarget; i++) {
      samples.push(await measureSingleStream(client, target.model, messages, maxTokens));
    }

    const ttfts = samples.map((s) => s.ttftMs);
    const tpsList = samples.map((s) => s.decodeTokensPerSec);

    console.log({
      endpoint: target.name,
      model: target.model,
      ttft_p50_ms: Number(percentile(ttfts, 50).toFixed(1)),
      ttft_p95_ms: Number(percentile(ttfts, 95).toFixed(1)),
      tps_p50: Number(percentile(tpsList, 50).toFixed(1)),
      tps_p95: Number(percentile(tpsList, 95).toFixed(1)),
    });
  }
}

Helpful Tips for Accurate Cross-Provider Benchmarks

  • Defeat prefix caching when measuring cold prefill TTFT: Cloud providers automatically cache identical prompt prefixes across repeated requests; prepend a unique nonce or vary realistic user context per run when benchmarking uncached prefill latency, or keep prefixes fixed when specifically testing prompt-cache hit speed.
  • Run benchmarks from the same cloud region as your production servers: Cross-continent network RTT (for example, South Asia or Europe to us-east-1) adds 120–250 ms directly onto every TTFT measurement and skews provider comparisons.
  • Account for reasoning tokens separately from visible text: Reasoning models emit internal reasoning tokens before visible answer tokens; decide explicitly whether your product metric measures time-to-first-reasoning-token (network responsiveness) or time-to-first-visible-content-token (UX responsiveness).