LESSON 67 ยท PRODUCTION GENAI

Latency

Learn how to make Generative AI applications feel fast by measuring response time, reducing unnecessary work, streaming output, and designing efficient production pipelines.

20 min readโ€ขIntermediateโ€ขGenerative AIโ€ขProduction

How GenAI Latency Works

UserSends a request
GatewayAuth + routing
RetrievalSearches useful context
ModelGenerates tokens
ToolsOptional external work
ResponseStreams back to UI
iImportant: Latency is not just model generation time. Network calls, retrieval, tool execution, queueing, retries, and application processing can all contribute to the time a user waits.
1

What Is Latency?

Latency is the time between an action being requested and the useful result becoming available. In a GenAI application, it is usually measured from the user's request until the answer starts or finishes arriving.

Key idea:A system can have a fast model and still feel slow if it performs too many sequential operations before the model starts generating.
2

TTFT vs Total Response Time

Two measurements are especially useful for streaming AI applications.

Time to First TokenTTFT

How long the user waits before the first generated token appears. Lower TTFT usually makes an application feel more responsive.

Time to Last TokenTTLT

How long it takes for the complete response to finish. This matters for tasks where users need the entire answer before continuing.

3

Where Does Latency Come From?

A production request can contain several latency components.

  • Network: Browser, API gateway, model provider, and database round trips.
  • Queueing: Waiting for an available worker or overloaded service.
  • Retrieval: Vector search, metadata filtering, and reranking.
  • Model: Time to start and generate output tokens.
  • Tools: APIs, databases, search, or business systems.
  • Retries: Failed calls can multiply the total request time.
4

Measure Before You Optimize

Start with a latency budget and measure every important stage. Do not optimize based only on how fast the model provider says the model is.

Trace the request

Record timestamps for gateway, retrieval, reranking, model calls, tool calls, and final response.

Track percentiles

Use p50, p95, and p99. An average can hide the slow requests that real users experience.

5

Python: Measure a Stage

Simple timing instrumentation helps identify which operation is actually slow.

</> Python
from time import perf_counter

start = perf_counter()

# Replace this with a real retrieval or model call.
result = "retrieved context"

elapsed_ms = (perf_counter() - start) * 1000
print(f"Stage latency: {elapsed_ms:.1f} ms")

In production, attach the measurement to a request ID so you can compare stages across real traffic.

6

Reduce Sequential Work

One of the biggest latency problems is performing independent operations one after another.

SlowSearch A โ†’ Search B โ†’ Tool C โ†’ Model
BetterSearch A + Search B in parallel โ†’ Model
Best when possibleStart independent work early and wait only when the result is required.
7

Parallelize Independent Calls

If two operations do not depend on each other, run them concurrently. This can reduce wall-clock time even when the individual operations are unchanged.

Example:An application may retrieve product documentation and customer account data independently. Waiting for one before starting the other adds unnecessary latency.
8

Python: Parallel Async Work

Python's async tools can start independent I/O operations together.

</> Python
import asyncio

async def retrieve_docs():
    await asyncio.sleep(0.3)
    return "docs"

async def load_customer():
    await asyncio.sleep(0.3)
    return "customer"

async def prepare_context():
    docs, customer = await asyncio.gather(
        retrieve_docs(),
        load_customer(),
    )
    return docs, customer

print(asyncio.run(prepare_context()))

The example simulates I/O. Real applications should use async-compatible clients for the services they call.

9

Streaming Makes AI Feel Faster

Streaming sends generated output to the user as it becomes available instead of waiting for the complete answer.

Without streaming

User waits โ†’ model generates โ†’ complete response arrives.

With streaming

User sees the first tokens โ†’ more tokens arrive โ†’ answer completes.

Important

Streaming improves perceived responsiveness, but it does not necessarily reduce total generation time.

10

Choose Faster Models When Quality Allows

Model capability, output length, and generation speed often trade off against one another. Select a model based on the quality target and measured latency, not marketing labels alone.

Simple requests

Classification, extraction, routing, and short transformations may not require a large reasoning model.

Complex requests

High-value reasoning may justify a slower model when the quality gain is meaningful.

11

Control Output Length

Generating more tokens takes more time. Ask for the amount of output the UI actually needs.

Example:A support card that needs a two-line status should not request a long essay. Short structured output can improve both latency and cost.
12

Optimize RAG Retrieval

Retrieval should return enough evidence for a correct answer without forcing the system to process unnecessary data.

  • Use appropriate chunk sizes.
  • Use metadata filters when the query has known constraints.
  • Keep the candidate set reasonable.
  • Use reranking only when its quality benefit justifies its latency.
  • Send focused context to the model instead of whole documents.
  • Measure retrieval latency separately from generation latency.
13

Cache Repeated Work

Caching can remove entire model or retrieval calls from the critical path when the same result can safely be reused.

Good cache candidates

