RBRunbook
Study

Domains · Domain 6 · 8% of scored questions

Cost and Latency Optimization at Scale

About 5 of the 60 scored questions come from this domain. It has 2 skills:

Lessons

Skill

Cost Architecture at Scale

Cost architecture: read the usage data, then pull the levers in order

Cost work at fleet level starts from usage data, not from a favourite technique. Each response reports its token counts by type, and the usage and cost endpoints roll them up by workspace, API key and model. Read those first, then apply the levers in order: caching, batch for work nobody waits on, effort, and only then a second model.

Caching: what the three usage fields tell you

A cached request reports cache_read_input_tokens (prefix read from the cache), cache_creation_input_tokens (prefix written now) and input_tokens (only what follows the last breakpoint). In an agent loop most input should be cache reads. Anthropic's cost guide says that below about 80% you should look for something breaking the cache.

The cache is an exact prefix match in the order tools, then system, then messages. A change at one level invalidates that level and everything after it. Writes happen only at the block you mark. On a miss the API looks backward for entries that earlier requests wrote; it does not find stable content on its own.

What you seeLikely causeFix
A write on every request, no reads, requests seconds apartThe breakpoint sits on a block that changes each time (timestamp, queue position, the incoming message)Put the breakpoint on the last block that stays identical; move the changing text after it
Reads drop after a deployTools reordered or serialized differently, an edited system prompt, rewritten history, a different modelUse cache diagnostics; it reports the earliest divergence only, so fix it and check again
Requests match but reads are lowThe entry expired, or the prefix is under the minimum cacheable lengthChoose the 1-hour duration for gaps between 5 minutes and an hour, or keep the entry warm
Both cache fields are zero, no errorThe prefix is too short to cacheExtend the cached content past the minimum

The default lifetime is 5 minutes, refreshed free on each use and measured from the start of the request. The 1-hour duration costs more to write. If the prompt is used more often than every 5 minutes, stay on the default. If gaps often fall between 5 minutes and an hour, the longer duration pays. If gaps usually exceed an hour, it only raises the write price.

Adding a breakpoint does not repair a prefix that changes. A timestamp at the front of the system prompt turns every request into a full cache write however many breakpoints follow it.
Batch versus realtime

The Message Batches API charges half the standard price for every token. The trade is time: most batches finish within an hour, but the contract is up to 24 hours, and a batch can expire. Route work that no one is waiting on (evaluations, backfills, scheduled jobs) through batch and keep interactive paths synchronous. Batch has its own rate limits, so it also takes load off the Messages API limits. Cache hits inside a batch are best effort; because a batch can run longer than 5 minutes, use the 1-hour duration on a shared prefix. Results can come back in any order, so match on custom_id.

Routing, effort and cascades
  • Compare models on cost per completed task, not per token. A failed task still bills its tokens, then the retry.
  • Price the tail. A few hard tasks often carry most of the spend, so a forecast built on the median task undershoots.
  • Sweep effort on the current model before adding a second model. If costs are high and quality is fine, lower effort is the first thing to try.
  • When outcomes are checkable (tests, a verifier), run everything at a cheap setting and re-run only the failures at a higher one. This needs a trustworthy failure signal, and each failure costs two runs of wall-clock time.
  • max_tokens caps one response and is invisible to the model. Lowering it does not make the model economize; it truncates.
Budgets per tenant or team

Workspaces carry their own monthly spend limit and rate limits, enforced by the platform, and they cannot exceed the organization's limits. That makes a workspace the unit of hard isolation: one tenant or team that overruns is stopped without draining the shared pool. Usage and cost reports are for attribution and forecasting, not enforcement, because the data arrives late (the analytics endpoints typically refresh within hours). Batches may slightly overshoot a workspace spend limit because of concurrent processing.

An alert on a dashboard detects overspend after the fact. If the requirement is that a tenant must be stopped, the control has to sit in the request path: a workspace limit or a gateway check.

Sources
Prompt caching
Cache diagnostics
Batch processing
Optimizing for cost and intelligence
Choosing the right model
Workspaces
Usage and Cost Analytics API
Tool use with prompt caching

Skill

Latency Engineering

Latency engineering: find which part of the wait misses the target

A latency target is only useful once you know which wait it describes. Split every request into parts and measure each one before changing anything.

Two different numbers
  • Time to first token (TTFT): from sending the prompt to the first generated token. It is driven by how much input the model must process and by any thinking that happens before the answer.
  • Total latency: TTFT plus generation time. Generation time is roughly output tokens divided by output speed. In an agent turn, add tool execution time and one more model call per round trip.

Ask who is waiting. A person reading text cares about the first visible words. A service that parses the full response cares only about the total.

LeverImprovesDoes not improve
StreamingPerceived wait: text appears as it is generatedTotal time to the last token
Caching a long stable prefix, pre-warming itTTFT on requests that would otherwise reprocess the prefixGeneration time
Shorter requested outputTotal latencyTTFT
Lower effortTotal latency and often TTFT, through less thinking and fewer tool callsNothing for free: quality can drop, so check evals
Fast modeOutput tokens per second, at premium pricingTTFT
Running independent tool calls concurrentlyTool time within a turnModel time
Streaming does not make the response finish sooner. If the consumer is another service that waits for the whole body, streaming changes nothing; cut output tokens or thinking instead.
Cache checkpoints for latency

