Chapter 3. Performance and cost optimization

Learning objectives

  • Break down the latency of a single request stage by stage and select the improvement point with the greatest effect.
  • Process streaming events correctly and distinguish between what streaming reduces and what it does not.
  • Arrange prompts to increase cache hits and calculate the break-even point of caching.
  • Select tasks whose requirements match Batch APIs and service tiers, and safely retrieve results.
  • Design model-tier routing and escalation conditions, and evaluate latency-cost trade-offs in terms of cost per task.

Introduction

One team received complaints that "responses are slow" and switched to the most expensive model. The responses became even slower, and the bill tripled. Another team cut their prompts in half to reduce costs; quality dropped, while latency remained virtually unchanged. Both teams shared the commonality of taking action before measuring. Latency and cost are the sum of multiple stages and items, and you only know which one is large by measuring them.

This chapter begins with measurement. It first examines how to divide latency into stages and the latency-reduction principles compiled by OpenAI, and continues through streaming to reduce perceived latency, prompt caching to reuse repeated inputs, Batch APIs and service tiers to process non-urgent work cheaply, and routing to select the right model for each request. Finally, it compares these methods against a single yardstick: cost per task.

Key concepts

Dividing latency into stages

The wait time felt by users is the sum of multiple stages. Application queueing, input preprocessing, model processing, tool execution, post-processing, and network delivery follow one after another. Model processing is also split into two parts: the phase of reading the entire input and the phase of generating output tokens one by one. Therefore, the metrics to measure are also divided into three.

Metric Meaning Primary determining factors
Time to first token (TTFT) From request until the first output chunk arrives Queue, input length, thinking time, cache hits
Output speed Generated tokens per second Model tier, service tier
Total response time Until the final token Output length × speed, number of tool round trips

From the user's perspective, one must also look at when the "first usable result" appears. Even if the first chunk arrives quickly, if the screen can only be rendered after a structured result is completed, perceived latency is close to the total response time. Because complaints come from the tail, look at p95 (the threshold for the slowest 5%) rather than the average.

Seven principles for reducing latency

OpenAI's latency optimization guide presents seven principles. This summary applies regardless of the provider.

Principle Key point
Process tokens faster Smaller models are generally faster and cheaper
Reduce output tokens Reducing output by 50% reduces latency by nearly 50%
Reduce input tokens Reducing prompts by 50% improves latency by only about 1–5%. The effect is small unless context is extremely long
Reduce the number of requests Combine sequential steps into a single prompt to reduce round trips
Parallelize Call steps that do not use each other's results concurrently
Make users wait less Streaming is the most effective. Showing progress stages also helps
Do not use LLMs as the default Handle tasks that can be precalculated or resolved with fixed UI without a model

The core point is that output dictates latency most heavily. Openings that repeat the question, verbose conclusions, and unnecessary full rewrites increase both latency and cost.

How streaming works

Streaming is a method of receiving responses in increments via Server-Sent Events (SSE). Just as a delivery's arrival time remains the same even after a dispatch notification arrives, streaming merely displays initial content quickly and does not reduce the volume of tokens to generate or the cost.

Anthropic streams send events in a fixed order: message_start → for each block: content_block_start, content_block_delta (multiple times), content_block_stop → message_delta → message_stop, with ping events potentially interspersed. When handling them, note the following:

  • stop_reason is null in message_start and is finalized in message_delta.
  • usage in message_delta is a cumulative value. Adding it up for each event results in overcounting.
  • Even after receiving an HTTP 200, an error event (e.g. overloaded_error) may still arrive. Relying solely on status codes for error handling will miss it.
  • If there is no need to handle events directly, use the SDK's accumulation helper (Python get_final_message(), TypeScript finalMessage()) to receive the completed message.

The OpenAI Responses API sends semantic events such as response.created, response.output_text.delta, response.completed, and error, while Gemini streams via the SDK's stream option or REST's alt=sse.

Designing the entire streaming path

