Engineering LLM Applications at Scale: A Practical Guide to Model Selection, Architecture, Cost, Evaluation, and Governance
As capital continues to flow into foundation models, engineering teams face a changing market of providers, interfaces, and pricing structures. This article outlines a practical workflow for building LLM applications at scale: derive model selection from business tasks, wrap model calls behind a unified abstraction, estimate and control token costs, build offline regression and online monitoring, and introduce launch governance such as rate limiting. It focuses on verifiable metrics, maintainable architecture, and operational controls rather than market hype.
1. Why Capital Trends Matter to Engineering Teams
As capital continues to flow into foundation model providers, the number of available models, interface forms, and pricing structures will keep changing. More suppliers mean more choices and faster capability updates. At the same time, providers’ service stability, pricing rules, and data-processing terms may also change, so teams need to track these developments continuously.
Funding size alone does not indicate technical quality. Engineering teams should focus on verifiable metrics, including task accuracy, response latency, cost per request, service availability, and data-processing terms. The judgment criterion should always come from actual performance in business scenarios, not external hype.
2. Deriving Technology Selection from Business Requirements
Selection should start with the business task, not with a particular model. Different tasks impose very different requirements on model capabilities. The following table lists core metrics for several common scenarios.
| Task type | Main metrics | Key focus |
|---|---|---|
| Text generation and rewriting | Semantic accuracy, style consistency | Output format constraints, factual control |
| Retrieval-augmented question answering | Retrieval quality, citation reliability | Retrieval pipeline design, context length |
| Code assistance | Compilation pass rate, test pass rate | Context window, code security review |
| Information extraction | Field accuracy, recall | Structured output, post-validation rules |
When comparing candidate solutions, it is recommended to evaluate them across the following five dimensions.
Quality. Quality must be measured with the team’s own test data. Public leaderboards only indicate general capability and cannot replace performance on business data.
Latency. Interactive scenarios usually require sufficiently fast first-token response. Batch tasks have lower latency requirements and can trade latency for lower cost.
Cost. Cost is determined jointly by the number of input and output tokens and their unit prices. Long prompts and long outputs both significantly increase costs.
Compliance. It is necessary to confirm whether data will be retained, whether it will be used for training, and whether it meets industry regulatory requirements. When personal information or trade secrets are involved, this should be a veto criterion.
Replaceability. If business code directly depends on the interface details of one provider, switching costs will be high. Therefore, replaceability itself is a metric that needs to be designed for.
3. Architecture Design: Wrap Model Calls in an Independent Layer
Business code should not directly call a specific API. A recommended approach is to define a unified invocation abstraction and let a routing layer decide which backend to use. This brings three benefits: switching models requires only configuration changes; new versions can be rolled out by percentage; and the primary service can automatically fall back when it fails.
The following sample code shows a unified interface and routing logic with retries and fallback.
from abc import ABC, abstractmethodfrom dataclasses import dataclassimport time@dataclassclass GenerationRequest:prompt: strmax_output_tokens: int = 512temperature: float = 0.2timeout_s: float = 20.0@dataclassclass GenerationResult:text: strinput_tokens: intoutput_tokens: intlatency_ms: floatprovider: strclass ModelProvider(ABC):name: str@abstractmethoddef generate(self, req: GenerationRequest) -> GenerationResult:...class ModelRouter:def __init__(self, primary, fallback=None, retries=2):self.primary = primaryself.fallback = fallbackself.retries = retriesdef generate(self, req: GenerationRequest) -> GenerationResult:last_error = Nonefor provider in (self.primary, self.fallback):if provider is None:continuefor attempt in range(self.retries + 1):try:start = time.perf_counter()result = provider.generate(req)result.latency_ms = (time.perf_counter() - start) * 1000return resultexcept TimeoutError as exc:last_error = exctime.sleep(0.5 * (2 ** attempt))raise RuntimeError("All model backends failed") from last_error
Two points need attention. First, retries increase actual token consumption, so retry counts should be limited and timeouts should be tracked. Second, retries are safe only when requests are idempotent or results can be discarded. For operations with external side effects, such as writing to a database or sending messages, ensure idempotency at the business layer before introducing automatic retries.
4. Cost Accounting and Capacity Planning
Cost estimation is required before launch. The basic formula for single-request cost is:
Single-request cost = input tokens × input unit price + output tokens × output unit price
Monthly cost equals average daily request volume multiplied by single-request cost, then multiplied by the number of days. The following example is only for demonstrating the calculation method. Prices are hypothetical, and actual values should follow the provider’s official billing documentation.
def estimate_monthly_cost(daily_requests, avg_in_tokens, avg_out_tokens,price_in_per_k, price_out_per_k, days=30):per_request = (avg_in_tokens / 1000) * price_in_per_k \+ (avg_out_tokens / 1000) * price_out_per_kreturn daily_requests * days * per_request# Assume 100,000 requests per day, average input 800 tokens, average output 300 tokensprint(estimate_monthly_cost(100_000, 800, 300, 0.01, 0.03))
Cost control usually can start from the following directions.
Compress prompts. Remove repeated explanatory text, put fixed rules into system-level configuration, and inject retrieved context only when needed.
Limit output length. Set an upper bound through max_output_tokens and ask for concise answers in the prompt. Output tokens usually have a higher unit price than input tokens, so controlling output yields greater savings.
Cache repeated requests. For standardized Q&A or templated tasks, identical inputs can directly return cached results with a reasonable expiration time.
Choose model size by task. Simple tasks such as classification and extraction do not necessarily require the largest model. Routing simple requests to smaller models can significantly reduce overall cost.
Batch non-real-time tasks. Scenarios such as report generation and offline labeling can combine requests and run them during off-peak periods.
5. Evaluation System: Offline Regression and Online Monitoring
Every change to a model or prompt may introduce regressions in some scenarios. Without an evaluation system, teams can only rely on user feedback to discover problems, which is costly.
The first step in building an evaluation system is to construct a golden test set. The test set should cover three types of samples: high-frequency real scenarios, error-prone edge cases, and deliberately designed adversarial samples, such as inputs containing misleading instructions. Each sample should record the expected key information and forbidden content.
The second step is to design a scoring rubric. Common dimensions include correctness, completeness, format compliance, and whether sensitive information is included. The rubric needs to be as specific as possible and avoid vague judgments such as “answers well.”
The following is a minimal regression framework based on keyword rules.
from dataclasses import dataclass, field@dataclassclass EvalCase:case_id: strprompt: strmust_contain: list = field(default_factory=list)must_not_contain: list = field(default_factory=list)def score_output(text, case):if any(k not in text for k in case.must_contain):return Falseif any(k in text for k in case.must_not_contain):return Falsereturn Truedef run_suite(generate_fn, cases):passed, failures = 0, []for case in cases:output = generate_fn(case.prompt)if score_output(output, case):passed += 1else:failures.append(case.case_id)return passed / len(cases), failures
Keyword matching can only serve as a baseline. For open-ended generation tasks, it is necessary to combine manual sampling or use calibrated judge models for scoring. Judge models themselves must also be validated against human-labeled samples; otherwise, scoring results are unreliable.
The third step is to integrate evaluation into the release process. Every time a model version is changed, the system prompt is modified, or the retrieval strategy is adjusted, regression tests should be run first. When the pass rate drops beyond a configured threshold, the pipeline should automatically block the release.
Online monitoring is equally necessary. It is recommended to continuously record request volume, error rate, timeout rate, average token consumption, and the proportion of negative user feedback, and to set alert thresholds.
6. Launch Governance: Rate Limiting, Degradation, and Security
6.1 Rate Limiting
Model services usually have request rate and concurrency limits. Implementing rate limiting on the application side can avoid burst traffic triggering provider limits and can also prevent a single tenant from exhausting resources. A token bucket is a common approach: tokens are replenished into a bucket at a fixed rate, and each request consumes a token.
