LLM Serving, Latency & Cost

LLM Serving, Latency & Cost

The ExampleCo assistant works during a small demonstration. At lunchtime, requests queue behind the provider’s quota. Some users retry repeatedly. The UI shows the first word quickly, but complete answers take 20 seconds, and the bill includes several failed attempts for each successful answer.

Serving is about delivering a validated result under load, not merely obtaining a model response once. Measure latency, capacity, reliability, quality, and cost together.

Managed API vs Self-Hosted Model

ChoiceWhat you gainWhat you own
Managed APIFast setup, provider-managed model servingQuotas, vendor dependency, data-handling review, per-usage cost
Self-hosted modelMore deployment and infrastructure controlHardware, runtime, capacity, updates, security, availability

Self-hosting does not automatically make a system cheaper, private, or accurate. Managed APIs do not automatically satisfy a company’s privacy requirements.

Start with the simplest option meeting quality, data-handling, quota, and latency requirements. Model availability, pricing, and limits change; verify them for the actual deployment.

Prefill vs Decoding

  • Prefill: Process the input context and prepare the model state used for generation.
  • Decoding: Generate output tokens, typically one step after another for an individual sequence.

Long input can increase prefill work; long output increases decoding work. Network delay, queueing, retrieval, and validation add latency outside both stages.

flowchart LR
    U["Request"] --> A["Admission and authentication"]
    A --> R["Retrieve and authorize evidence"]
    R --> P["Provider queue and prefill"]
    P --> D["Decode output tokens"]
    D --> V["Validate and recheck sources"]
    V --> O["Usable answer"]

An illustrative latency breakdown:

StageExample budget
Application and identity100 ms
Retrieval and source checks250 ms
Provider queue and prefill650 ms
Output generation2,500 ms
Validation and release checks200 ms
Total3,700 ms

These are teaching assumptions, not a model benchmark. Measure distributions, particularly tail latency under realistic load.

Three Different Time Measurements

MetricMeasures
Time to first byte/tokenWhen delivery starts
Time to model completionWhen generation finishes
Time to validated completionWhen the application has a usable result

If the UI streams immediately, users may perceive progress sooner. That does not reduce total model work or guarantee that the partial text is correct.

Streaming Is a Product Decision

Server-Sent Events (SSE) can deliver one-way text updates over HTTP. See real-time transport.

For streamed responses:

  • Mark partial content provisional.
  • Distinguish completion, refusal, cancellation, timeout, and disconnect.
  • Propagate cancellation to the provider when supported.
  • Do not assume a disconnected client stopped provider billing.
  • Do not treat partial structured output as executable arguments.
  • Decide what source checks can happen before delivery.

If policy requires checking final output and current source permissions before any answer text is released, buffer the answer. You can still stream safe progress events such as “searching policies,” but not unvalidated sensitive answer text.

Once a token is delivered, later revocation cannot retract it.

Capacity: Requests and Tokens Are Both Resources

Use ExampleCo’s admitted peak: 30 requests/second, with a planning mean duration of 4 seconds at that load. That is the same peak and the same in-flight estimate as the case study.

Average concurrent requests = arrival rate * average duration
                            = 30/s * 4 s
                            = 120

This is Little’s law for a stable system. It is not a guarantee of p99 capacity; add headroom and test queueing.

A provider might separately limit requests/minute and tokens/minute. Average tokens are not the quota. ExampleCo’s hard admission cap is 6,000 input tokens and 600 reserved output tokens. The 2,000 + 400 average is only the cost forecast.

Peak requests             = 30/s * 60 s = 1,800 requests/minute
Average token volume      = 1,800 * 2,400 = 4.32 million tokens/minute
Admission-cap token volume = 1,800 * (6,000 + 600) = 11.88 million tokens/minute

Size the provider token quota to the admission cap, or lower the cap and reject the oversized question before calling the model. Do not truncate mandatory policy text so that an average-sized quota appears to fit. Many providers reserve max_output even when generation stops early, so the 600 output tokens belong in the quota even though the average output is 400.