Even if streaming is enabled on the API, users may still see a blank screen. This occurs because the effect of streaming disappears if intermediate layers buffer responses and deliver them all at once. Inspect the entire path:

  1. Turn off response buffering on reverse proxies and API gateways for SSE paths. Compression settings may also buffer chunks.
  2. Have the server flush received chunks immediately, but batch UI updates into suitable intervals (e.g. sentences, 100ms) to reduce browser load.
  3. If the user closes the window or cancels, terminate the upstream request as well using the HTTP client's cancellation signal (e.g. AbortController). Generating output to the end when no one is viewing it only incurs unnecessary costs.
  4. Consider whether results requiring post-processing can be handled chunk by chunk. OpenAI documentation warns that streaming makes output moderation difficult. Determine beforehand whether content may only be revealed after reviewing the entire response.
  5. Concatenate chunks for tool arguments or JSON, but execute and store them only after completion and after passing validation (Chapter 2).

Principles of prompt caching

Imagine that instead of rereading the same packet from the beginning at every meeting, you mark the part you already read and read only newly added pages. Prompt caching stores the result of processing the beginning of a request (prefix) and reuses it in subsequent requests. Consequently, if the prefix differs by even a single character, it cannot be reused from that point onward.

Caching is not a feature that stores and returns outputs. Responses are generated fresh every time, and OpenAI documentation also states that caching does not change how output tokens are generated. In this respect, it fundamentally differs from a response cache that reuses previous answers as-is (Going deeper). There are two benefits: inputs read from the cache are billed at a discounted rate, and input processing time is shortened, speeding up the first token.

Comparing caching across vendors

Item Anthropic OpenAI Gemini
How to enable Top-level cache_control (automatic) or block-level cache_control (explicit). Maximum of 4 breakpoints Enabled by default on supported models Implicit caching enabled by default on Gemini 2.5 and later models
Minimum length 512–4,096 tokens depending on model. If below, not cached without an error 1,024 tokens on GPT-5.6 and later 4,096 tokens on Gemini 4 Argon / 3.x, 2,048 tokens on 2.5
Retention time 5 minutes default, refreshed for free upon each use. 1-hour option available prompt_cache_options.ttl (30m default, 12h) on GPT-5.6 and later. Earlier models use prompt_cache_retention (in_memory, 24h. From 2026-05-29, default is 24h for non-ZDR organizations) Managed automatically by provider
Pricing Write 1.25x (5 min) / 2x (1 hour), read 0.1x (even lower on some recent models) Write 1.25x on GPT-5.6 and later, read mostly 0.1x (some models 0.05x) 95% discount on cached inputs for Gemini 4 Argon
Verification fields cache_creation_input_tokens, cache_read_input_tokens, input_tokens (after the last breakpoint) usage.input_tokens_details.cached_tokens Interactions API usage.total_cached_tokens, generateContent usageMetadata.cachedContentTokenCount
Rate limits Cache reads are not counted toward input tokens per minute (ITPM) on most models Cached inputs are also included in tokens per minute (TPM) limit —

When using cache in Anthropic, input_tokens refers only to tokens after the last breakpoint. Total input is the sum of the three values:

Total input tokens = cache_read_input_tokens + cache_creation_input_tokens + input_tokens

Gemini supports only implicit caching on the Interactions API and models from Gemini 4 Argon onward. Explicit caching, where caches are created and managed manually, is only available via the generateContent API on supported earlier models.

Prompt arrangement to increase cache hits

The common principle across all three providers is one: place static elements in front and dynamic elements in the back. Even a single line showing the current time placed at the very front will cause thousands of subsequent tokens to miss the cache entirely.

  1. Keep the order fixed. Anthropic builds the prefix in the order of tools → system → messages. Place tool definitions, static instructions, reference materials, and examples up front, and put time, user information, and questions at the end.
  2. Place breakpoints at the end of the static section. Placing a breakpoint on a block that changes every time will only repeat writes.
  3. Keep serialization stable. If the order of tool lists, JSON key ordering, or whitespace varies across requests, the prefix is different even if the content is identical. Generating tool lists from sets or hash maps causes ordering to fluctuate.
  4. Understand changes that break the cache. In Anthropic, modifying tool definitions invalidates the entire cache, while modifying tool_choice or adding/removing images invalidates the message-portion cache. Modifying top-level effort or output_config.format also invalidates the cache.
  5. Check the minimum length. If the prefix falls short of the model's minimum length, it will silently fail to cache even if marked.
  6. Measure. Compare the cache read ratio before and after deployment, and use tools like Anthropic's cache diagnostics that reveal where prefixes diverged between consecutive requests.

