Open-Source LLM Weights and Hosted APIs: Architecture Practices for Tiered Operations
When you deliver a large language model to the outside world, you are really running two coupled engineering contracts at once—shipping weights for self-hosting and operating a stable hosted API—yet many teams let the two drift apart. This article lays out a practical architecture for keeping them aligned: a single source of truth for weights and inference config, a three-segment versioning scheme with explicit compatibility semantics, and one unified quota engine spanning free, subscription, and usage-based billing. It then covers metering with idempotent rate limiting, a three-tier overload strategy that treats queuing as a normal state, multi-tenant isolation and security, and the cost-engineering levers that decide long-term viability. It closes with a deployment checklist and the metrics worth watching.
1. Open Weights and Hosted Services Are Two Engineering Contracts
When a team ships a model externally, it does not face a single path but two that constrain each other.
The first is weight delivery: packaging parameters, config, tokenizer rules, and license declarations, and letting users deploy in their own environment. This path’s contract faces “hardware and software stack diversity”—the other side might be running single-machine inference or multi-GPU distributed setups, full-precision compute or a range of quantization schemes. You have to guarantee that “the same weights produce stable, reproducible output behavior under expected configurations.”
The second is a hosted service: you carry the compute and operations, and expose a stable calling interface. This path’s contract faces “latency, availability, tenant fairness, and billing correctness.”
Both paths share the same core assets—weights and inference config—but their acceptance criteria are completely different. Many teams run into trouble here: they treat the open-source version as an “experimental branch” and the hosted version as a “production branch,” and the two capabilities drift apart over time. Code a user wrote against the public weights then behaves differently when switched to the hosted API, which drives trust costs through the roof.
Practical advice: a single source of truth. Maintain only one copy of the weights and config, shared by both open source and hosted. Differences should be allowed only in service-layer add-ons (such as tool-call orchestration, content-safety filtering, and audit logging), never in the model’s behavior itself. A minimal version manifest helps here:
# Release manifest example; open source and hosted share the same baselinemodel:name: internal-model-xversion: 3.1 # bound to the public capability declarationrevision: sha256:9f1c # weight fingerprint, reproduciblecontext_window: 131072license: apache-2.0served_by: [api, self-hosted] # both delivery paths are driven from here
2. Versioning: Distinguish Capability Upgrades from Behavior Tweaks
A version number is not just a marketing label; it should carry clear compatibility semantics. A three-segment scheme works well:
- Major: the capability boundary or API contract changes (context-length expansion, tool-call protocol changes, a shift in the default safety policy). Users must migrate explicitly.
- Minor: capabilities improve while the API and existing behavior commitments stay compatible; auto-rolling upgrades are allowed.
- Patch: precision fixes, decoding-parameter calibration, throughput tuning—usually with no externally visible behavior change.
Three things need to support this:
- A deprecation window. Keep the old major version for a defined announcement period during which old and new run in parallel. Parallel here doesn’t mean “both interfaces are simply live”—it means sharing the same scheduling and metering foundation and switching only the routing target.
- Shadow traffic. Have the new version receive a mirrored copy of production traffic first, logging only and returning nothing, to compare the validity of structured outputs, the completeness of tool-call parameters, and the distribution of first-byte latency.
- A structured-output contract. Write “output must be valid JSON with fixed fields and types” into the contract, and use automated validation as a release gate. This protects users better than any capability description in natural language.
3. Free Tier, Subscription, and Pay-As-You-Go: Why Three Tiers Coexist
These three models are not simply stacked on top of one another; they address three different kinds of demand.
The free tier handles acquisition and evaluation. Its goal is not revenue but letting users complete a feasibility judgment at zero cost. So the correct design for the free tier is complete capability but limited throughput, not “feature-crippled.” Once you cripple features, the evaluation conclusion users reach is distorted.
The subscription tier handles predictable cash flow and high-frequency individual users. Its pricing anchor is a “predictable monthly usage quota.” What users care about most isn’t the unit price but “will it suddenly stop working this month?” So the subscription tier must give clear quota visibility and remaining-balance hints.
Pay-as-you-go handles elasticity and scale. Users are willing to pay a premium for something that “scales linearly with usage,” in exchange for no prepayment and no need to estimate capacity. The key engineering constraint here is metering accuracy and reconciliation explainability—if a user cannot recompute any given bill, trust collapses.
The direct complexity that three coexisting tiers create is that the quota engine must be unified. Don’t write three separate rate-limiting systems for the three modes; abstract them into a single “tenant → quota pool → metering event” model:
tenant tenant└── quota_pool quota_pool (type: free quota | subscription pack | prepaid balance)└── usage_event usage_event (input token / output token / cache hit / tool-call count)
4. Implementing Metering and Rate Limiting
A minimum viable metering system doesn’t need heavy dependencies—an in-process sliding window plus a persistable quota ledger is enough to start. The sample code below emphasizes semantics over performance:
import timefrom collections import defaultdict, dequefrom dataclasses import dataclass, field# ---- 1. Usage event: the single source of truth for all billing ----@dataclassclass UsageEvent:tenant_id: strmodel: strinput_tokens: intoutput_tokens: intcached_tokens: int = 0 # prefix-cache hits; unit price is usually much lowertool_calls: int = 0ts: float = field(default_factory=time.time)# ---- 2. Sliding-window limiter: counted independently per tenant + model ----class SlidingWindowLimiter:def __init__(self, window_sec: float = 60.0, limit: int = 600):self.window, self.limit = window_sec, limitself.events: dict[str, deque] = defaultdict(deque)def allow(self, key: str) -> bool:now, q = time.time(), self.events[key]while q and now - q[0] > self.window:q.popleft()if len(q) >= self.limit:return Falseq.append(now)return True# ---- 3. Quota deduction: idempotency is a hard requirement ----def charge(ledger: dict, evt: UsageEvent, units: int, event_id: str) -> dict:"""units is the converted billing unit; event_id deduplicates retries"""if event_id in ledger.setdefault("seen", set()):return {"status": "duplicated"}ledger["seen"].add(event_id)pool = ledger["pools"][evt.tenant_id]if pool["balance"] < units:return {"status": "insufficient", "balance": pool["balance"]}pool["balance"] -= unitsledger["usage"].append({**evt.__dict__, "units": units})return {"status": "ok", "balance": pool["balance"]}
Two easily overlooked engineering details matter here.
First, the billing unit must be “converted,” not added directly. Input and output tokens differ greatly in compute cost, so adding them directly makes the bill impossible to explain. It’s better to expose a single “billing unit” externally, maintain an internal unit-price table, and show the conversion details on the bill.
Second, the idempotency key cannot be dropped. Caller timeout retries, gateway replays, and duplicate message delivery are all normal. Without an idempotency key, at best you get user complaints about overcharging; at worst you run into fund-compliance problems. The approach is to generate a unique identifier per request and deduplicate before the metering event is persisted.
5. Capacity Governance: Treat Queuing as a Normal State
The elasticity of model-inference capacity is inherently limited—compute expansion has a lead time, while traffic spikes happen in minutes. So handling overload gracefully matters as much as improving peak performance.
Define three degradation levels explicitly, and put them in configuration rather than scattering them through the code:
- Extend the queue. Set a queue-timeout ceiling for interactive scenarios, and give clear waiting feedback before the timeout. This preserves the user experience better than an outright error.
- Routing downgrade. Temporarily route non-critical requests to a smaller or higher-throughput configuration, trading some quality for overall availability.
- Entry-level rate limiting. Reject requests differentially based on tenant priority and plan level, returning a structured error with a retry suggestion (use
429semantics with aRetry-Afterfield).
The switch that opens up new subscriptions is, essentially, an extreme action of this same governance: once the latency budget of existing online tenants has been compressed to its limit, pushing in more volume only slows everyone down. Treating this as a monitoring-driven switch rather than an ad-hoc decision is the key.
Metrics to keep an eye on:
| Metric | Meaning | Alerting direction |
|---|---|---|
| First-token latency P99 | The core of the interactive experience | A sudden spike triggers a capacity review |
| Output throughput (tokens/s) | Compute output per unit | A sustained decline points to scheduling or batching problems |
| Queue time and rejection rate | Direct overload signals | Rejection rate crossing the threshold triggers rate limiting |
| Cost per thousand tokens | Health of the unit economics | Reviewed in sync with pricing |
| Cache hit rate | Room for cost optimization | When low, investigate the prefix-reuse strategy |
6. Isolation and Security in a Multi-Tenant Environment
Serving externally means the input is untrusted. At a minimum, enforce dual limits on request-body size and context length; apply whitelist validation to tool-call parameters; detect and filter prompt-injection-style attacks on the server side; and run one more content-safety review on the output. On the data side, define a clear retention period and desensitization policy, and state plainly in the docs “which fields are used for metering and which are never persisted.” This is the lowest-cost way to reduce compliance risk.
7. Cost Engineering: What Determines Long-Term Viability
A model service rarely dies from technology; it dies when unit cost exceeds the customer’s unit price. Four general-purpose levers:
- Prefix-cache reuse. Fix the system prompt, few-shot examples, and long-document prefixes; bill the hit portion at a discount. This usually cuts costs significantly in repetitive scenarios.
- Dynamic batching. Batch as much as possible within the latency budget to raise hardware utilization.
- Tiered routing. Start with a lightweight model and escalate to a heavier configuration only when confidence is insufficient.
- Output-length constraints. Output tokens are often the most expensive part, so control the tail cost with explicit format constraints and a maximum length.
8. Deployment Checklist
- Open source and hosted share the same weights and config manifest, with no behavior drift
- Version numbers carry clear compatibility semantics, and old major versions have a deprecation window
- The release gate includes structured-output validation and shadow-traffic comparison
- Free / subscription / pay-as-you-go all share one unified quota and metering foundation
- Metering events carry an idempotency key, and the bill can be recomputed by the user
- Overload handling has three degradation levels, and is config-driven
- The subscription switch is driven by capacity metrics, not manual ad-hoc judgment
- Core monitoring metrics and alert thresholds are defined and have been rehearsed
Treat open source as the entry point of trust, the hosted service as the source of revenue, and metering and capacity governance as the shared foundation for both—once these three boundaries are clear, the complexity of product evolution falls from exponential back to linear.