A cache hit lets the API resume from the cached prefix, which shortens TTFT for long prompts. The 5-minute and 1-hour durations behave the same for latency; the choice between them is about whether the entry is still there when the next request starts. Three facts decide most cases:

  • A cache entry becomes available only after the first response starts. Fifty parallel requests sent together all miss. Send one, wait for its response to begin, then release the rest.
  • Pre-warming writes the prefix before a user arrives. A request with max_tokens: 0 reads the prompt, writes the cache at the breakpoint and returns no output. The breakpoint must be on the last block shared with the real request, and the thinking and effort settings must match, or real traffic never hits the entry. It cannot be used with streaming or inside a batch.
  • Anything that invalidates the prefix costs latency as well as money. Changing top-level effort, switching speed, editing tools or the system prompt mid-conversation all force reprocessing. Where the model supports it, a per-message effort change keeps the cache; otherwise hold one effort level for the session.
Effort tuning

Effort controls how many tokens the model spends on thinking, tool calls and text. It is a behavioural signal, not a strict token budget. Lower effort means less thinking and fewer, terser tool calls, so it is the main control for speed inside one model. Use it per route: low for simple, high-volume or chat traffic, higher where evals show the quality is needed. Sweep levels on your own eval set and keep the lowest level that holds quality.

Lowering max_tokens to speed things up backfires when thinking is on. Thinking counts toward the cap, so a cap sized for the visible answer can end the response before any text is produced.
Parallel tool execution

One model response can contain several tool_use blocks. How you run them is your decision. Independent, read-only calls are usually safe to run concurrently, so the turn costs the slowest call rather than the sum. Calls with side effects, shared state or ordering requirements should run in order; if you skip a call after a failure, still return a result for it marked as an error.

Return one tool_result per call, all in a single user message, with results before any text. Sending each result in its own message teaches the model to stop issuing parallel calls, and round trips multiply. Turning parallel tool use off has the same effect on purpose: one call per response, more model calls per task.

Order of work
  1. Get a prompt that meets the quality bar first.
  2. Break the trace into TTFT, generation, tool time and round trips.
  3. Pick the lever that acts on the part that misses the target.
  4. Re-run quality evals after each change.

Sources
Reducing latency
Streaming messages
Prompt caching
Effort
Fast mode
Parallel tool use
Steering and cost control (thinking)
Fine-grained tool streaming

Sample questions

Sample question
A SaaS vendor serves 40 enterprise tenants with a contract-review assistant. All traffic goes through the vendor's gateway and uses one workspace and one API key. Over a weekend, one tenant's misconfigured bulk job consumed 61% of the organization's monthly spend limit. On Monday at 09:10 the organization limit was reached and requests for all 40 tenants failed until an admin raised it. Leadership's requirement is that a runaway tenant is stopped within its own budget, with no effect on the others, and that the stop does not depend on someone reacting to a report. Which change most directly meets that requirement?
  • AMove each tenant to its own workspace and set a monthly spend limit on each one
  • BIssue one API key per tenant in the shared workspace and set a spend limit per key
  • CBlock a tenant at the gateway once the cost analytics endpoint shows it over budget
  • DDivide the organization spend limit by tenant and email each tenant at 80% of its share
Show the answer and explanation

Answer:

  • Move each tenant to its own workspace and set a monthly spend limit on each one

Spend limits are set on workspaces and enforced by the platform, so a tenant in its own workspace is stopped at its own cap while the others keep working. A gateway block driven by the cost analytics endpoint looks like enforcement, but that data typically refreshes within 4 hours and can take up to 24, so a weekend bulk job overruns long before the block fires. Keys in a shared workspace give attribution; the documented spend and rate limits attach to the organization and to workspaces, not to a key. A per-tenant email at 80% is a notification that still relies on someone acting, and the pool stays shared.

Sample question
An insurer's claims-intake assistant answers adjusters in a web console. The console calls a backend service, which calls the model. The latency targets are first visible text within 2 s and the complete answer within 20 s, both at p95. One week of traces shows:
backend: request sent to first token generated   p95 1.1 s
backend: request sent to last token generated    p95 14 s
console: question submitted to first text shown  p95 14.3 s
output length                                    p50 880 tokens
instruction prefix                               6,000 tokens, uncached
Adjusters complain that the console is slow. Which change most directly brings the assistant inside its targets?
  • ASplit each answer into a 100-token verdict call followed by a separate detail call
  • BLower the effort level by one step on every request the backend sends to the model
  • CRelay the model's output events through the backend to the console as they are sent
  • DAdd a cache breakpoint at the end of the instruction prefix on every backend request
Show the answer and explanation

Answer:

  • Relay the model's output events through the backend to the console as they are sent

The model produces its first token at 1.1 s and its last at 14 s, so both model-side numbers are inside the targets. The console shows nothing until 14.3 s, which means the backend waits for the whole body. Passing the output through as it is generated puts text on screen shortly after 1.1 s. Caching the prefix shortens a first-token time that already meets the target and leaves the 14-second wait for visible text. A 100-token verdict call still takes about 1.1 s plus 1.5 s of generation at the observed rate of roughly 68 tokens per second, which misses 2 s, and it adds a second call. Lower effort may shorten the total, which already meets its target, but the first visible text would still arrive with the last token.

↑↓ move↵ openesc close