In OpenAI, allowed_tools, which leaves the tool list intact and alters only the invokable scope, is advantageous for preserving the cache. prompt_cache_key affected only routing in earlier models, while on GPT-5.6 and later it is primarily used for aggregating customer-specific cache usage. Because models from GPT-5.6 onward place breakpoints at the end of recent messages by default, if the end portion changes every time, inserting prompt_cache_breakpoint at the end of the static portion is necessary to score hits. Anthropic caches are not shared between organizations and are also partitioned by workspace in the Claude API.

Break-even point of caching

Writing to cache is more expensive than standard input, so there must be sufficient reuse to be advantageous. Let us calculate using Anthropic multipliers, setting the prefix processing cost to 1.

Number of requests (within retention time, relative cost: 1 time without cache = 1.00) No cache 5-minute cache 1-hour cache
1 1.00 1.25 2.00
2 2.00 1.35 2.10
3 3.00 1.45 2.20
10 10.00 2.15 2.90

Based on a read multiplier of 0.1x, a 5-minute cache is beneficial starting from the second request within the retention time, and a 1-hour cache from the third (models with lower read multipliers offer even greater savings). Conversely, if the interval between requests is longer than the retention time, writes occur every time, making a 5-minute cache 25% more expensive and a 1-hour cache 100% more expensive than no cache. In such cases, it is better to choose a longer retention time or disable caching. Because retention time is measured from the moment a request starts, factor in that requests taking longer to generate responses will reduce the remaining time accordingly. There is also a throughput advantage. On most Anthropic models, cache reads do not count toward ITPM, so higher hit rates allow processing more input within the same limit.

Batch APIs

Packages that do not require same-day delivery are sent via inexpensive standard mail. Batch APIs aggregate bulk requests that do not require immediate responses, process them asynchronously, and discount the price.

Item OpenAI Batch API Anthropic Message Batches API Gemini Batch API
Discount 50% 50% 50% relative to standard
Processing time 24-hour window Mostly within 1 hour; expires if not completed within 24 hours Target 24 hours; expires after 48 hours
Scale 50,000 requests per batch, 200MB input file 100,000 requests or 256MB Inline under 20MB, file up to 2GB
Result retention Output file deleted 30 days after completion 29 days after creation 6 weeks default
Matching results custom_id custom_id User-defined key

OpenAI and Anthropic state that the order of results may differ from the input order, so always match them using identifiers. Although the Gemini API reference explicitly specifies that results arrive in the input order, matching by key is safer so that the same code works across providers. Anthropic validates requests asynchronously, meaning format errors are only discovered after the batch finishes. They recommend testing a single request in the same format using the Messages API first. Billing for failed requests also differs. In Anthropic, errored, canceled, or expired requests are not billed; in OpenAI, uncompleted requests are canceled upon expiration, and only completed requests are billed. Although caching can be used alongside batches, Anthropic notes that cache hits within a batch operate on a best-effort basis and recommends a 1-hour cache for shared context. Gemini batch documentation explains that context caching fees apply to cache hits, so verify actual unit prices in model-specific price sheets. Batch limits are managed separately from synchronous API limits.

Selecting service tiers

Even for the same model, you can choose which tier processes the request.