Actual quota accounting can differ. Check the provider’s rules, including reserved output or model-specific tokens.

Cost: Show the Arithmetic and the Assumptions

Use hypothetical rates:

  • Input: $1 per million tokens.
  • Output: $4 per million tokens.
  • Request: 2,000 input tokens + 400 output tokens.
Input cost  = 2,000 / 1,000,000 * $1 = $0.0020
Output cost =   400 / 1,000,000 * $4 = $0.0016
Model total per request             = $0.0036
10,000 requests/day * $0.0036        = $36/day

That $36/day figure is a smaller drill, not ExampleCo. At the same invented rates, ExampleCo’s 200,000 questions/day cost about $720 before retries and the rest of the path. The full arithmetic is in the case study.

That excludes embeddings, retrieval, reranking, storage, network, retries, and operational work. These are not provider prices.

The roadmap’s simpler example, 10,000 * $0.002 = $20/day, is valid only when $0.002 is the assumed average total cost per request. Do not mix assumptions from different estimates.

Use cost per successful task for product decisions:

all task-related spend / successfully completed tasks

A cheaper model can be more expensive per success if it needs many retries or manual corrections.

Reduce Waste Before Adding Infrastructure

ImprovementWhy it can helpWhat to verify
Select relevant passagesFewer input tokens and less distractionEvidence coverage does not fall
Ask for concise outputLess decodingRequired detail remains
Use the smallest adequate modelLower serving costQuality and safety gates pass
Remove duplicate tool callsLess unnecessary processingState remains correct
Batch offline workBetter throughputDelay is acceptable
Cache safe reusable resultsAvoid repeated workAccess and freshness are valid

A two-stage router that always calls an expensive classifier before generation may erase the savings it was intended to create. Measure the complete path.

Three Caches That Should Not Be Confused

CacheReusesImportant limitation
Application answer cacheA prior answer and source dependenciesMust enforce caller access, applicability, and freshness
Provider prompt/prefix cacheProcessing of repeated input prefixesProvider-specific behavior and billing
Model key/value cacheInternal attention state used during generationRuntime optimization, not a source-of-truth answer cache

An application answer-cache key or validation record may need:

tenant + verified applicability + access scope
+ normalized question + model/prompt versions
+ source versions + source/authorization epochs

Recheck dependencies before reuse. A semantic near-match is not enough: “entitlement” and “remaining balance” are related questions with different answers.

Admission Control and Bounded Retries

PSEUDOCODE
require_request_and_token_budget(caller)
slot = acquire_bounded_concurrency_slot(deadline)
if slot unavailable:
    return explicit_rate_or_capacity_error()

try:
    for attempt in [1, 2]:
        result = call_provider_with_deadline()
        if result.success:
            return validate_and_recheck_sources(result)
        if not result.retryable or attempt == 2:
            report_provider_failure(result)
        wait_bounded_backoff_with_jitter_within_deadline()
finally:
    release(slot)

The pseudocode intentionally allows at most two attempts. Use provider guidance for rate limits and do not retry permanent input errors.

Retries may repeat billable work even when no successful response was received. Count them against task budgets.

Outages Need Honest Behavior

  • Circuit breakers can stop repeated calls to a failing provider.
  • Bounded queues and concurrency limits prevent unbounded memory growth.
  • An approved fallback model needs its own evaluation and data-handling review.
  • Cached answers can be used only when their evidence and permissions are still valid.
  • If no safe fallback exists, return an explicit service error.

Do not turn a model outage into a fabricated unsupported policy response or a canned policy answer. Operational failure and missing evidence are different states.

See circuit breakers and back-pressure.

Trade-offs