Stable system instructions, repeated retrieval results, public answers, and expensive deterministic computations.

Use caution

Personalized answers, rapidly changing data, and sensitive information need careful cache keys, TTLs, and access controls.

14

Keep Context Small

Large prompts can increase processing time and make every request heavier. Keep only information that is relevant to the current task.

Practical rule:Do not automatically pass the entire chat history, all retrieved chunks, or every available tool description. Select what the model needs for this step.
15

Agent Latency Can Multiply

Agents may call a model and tools several times. A five-step sequential agent can feel much slower than a single model request.

PlanModel call
SearchTool call
AnalyzeModel call
VerifyTool or model call
AnswerFinal model call
Optimize:Limit unnecessary steps, parallelize independent tools, cache stable results, and stop as soon as the required outcome is achieved.
16

Queueing and Background Work

Not every AI task must block the user request. Reports, document ingestion, bulk embeddings, evaluations, and notifications can run asynchronously.

InteractiveKeep the critical path short.
BackgroundMove long-running work to a queue.
UIShow progress or notify when complete.
17

Timeouts and Retries

Retries can improve reliability but can also create large latency spikes. Use bounded retries, timeouts, and backoff.

Timeout

Stop waiting when a dependency exceeds the acceptable latency budget.

Retry policy

Retry only failures that are likely to succeed and cap the number of attempts.

18

Latency Budgets

Set a target for the complete user journey and divide it among the important stages.

Target2.5 s
Gateway100 ms
Retrieval300 ms
Model start700 ms
Generation1.2 s

These numbers are an example budget, not a universal benchmark. Choose targets from your product requirements and real measurements.

19

Perceived vs Actual Latency

Users care about how quickly the interface becomes useful. A progress state, streaming response, or immediate acknowledgment can improve perceived responsiveness while the full operation continues.

Actual

Total request duration from start to completion.

Perceived

How quickly the user sees useful progress or content.

Best practice

Improve both when possible. Do not use UI tricks to hide genuinely poor backend performance.

20

Latency and Cost Are Connected

Performance improvements can sometimes reduce cost because fewer retries, smaller prompts, fewer model calls, and less infrastructure work are required. But faster is not automatically cheaper.

Think in trade-offs:A more expensive model may reduce the number of retries or agent steps, while aggressive caching may improve latency but increase storage and invalidation complexity.
21

Production Observability

Track latency by endpoint, feature, model, customer segment, and workflow. Useful measurements include TTFT, total response time, stage duration, timeout rate, retry count, and error rate.

Trace ID

Connect every stage of one request.

Percentiles

Watch p50, p95, and p99 instead of only averages.

Breakdowns

Compare model, retrieval, tool, and network time.

Alerts

Detect regressions before users report them.

22

Common Latency Mistakes

  • Optimizing average latency while ignoring p95 and p99.
  • Calling independent APIs sequentially.
  • Sending huge prompts and entire documents.
  • Using reranking or tools without measuring their benefit.
  • Allowing unlimited agent loops.
  • Retrying every error without a timeout or backoff.
  • Measuring model time but ignoring retrieval and network time.
  • Improving perceived speed while leaving the actual system unreliable.
23

Mini Project: Build a Faster RAG Assistant

Step 1 โ€” Baseline

Measure TTFT, total response time, retrieval time, and model time.

Step 2 โ€” Reduce context

Improve chunk selection and remove irrelevant retrieved text.

Step 3 โ€” Parallelize

Run independent metadata or business-data lookups concurrently.

Step 4 โ€” Stream

Show generated tokens as they arrive.

Step 5 โ€” Cache

Cache safe repeated retrieval or deterministic work.

Step 6 โ€” Re-measure

Compare p50 and p95 latency while checking answer quality.

24

Quick Quiz

1. What does TTFT measure?

The time until the first generated token becomes available.

2. Does streaming always reduce total latency?

No. It mainly improves perceived responsiveness by showing output earlier.

3. Why parallelize independent calls?

To reduce wall-clock time by overlapping I/O work.

4. Why can RAG increase latency?

Retrieval, filtering, reranking, and larger context can add processing and network time.

5. Which percentile is useful for slow-user experience?

p95 and p99 are useful for identifying tail latency.

25

30-Second Recap

01Measure TTFT and total response time separately.
02Trace retrieval, model, tool, network, and queueing time.
03Parallelize independent operations and avoid unnecessary sequential steps.
04Use streaming to make responses feel responsive.
05Keep prompts, retrieval context, agent steps, and output lengths focused.
06Use budgets, timeouts, retries, caching, and observability in production.

Key Takeaways

  • GenAI latency is an end-to-end application problem, not only a model problem.
  • Measure p50, p95, p99, TTFT, and total response time to understand real user experience.
  • Parallelism, streaming, caching, smaller context, and efficient models are powerful optimization tools.
  • Production systems need explicit latency budgets, bounded retries, timeouts, and observability.