Tier Example Characteristics
Slower but cheaper tier OpenAI Flex (service_tier: "flex") Batch API pricing, slower response. Returns a 429 error with Resource Unavailable if capacity is insufficient (no charge). Documentation examples extend SDK timeouts from 10 to 15 minutes
Faster but more expensive tier OpenAI Fast mode (formerly priority processing, service_tier: "fast") Per-token surcharge. If traffic surges abruptly, some requests are downgraded to standard, displaying service_tier: "default" in the response
Priority capacity Anthropic Priority Tier (service_tier), fast mode on select Opus models (speed: "fast") Check usage.service_tier in the response to verify priority capacity usage. Fast mode has separate rate limits. Fast mode for Opus 4.8 is deprecated and will be removed on 2026-11-30

Choosing a tier is a question of the value of time. Send tasks that can afford a delay of a few minutes, such as evaluation runs or data enrichment, to cheaper tiers; send only the portions exceeding latency targets on paths where customers are waiting to faster tiers. If using a fast tier, record the actual service tier indicated in the response to monitor the downgrade rate.

Model-tier routing and escalation

Sending every request to the largest model is like using a heavy-duty truck for neighborhood errands. Routing directs requests to different models depending on their nature, and escalation reprocesses a request with a higher-tier model when a smaller model's results fall short of standards.

Method Decision basis Caveats
Rule-based routing Task type, input length, customer tier Simple and fast. Misses requests outside rules
Classifier routing Smaller model classifies difficulty and intent Latency of classification itself and misclassification cost
Validation-based escalation Escalates to higher-tier model if smaller model results fail schema or business validation Adds cost and latency proportional to the failure rate

Do not delegate escalation to confidence scores self-reported by the model. Confidence and correctness do not always align. Make decisions based on verifiable signals (passing schemas, including mandatory facts, absence of prohibited expressions), and measure quality, latency, and cost separately for each path using evaluation sets. For reasoning models, route reasoning effort in the same manner.

Evaluating latency-cost trade-offs

Each approach gains different advantages and makes different sacrifices.

Approach Latency Cost Sacrifices
Streaming Reduces perceived latency No change Implementation complexity, timing of moderation
Prompt caching Shortens time to first token Discounts repeated inputs Prompt structure constraints, write surcharge
Output reduction Substantially decreases Decreases Redesigning response format
Batch / cheaper tiers Substantially increases Decreases Immediacy
Faster tiers Decreases Increases Surcharges, managing downgrades
Routing to smaller models Generally decreases Decreases Escalation design, path-by-path evaluation

The basis for comparison is not cost per call, but cost per task.

Cost per task = (Cost of all calls + Retry/escalation cost + Human review cost) ÷ Number of tasks passing quality standards

Even if a model costs half as much per call, it represents a net loss if retries and human corrections triple. Determine the response deadline and failure cost first, and choose the combination that yields the lowest cost per task within those bounds.

Regulating thinking with effort and aligning with caching

Anthropic's recent models do not determine reasoning quantity via token budgets. Because it uses an adaptive approach where the model determines whether to think and how deeply to think on a per-request basis, settings like a reasoning token budget do not exist at all. The primary means to regulate thinking is effort. Manual extended thinking using thinking.type: "enabled" and budget_tokens became deprecated in Opus 4.6 and Sonnet 4.6, and subsequent models do not accept this configuration. Opus 5.5 cannot even turn off adaptive thinking.

Effort has five levels: low, medium, high, xhigh, and max. As of 2026-11-01, top-level effort is a GA feature used without beta headers, and only per-message effort remains in beta. Leaving the value blank applies the model-specific default.

Model Default effort
Fable 5.1, Sonnet 5.5 high
Opus 5.5, Haiku 5.5 medium

There is an easy-to-overlook rule on the cost side. Because the resolved effort value enters the prompt, changing effort between requests invalidates cache breakpoints. If routing by effort, set the value when starting a conversation and keep it constant across requests sharing the same cache.

When migrating a Sonnet 4.5 path—whose support ended on 2026-11-30—to Sonnet 5.5, one support team deleted budget_tokens but left effort blank. Once the default value of high took effect, thinking occurred frequently, slowing down responses. A rule that raised effort to max mid-conversation when difficult questions arose was also problematic, because new cache writes occurred on every turn where effort was raised. The team explicitly specified medium for general inquiries, identified difficult inquiries on the first turn, and locked them to high through the end of the conversation.

