Optimize cost and resources
Measure unit economics and choose model, context, caching, batching, quota, and scaling strategies without hiding quality loss.
- Lesson
- d4-lesson
- Practice pool
- d4-questions
- Application
- aip-l07
Balance quality, tokens, throughput, latency, caching, scaling, quotas, resilience, observability, and cost across the whole application.
Measure unit economics and choose model, context, caching, batching, quota, and scaling strategies without hiding quality loss.
Measure and improve end-to-end latency, throughput, token use, retrieval, concurrency, resilience, and user-perceived responsiveness.
Observe application, model, retrieval, tool, safety, business, reliability, and cost signals with actionable ownership.
Optimize the cost and latency of a successful, safe task—not the price of one model call. End-to-end behavior includes request handling, retrieval, reranking, context construction, model invocation, guardrails, tool calls, retries, validation, storage, and human review. A cheaper call that produces more failures or retries can increase unit cost. A faster response that omits required evidence is not a performance improvement.
Establish a baseline before changing architecture. Measure representative workloads and keep quality and safety gates fixed while comparing cost or speed.
| Objective | Required judgment | Proof |
|---|---|---|
| 4.1 Optimize cost and resources | Measure unit economics and select model, context, cache, batch, quota, and capacity strategies | Cost per successful task improves without violating quality or safety thresholds |
| 4.2 Optimize performance | Diagnose end-to-end latency, throughput, tokens, retrieval, concurrency, resilience, and perceived responsiveness | A layer-level trace shows the constrained component and verified improvement |
| 4.3 Implement monitoring | Observe application, model, retrieval, tool, safety, business, reliability, and cost signals with ownership | Alerts connect a breached objective to an actionable runbook and owner |
Define service-level indicators for availability, end-to-end latency, time to first token, completion latency, throughput, throttle rate, retry rate, malformed output, retrieval success, grounding, tool success, safety intervention, user abandonment, and task completion. Set objectives from user and business needs. Do not alert on every metric; alert on symptoms or leading signals that require action.
Use correlation IDs to join application, retrieval, model, tool, and business events. Emit privacy-safe structured logs and traces. Record model and configuration version, token counts, latency by layer, retry reason, cache status, guardrail outcome, tool status, and final task result without copying sensitive content by default. Sampling can control volume, but critical safety and transaction events may require complete records.
Calculate cost per successful business outcome. Include input and output tokens, embeddings, vector storage and queries, reranking, guardrails, provisioned or reserved capacity where used, compute, data transfer, logs, retries, failed tasks, and human review. Allocate cost by application, environment, tenant, feature, or owner using tags and application telemetry where possible.
Choose the smallest approved model that meets the evaluation threshold. Route by task complexity only after testing routing errors. Reduce unnecessary instructions, duplicate context, retrieved noise, and overly large outputs. Summarize or precompute stable context with validation. Use prompt caching or application caching only when supported and safe; cache keys must include every input that affects authorization and output. Never share cached protected content across tenants.
Batch noninteractive work and control concurrency. Queue bursts rather than allowing unbounded retries. Request quotas based on measured demand and plan for provider limits. Provisioned throughput or similar capacity can improve predictable performance for suitable demand, but idle capacity can cost more than on-demand use. Measure utilization and re-evaluate commitments.
Break latency into client, network, authentication, retrieval, reranking, context assembly, model queue, time to first token, generation, guardrail, tool, validation, and persistence. Optimize the dominant constrained layer. Reducing model output tokens will not fix a slow vector query. Increasing concurrency can worsen throttling or downstream saturation.
Streaming improves perceived responsiveness but needs a policy for partial output, safety checks, cancellation, and downstream clients. Parallel retrieval or tool calls can reduce latency when independent, but increase cost and failure combinations. Use deadlines and cancellation so abandoned requests stop consuming resources.
Design explicit failure modes. For throttling, use backoff, jitter, quotas, queues, and load shedding. For model unavailability, decide whether an approved fallback preserves capability, Region, privacy, and safety requirements. For retrieval failure, abstain or use a clearly bounded alternative rather than inventing an answer. Circuit breakers can prevent cascading retries. Dead-letter queues preserve failed asynchronous work for owned remediation.
Monitor four layers together:
Quality monitoring requires representative sampled evaluation, not only infrastructure metrics. Model, prompt, corpus, user population, or task drift can change behavior without an HTTP error. Define release and runtime thresholds, review cadence, owner, and rollback or pause action.
| Symptom | Investigate first | Possible response |
|---|---|---|
| High time to first token | Request queue, model capacity, context size, Region | Reduce unnecessary context, adjust capacity, or route approved traffic |
| Long total latency | Output length, tools, validation, downstream writes | Bound output, parallelize safe independent work, set deadlines |
| Rising cost per task | Tokens, retries, model mix, cache, failed work | Fix retries, route by validated complexity, reduce unused context |
| Poor quality after cheaper routing | Router errors and per-class evaluation | Tighten routing or restore the higher-capability model |
| Quota failures | Concurrency, retry storm, demand forecast, downstream limits | Queue, back off, request quota, shed low-priority work |
| Stable infrastructure but declining outcomes | Corpus, prompt, model, user or task drift | Run evaluation, compare versions, refresh data, roll back |
A RAG assistant meets quality targets but p95 latency is eight seconds and cost per completed task doubled after adding reranking and longer context.