ChoiceBenefitLimitation
Immediate answer streamingFaster visible progressCannot retract delivered text
Buffered validated answerStronger release checksHigher perceived wait
Large batchesBetter offline throughputQueueing latency
More contextMore available evidenceInput cost and prefill work
Aggressive cachingLower latency and spendAuthorization and stale-answer risk
Self-hostingMore runtime controlSignificant operational ownership

Test Your Understanding

Try answering before expanding. Explain the missing assumption, not just the vocabulary.

  1. The first token arrives in 200 ms. Is the answer latency 200 ms?
Only time to first token is 200 ms. The full answer and validation may take much longer. Report time to usable completion separately.
  1. Does streaming make generation cheaper?
Not inherently. It changes delivery timing. Cost depends on actual processing and provider billing, including whether cancellation stops generation.
  1. At 30 requests/s and four seconds average duration, what is average concurrency?
Approximately 120 in a stable system. This is the same planning mean as the case study. It is not a p99 capacity target; account for variability, queueing, and headroom.
  1. Why can a request-rate quota pass while a token quota fails?
A small number of long requests can consume many tokens. Model traffic has both per-request and per-token resource dimensions. ExampleCo’s average peak is 4.32 million tokens/minute, but the admission cap is 11.88 million. A quota sized from the average fails closed, or worse, forces silent truncation, exactly when evidence-heavy questions arrive together.
  1. With the hypothetical rates, what does one 2,000-input, 400-output request cost?
Input costs $0.0020 and output $0.0016, totaling $0.0036 before other services and failed attempts.
  1. Why can a cheaper model cost more per successful task?
It may require more retries, longer prompts, extra validation, or manual repair. Include all attempts and task-level costs.
  1. Can a cached Region A answer be reused for Region B because the question matches?
Not without verifying applicability. The same wording can require a different policy and answer.
  1. Is a provider prefix cache equivalent to an application answer cache?
No. Prefix caching reuses input processing; answer caching reuses an actual response and needs evidence and permission validity.
  1. The client disconnected. Can you assume no more tokens will be billed?
No. Propagate cancellation where supported and inspect actual usage. A client disconnect may not terminate provider computation.
  1. Should an invalid-input error be retried with exponential backoff?
Usually not. Backoff helps transient conditions, not an unchanged invalid request. Classify errors and surface permanent failures clearly.
  1. Why can unbounded retries worsen a provider outage?
They amplify traffic, occupy resources, increase cost, and delay recovery. Use bounded attempts, jitter, deadlines, and circuit breakers.
  1. Does self-hosting guarantee privacy?
No. Access controls, logging, backups, network boundaries, operators, and data retention still matter. Self-hosting changes ownership, not the need for governance.
  1. Why can large offline batches be unsuitable for chat?
Waiting to form a batch adds latency. Throughput-oriented scheduling and interactive response time are different optimization goals.
  1. A provider outage occurs. Why not return the last popular policy answer?
It may be wrong for the caller, stale, or unauthorized. Use only a validated eligible cached result, otherwise return an explicit service failure.
  1. Why revalidate cached source dependencies after a permission change?
The answer may expose content the caller can no longer use. Cache reuse must obey the same current authorization rules as a fresh response.
  1. Can a key/value cache establish that a policy is current?
No. It is an internal inference optimization. Active policy versions remain an application/source-of-truth concern.
  1. Why can doubling input increase latency even with identical output length?
Input processing, tokenization, provider queueing behavior, and attention work can increase. Output length is only one part of latency.
  1. What is wrong with sizing from average requests/day alone?
Daily average hides business-hour concentration and bursts. Size and test against the expected peak distribution and concurrent work.
  1. Can final authorization checks protect text already streamed?
They cannot retract delivered tokens. If the required guarantee is final permission checking before answer release, buffer answer text and stream only safe progress events.
  1. What is the first cost optimization to try in a noisy RAG prompt?
Remove irrelevant and duplicated evidence while preserving required support, then measure quality, token usage, and latency. This can improve both clarity and cost without new infrastructure.