Calculating combined cache read rates and batch discounts

Anthropic's cache read price is determined by multiplying the base input unit price by a model-specific multiplier. As of 2026-11-01, multipliers fall into three tiers:

Model Cache read multiplier
Fable 5.1, Mythos 5.1 0.025x
Opus 5.5, Sonnet 5.5 0.05x
Other models 0.1x

Because Sonnet 5.5 charges $2 per million input tokens and $10 per million output tokens, cache read is $0.10. The minimum cache length is 512 tokens for Opus 5.5, Sonnet 5.5, Haiku 5.5, Fable 5.1, and Mythos 5.1 alike. Among earlier models, some require longer minimum lengths.

Even if the read multiplier decreases, the break-even request count does not change. Because a 1-hour cache incurs a 2x write multiplier, even with a 0.05x read multiplier, the total through the second request is 2.05, making it more expensive than no cache (2.00). What increases is the extent of savings when reuse is frequent.

The 50% discount of the Message Batches API applies to both input and output, overlapping with the cache multiplier. Running a batch with Sonnet 5.5 results in a cache read price of $0.05 per million tokens and an output price of $5.

Suppose a legal team generates summaries nightly with Sonnet 5.5 batches, providing a 4,000-token review guideline and contract texts (averaging 6,000 tokens). Output averages 800 tokens. When the guideline is read from cache, the cost per request is $0.0002 for the guideline, $0.006 for the contract text, and $0.004 for the output. Even if the guideline is cut in half, the cost per task remains virtually the same. The areas to address are contract text preprocessing and summary length. Because cache hits within a batch operate on a best-effort basis, verify actual hits via usage fields.

Distinguishing between OpenAI cache retention and response storage

Starting 2026-05-29, in organizations not using Zero Data Retention (ZDR), the default value of prompt_cache_retention changed from in_memory to 24h. Requests leaving this setting blank are assigned the 24h policy. This change does not apply to ZDR organizations. Because cache retention duration varies by organization even with identical code, measure cost estimates within the actual operating organization.

Do not confuse cache retention periods with data storage periods. Prompt cache is a mechanism that temporarily retains and reuses the processing results of a request prefix. Responses and conversation history have separate storage rules. Response objects are stored for 30 days by default, but Conversation objects and items within them do not follow this 30-day TTL.

One edtech startup assumed that because cache retention was 24h, student conversations would also disappear after one day. In reality, items accumulated in Conversation remained even after 30 days had passed. Retention periods for personal information should be designed not via cache settings, but by determining when to create and delete response and conversation objects.

When planning throughput, also consider usage tiers. OpenAI rate limits are measured using metrics such as RPM, RPD, and TPM, and tiers are divided into Free, Build, Launch, and Grow. Cumulative credit purchases of $5, $100, and $500 serve as the thresholds separating tiers. Because cached inputs are also included in TPM, increasing hit rates does not increase available TPM headroom.

Going deeper

When response caching is dangerous

Response caching returns previously generated answers as they are. When there are many identical questions, latency and cost can be virtually eliminated. The approach of returning the same answer when questions have similar meanings despite slight differences in phrasing is called semantic caching, which finds previous questions using embedding similarity. As powerful as it is, the risks are also distinct.

  1. Personalization and permissions. If user-specific information is mixed into an answer, that answer may be delivered to someone else. Include the organization, permissions, language, and data version in the cache key, or do not use it for personalized answers.
  2. Freshness. If source documents change, cached answers become incorrect answers. Include document versions in the key, and invalidate corresponding entries upon revision.
  3. Similarity threshold. If the threshold is low, the same answer will be returned for questions that are similar yet different, such as "refund eligibility period" and "exchange eligibility period." Determine the threshold using an evaluation set that collects false-positive cases.
  4. Mutating operations. Do not cache requests that require executing tools.

