Machine Learning pathway increased my salary by 40%
Cost & Latency Optimisation for LLM Applications
Make AI applications economically and experientially viable: token economics, caching, routing, streaming and the measurement that shows where the money actually goes.
Executive Overview
LLM applications have two hard constraints: cost per unit of work and perceived latency. Both are governed by architecture rather than by model choice alone. Cost is driven by input tokens (system prompts, retrieved context, history), output tokens, retry volume and model tier; latency is driven by time to first token, generation length and the number of sequential model calls. The effective levers are prompt and context trimming, caching of stable prefixes and repeated queries, routing easy requests to smaller models, parallelising independent calls, streaming so users see progress, and batching where interactivity is not required. None of these can be tuned without attribution: if cost is not measured per feature, per task and per tenant, optimisation becomes guesswork.
Why It Matters in 2026
Pilot economics rarely survive scale. A feature costing a few cents per interaction in a demo becomes a monthly budget line at production volume, and a two-second delay becomes abandonment in consumer flows. Optimisation also improves quality, because routing and trimming force teams to define what each task actually needs, and caching reduces variance. The organisations that ship AI features profitably are the ones that instrument cost and latency from the first release and treat them as product metrics.
Enterprise Relevance: Unit economics decide whether an AI feature survives pilot. Cost per task and time to first token are the two numbers executives and users both judge.
Learning Outcomes
- Attribute tokens, cost and latency per feature and tenant
- Reduce cost through trimming, caching and routing
- Improve perceived latency with streaming and parallelism
- Set quotas and degradation behaviour per tenant
- Compare designs on cost per completed task
Token Economics
Every call pays for input and output separately, at different rates per model. Long system prompts and retrieved context dominate input cost, while verbose answers dominate output. Attribution per feature and task is the prerequisite for any optimisation.
Caching Layers
Provider prompt caching discounts stable prefixes, semantic caching returns stored answers for repeated queries, and application-level caching covers expensive derived artefacts. Cache design changes cost profiles more than model swaps.
Routing
A classifier or rule set sends simple requests to small fast models and escalates only hard ones. Routing typically cuts cost substantially with a small quality cost, provided the escalation path is evaluated.
Streaming and Perceived Latency
Time to first token shapes user perception more than total completion time. Streaming, progress indicators and speculative prefetch make the same backend latency feel acceptable.
Concurrency and Batching
Independent model calls should run in parallel; non-interactive workloads should batch. Sequential chains that could be parallel are the most common avoidable latency defect.
Architecture & Design
An optimised LLM application puts a metering and routing layer between features and providers. Requests carry a feature and tenant identifier, routing selects a model tier, caches are consulted before generation, calls are parallelised where independent, and every response records tokens, cost and latency against the originating feature.
Architecture Layers
Reference Architectures
Technology Stack
| Layer | Options | What to decide |
|---|---|---|
| Routing | LiteLLM, custom classifier, provider gateways | Escalation criteria and evaluation of quality loss |
| Caching | Redis, CDN, provider prompt caching | Key design and invalidation policy |
| Serving | Provider APIs, vLLM, TGI | Break-even volume for self-hosting |
| Observability | OpenTelemetry, Langfuse, cost dashboards | Granularity of attribution |
| Queueing | Managed queues, Kubernetes workers | Batch windows and concurrency limits |
Engineering Workflow
Cost per completed task, not per call
A cheap model that fails and retries can cost more than an expensive model that succeeds first time. Measure cost per successful outcome, including retries, and compare designs on that basis. This reframes routing: the question is not which model is cheaper per token but which design completes tasks at the lowest total cost with acceptable quality.
Latency is a sequence of waits
End-to-end latency is the sum of retrieval, each model call, tool execution and rendering. Teams often optimise generation while retrieval and sequential calls dominate. Measure each stage, parallelise independent calls, stream partial output, and cache retrieval results that do not change within a session.
Operating model for Cost & Latency Optimisation for LLM Applications
Making cost & latency optimisation for llm applications work over time is an ownership question before it is a tooling question. Someone must hold the quality bar, someone must own the artefacts and someone must own the operational signals. In practice that means a named owner per workflow, a repository location that is the single source of truth, and a review path where changes arrive with evidence attached rather than assertion. The capabilities that matter most in this discipline — token economics, prompt caching, model routing — are learned by doing them on real traffic, so the operating model should create a steady cadence of small changes rather than occasional large ones. Teams that centralise everything in a specialist group create a bottleneck; teams that distribute without shared standards create drift. The workable middle is a platform that provides the shared harness and gates, with product teams owning behaviour and outcomes.
Measurement plan for Cost & Latency Optimisation for LLM Applications
A measurement plan turns cost & latency optimisation for llm applications from a matter of opinion into a managed process. Start with the outcomes the business already cares about — cost per completed task, handling time, error rates — and attach the engineering signals that lead them: cost per completed task, time to first token, cache hit rate. Establish a baseline before changing anything, because without it improvement cannot be distinguished from noise. Segment by tenant, document type or intent where behaviour genuinely differs, since averages hide the failures that matter. Set thresholds that block rather than warn, review them quarterly as the system and traffic change, and record the reason whenever a threshold is adjusted. The plan is finished when a new engineer can read it, run the harness and reach the same conclusion the team would.
Working with providers and platforms on Cost & Latency Optimisation for LLM Applications
No team owns this discipline alone: model providers, infrastructure platforms and internal review functions all shape what is possible. The practical work is to define the contract with each. From providers you need change notification, evaluation access and documented behaviour at the versions you actually run, so that an upgrade is a planned event rather than a surprise. From the platform you need the shared capabilities this topic depends on — logging, flags, secret management, queueing — so that product teams do not rebuild them inconsistently. From risk and audit you need agreement on the evidence that will be requested, captured at the point where it is generated. Negotiate these once and write them down. Teams that skip this step spend their time in repeated explanations of behaviour they cannot evidence, and they absorb provider changes as incidents rather than as planned migrations.
Bringing the team with you
Practice changes fail quietly when they are imposed as process. The teams that sustain cost & latency optimisation for llm applications explain why the gate exists, show the incident it would have prevented, and make the fast path the compliant path. That means templates that already include the artefact, a harness that runs in one command, and a dashboard that answers the question people ask first: is it getting worse? When the tooling makes the right thing easy, adoption follows; when it adds a step with no visible benefit, it is bypassed at the first deadline. Budget time for the first two workflows explicitly, because that is where the habit forms, and treat a caught regression as a success rather than a defect. A team that has experienced one early catch rarely needs persuading again.
Failure modes to design out
Most incidents in this area trace to a small set of predictable design gaps: unattributed spend; quality loss from over-aggressive routing; cache serving stale answers. Each has a structural remedy rather than a procedural one. Where the risk is silent drift, the remedy is a gate that fails loudly. Where the risk is uncontrolled blast radius, the remedy is narrower scope and a rollback path that has been tested. Where the risk is unowned quality, the remedy is a named owner with time allocated. Designing these out at the start costs a fraction of discovering them in production, and it converts the team's attention from firefighting to improvement. The test of a design is whether a plausible mistake by a competent engineer produces a caught error rather than a customer-visible incident.
Cost and Latency Levers
| Lever | Typical saving | Quality risk | Effort |
|---|---|---|---|
| Prompt and context trimming | High | Low if evaluated | Low |
| Prompt prefix caching | Medium to high | None | Low |
| Semantic caching | High on repeats | Medium, staleness risk | Medium |
| Model routing | High | Medium, escalation gaps | Medium |
| Self-hosted serving | High at scale | Operational risk | High |
| Parallelising calls | Latency only | None | Low |
Maturity Levels — Cost & Latency Optimisation for LLM Applications
| Level | Characteristics | Evidence you would see |
|---|---|---|
| Ad hoc | Practice depends on individual judgement; changes are unreviewed | No baseline metrics, incidents explained by anecdote |
| Defined | Artefacts are versioned and token economics is applied consistently | Repository contains versioned artefacts and a documented process |
| Measured | Cost per completed task and related signals are tracked per workflow | Dashboards and baselines exist, regressions are detected before users |
| Managed | Thresholds gate releases and ownership is explicit | Changes blocked on evidence, incidents reviewed with recorded actions |
Enterprise Use Cases
Case Study: Pilot economics at production volume
Case Study: Latency dominated by sequencing
Implementation Steps
Practical Project
Operationalise Cost & Latency Optimisation for LLM Applications
Take an existing workflow that relies on cost & latency optimisation for llm applications and make its behaviour measurable, gated and reversible, without changing the product surface users see.
Requirements
- A versioned artefact set: configuration, prompts or schemas, and the evaluation dataset
- Baseline measurements for quality, latency and cost before any change
- A release gate that blocks regressions rather than warning about them
- Documentation sufficient for another engineer to reproduce the evaluation
- A rollback procedure tested once before it is needed
Steps
- 1.Map the current workflow and identify the decision points where quality can be measured
- 2.Capture baseline metrics on live traffic samples and store them with the release record
- 3.Build or extend the evaluation dataset with edge cases drawn from real incidents
- 4.Implement the change behind a flag and run the evaluation harness against it
- 5.Roll out to a small cohort, compare against baseline and revert or proceed on evidence
- 6.Record the outcome and update the playbook with what the evaluation revealed
Enterprise & GCC Applications
- Global capability centres use Cost & Latency Optimisation for LLM Applications to standardise engineering practice across distributed teams, with shared evaluation and release gates rather than per-site conventions.
- Enterprise architecture groups apply the topic when defining reference platforms, so product teams inherit compliant defaults instead of rebuilding controls per project.
- Delivery leadership uses the associated metrics in quarterly reviews, replacing anecdotal quality claims with measured evaluation coverage and regression escape rates.
- Risk and audit functions rely on the artefacts the practice produces — versioned prompts, evaluation results, decision logs — as evidence during internal and external review.
Risks & Mitigations
Key Metrics
Trends & 2026 Outlook
Prompt prefix caching as standard
Tiered model routing
Cost attribution in AI platforms
Semantic caching with invalidation
Career Roles
Frequently Asked Questions
Should we always use the cheapest model?
No. Optimise cost per completed task at acceptable quality. Cheap models that fail and retry often cost more, and they erode trust in the feature.
Does caching risk incorrect answers?
Yes if keys ignore context or content changes. Use short TTLs for volatile content, include context in the cache key and never cache personalised answers across users.
When does self-hosting pay off?
At high, stable utilisation with predictable demand. Below that, operational overhead and idle capacity usually outweigh per-token savings.
How do we measure cost per feature?
Tag every request with feature and tenant identifiers at the call site and aggregate tokens and cost by those tags, including retries.
What is a reasonable latency target?
Time to first token under a second for interactive flows and total completion within a few seconds, with streaming covering longer generations.
How do we stop one tenant consuming the budget?
Per-tenant quotas with defined degradation: smaller model, shorter context or queueing, decided in advance rather than at incident time.
What does a mature cost & latency optimisation for llm applications practice look like?
It looks unremarkable: artefacts are versioned, changes arrive with evaluation evidence, thresholds block regressions, and a named owner reviews the metrics on a regular cadence. The visible behaviour is small frequent releases rather than occasional large ones, because small changes are what make attribution possible.
How do we start in an existing codebase without a rewrite?
Pick one workflow, instrument its baseline, and build a small evaluation set from real traffic and past incidents. Gate that single workflow first. Once the pattern is proven, extend it — retrofitting a whole estate at once usually stalls, while one gated workflow establishes the habit and the tooling.
What should we measure in the first thirty days?
Only what you can act on: a baseline for the workflow you chose, the leading signals that predict the outcome you care about, and the cost of running the current design. Resist adding dashboards nobody reads. Thirty days is enough to establish one gated workflow, one baseline and one caught regression, which is a stronger position than a broad but unmaintained measurement programme.
Which decisions belong in the platform rather than in each product team?
Anything that must be identical across the estate to be auditable: logging and trace format, secret handling, evaluation harness interfaces, flag mechanics and rollback paths. Behavioural decisions — what the system should do, what quality bar applies, which cases are unacceptable — belong with the product team that owns the outcome.
References & Resources
- Provider pricing and caching documentation:Token pricing, cache discounts and rate-limit behaviour
- Serving framework documentation:Throughput and batching characteristics for self-hosted inference
- Web performance research:Perceived latency and time to first token effects on engagement
- FinOps practice guidance:Attribution, budgeting and unit economics for variable-cost services
Continue this lesson with a subscription
AI Engineering & AI-Native Software Development is part of the paid catalogue. You have read the free preview. A subscription opens the rest of this lesson, the classroom slides and the assessment questions.
- The full lesson for this topic and every other catalogue topic
- Every classroom slide deck and worked example
- All assessments, with a verifiable certificate on completion
The Free-To-Learn library stays open to everyone and is not affected by this.