Prompt caching does not carry these risks because it generates output anew each time. The two forms of caching are not in competition; they exist at different layers. Use response caching for selected questions with predetermined answers, such as guidance on established information, and use prompt caching across the rest of the conversation.

How to fairly compare optimization experiments

There are common cases where optimization effects are misinterpreted. First, measuring with mixed cache states. The first request is slow and expensive because the cache is empty. Measure the empty cache state and the populated cache state separately. Second, failing to measure quality at the same time. Reducing output or switching to a smaller model reduces latency and cost, but can degrade quality. Hold the same evaluation set and passing criteria fixed. Third, ignoring load. Because latency distributions vary depending on the number of concurrent requests, measure p95 at concurrency levels close to the actual peak. Fourth, making multiple changes all at once. If you change the model, prompt, and cache placement simultaneously, you cannot know what caused the effect. Adhere to the principle of one measurement per change, and record results in cost per task and p95.

At work

Wavecrest Language Institute: The identity of the 14-second blank screen

The online language school 'Wavecrest Language Institute' proofread English compositions written by students. It took an average of 14 seconds from submission for results to appear, during which the screen remained blank. The operations team suggested switching to a higher-tier model, but Assistant Manager Tak, a developer, first measured the segments.

Segment Average
Server queue and preprocessing 0.3 seconds
Time to first token 1.7 seconds
Output generation (average 950 tokens) 11.2 seconds
Screen delivery 0.8 seconds

Streaming on the API side was already enabled. However, the in-house API gateway relayed SSE with response buffering turned on, so the browser received nothing until completion. Furthermore, most of the latency came from output generation. The model was rewriting the entire composition and appending lengthy explanations for the edits afterward.

Assistant Manager Tak changed two things. Buffering was turned off on the gateway's SSE path, and the response format was changed to a list of "sentences requiring correction, the corrected sentences, and a single-line reason." Full rewrites were made to be requested separately only when a student wanted one. The average output decreased from 950 tokens to 340 tokens. The time for the first correction item to appear became 2.1 seconds, full completion took 5.6 seconds, and costs dropped by 60%. Correction accuracy based on the evaluation set remained unchanged.

There were also rejected proposals. The higher-tier model had a slower generation speed. The proposal to reduce examples in the prompt was not attempted because the input was only around 2,000 tokens, which was expected to have virtually no effect.

Open Fields Distribution: Splitting review replies into three routes

The agricultural produce online mall 'Open Fields Distribution' generated draft replies for approximately 9,000 product reviews per day. Processing all reviews with synchronous APIs and higher-tier models caused costs to increase. Company policy mandated replying within 48 hours for regular reviews, and within 30 minutes for 1- to 2-star complaint reviews.

Platform Engineer Senior Manager Wi divided the routes by response deadline.

  1. Complaint reviews (approximately 11%) were sent through the synchronous route. A smaller model generated a draft, and a validator inspected essential elements (apology, action guidance) and prohibited elements (promising compensation amounts, asserting unverified causes). If inspection failed, it was escalated to a mid-tier model. The escalation rate was 14% in the first week.
  2. Regular reviews were submitted twice a day via the Batch API. The review ID was supplied as custom_id to match results, and only items that expired or encountered errors were resubmitted in the next batch.
  3. Reply guidelines and tone examples (approximately 3,000 tokens) were fixed at the front of the prompt, while the review body and product information were placed at the end.

The team compared results by cost per task. When factoring in the review time for drafts that humans had to correct, the option of processing all reviews with a small model had the lowest call cost, but human revision time for complaint reviews increased, resulting in a higher cost per task. The cost per task for the final setup was 31% of the original. They also reviewed response caching to reuse previous replies for similar reviews, but did not adopt it because replies varied depending on order history and product status.

Common mistakes

  • Streaming reduces cost. It only reduces perceived latency; generated tokens and costs remain the same.
  • Cutting the prompt in half cuts latency in half. Latency is determined by output length. The latency reduction effect of shrinking input is usually small.
  • Increasing cache retention time increases the hit rate. If the prefix differs every time, it will not hit regardless of retention time. Fix ordering and serialization first.
  • Simply attaching cache_control caches it. If it falls short of the minimum length per model, it silently fails to cache without any error. Verify with the usage field.
  • Batch results arrive in input order within a few hours. OpenAI and Anthropic do not guarantee order, and with any provider, the turnaround time is determined only within the promised window (such as up to 24 hours). Pair results with identifiers and prepare for expiration.
  • Cache reads are never subject to rate limits anywhere. While Anthropic does not count them toward ITPM for most models, OpenAI includes cached input in TPM.
  • Starting with a smaller model is always cheaper. Decisions must be made based on cost per task, including escalations, retries, and human corrections.

Summary at a glance

  • Measure latency by breaking it down into TTFT, generation speed, and total time, evaluating at p95. Output length is the largest variable.
  • Streaming is for perceived latency. Examine the entire path, from gateway buffering and cancellation propagation to inspection timing.
  • Anthropic streams: stop_reason is in message_delta, usage is cumulative, and error events can occur even after a 200 response.
  • Caching reuses prefixes. Place static content at the front, dynamic content at the back, fix serialization, and verify minimum lengths.
  • Anthropic 5-minute cache breaks even starting from the second use; 1-hour cache breaks even starting from the third use (based on 0.1x read pricing). If the interval is longer than the retention time, it results in a net loss.
  • Batch offers a 50% discount across all three providers. OpenAI and Anthropic do not guarantee order. Pair with identifiers and prepare for expiration.
  • Processing tiers: cheaper tiers trade off speed, while faster tiers require surcharges and downgrade management.
  • Escalations in routing should rely on verifiable signals. Comparisons should be made by cost per task.

Check the official docs

Self-check

3-1. Define the three metrics to distinguish when measuring the latency of a single request, and state the reason for examining p95 instead of the average.

3-2. Give two reasons why a user might see a blank screen even when streaming is turned on in the API, and state the items to check along the streaming path.

3-3. When using Anthropic's 1-hour cache (write 2x, read 0.1x), calculate how many times the same prefix must be used within the retention time to yield a net benefit, and compare this with the 5-minute cache (write 1.25x).

3-4. State what prompt caching and response caching each reuse, and explain the risks and countermeasures when using response caching for answers containing user-specific information.

3-5. In model tier routing, give three signals to use as promotion conditions instead of the model's self-confidence score, and explain the impact of the promotion rate on the cost per task.

3-6. For three tasks with response deadlines of immediate, 4 hours, and three days, create a decision table selecting the processing path (synchronous, processing tier, batch) and model tier, and state the rationale for each choice.

Hands-on tasks

Exercise

Latency decomposition measurement (45 minutes)

  1. Insert stage-by-stage timers into a feature in production or under practice. Measure queue/preprocessing, first token, output completion, post-processing, and screen delivery separately.
  2. Run the same 20 inputs with streaming turned off and on respectively, and record them along with the number of output tokens.
  3. Create one more version that reduces output by changing the response format, and run the same 20 inputs. Also record whether each passes the quality criteria.

Done when: The TTFT, total time p95, average output tokens, and quality pass rate of the three versions are presented in a single table, and the change that had the greatest effect is explained with figures.

Exercise

Cache placement and break-even experiment (45 minutes)

  1. Create a prompt consisting of fixed instructions that exceed the minimum cache length and a short question.
  2. In Version A, place the current time at the very beginning; in Version B, place the current time at the very end. In both versions, place a cache breakpoint at the end of the fixed section (Anthropic cache_control, and for OpenAI GPT-5.6 onwards, prompt_cache_breakpoint).
  3. Send the same question five times at 1-minute intervals with each version, and record the cache-related usage fields.
  4. Calculate the input costs of both versions using the price multiplier of the provider used, and also calculate the cost when the request interval becomes longer than the retention time.

Done when: The cache read/write tokens and costs for both versions are shown in a table, and the reason for the difference as well as the break-even number of requests are each explained in a single sentence.