Engineering Large-Scale AI Services: Open Weights, Subscriptions, and Usage-Based Billing

    This article examines the core engineering challenges behind production AI services and how to run open-weight models, free users, paid subscribers, and metered API callers within a single system. It clarifies four frequently confused concepts (open weights, hosted APIs, subscriptions, and usage-based billing), then walks through a five-layer architecture covering access, entitlements, inference scheduling, metering and billing, and governance. Along the way it shows how to model plans as configurable resource boundaries, separate entitlement periods from billing cycles, adopt an online-quota/offline-metering pattern, schedule requests with deadline-based priorities, implement engineering-grade sell-out controls, and build observability, evaluation, and compliance into the platform. A practical implementation checklist at the end helps teams build the foundation step by step.

    1. The Problem: From “Model Capability” to “Service Engineering”

    Over the past two years, the industry narrative around large AI models has shifted in two clear directions. The first is opening up: vendors have released model weights of different sizes as open source, pushing capability downward and expanding ecosystems. The second is productization: consumer-facing AI assistants commonly adopt a combination of “free core features + tiered paid subscriptions + usage-based API billing” to serve needs that range from individual users to teams and enterprise developers.

    Taken together, these two shifts have moved engineering teams’ focus from “how do we train or connect a better model” to a more concrete question:

    How can we reliably serve open-weight models, free users, paid subscribers, and metered API callers from a single system, while making every call measurable, billable, governable, and rollback-safe?

    Many teams initially treat a model as just an “inference endpoint.” As concurrent users, calling channels, and billing models all grow at once, problems start to pile up: rate limiting accidentally hurts paying users, usage cannot be reconciled, model upgrades cause output drift, new subscriptions exceed the compute budget. Most of these problems cannot be solved by swapping in a different model.

    From a neutral engineering perspective, this article analyzes the general technical problems behind large-scale AI services, including tiered entitlements, metering and billing, inference scheduling, sell-out control, and cost governance. It ends with a practical checklist you can adopt directly.

    2. First, Four Concepts That Are Easily Confused

    Before discussing specific solutions, it helps to separate four concepts that are often lumped together, because each maps to a completely different implementation path:

    • Open weights: model parameters can be downloaded, self-hosted, and fine-tuned. This answers “who runs the model.”
    • API service: callers use the model over a network interface, and inference is hosted by the provider. This answers “who bears the compute and operations burden.”
    • Subscription: users pay by time and receive usage rights included in a plan over a billing cycle. This answers “why users keep paying.”
    • Usage-based billing: charges are settled by actual usage, typically normalized into a standard unit (such as tokens), or measured by call count or task duration. This answers “how to price usage that exceeds the plan.”

    It is worth stressing that opening the weights does not mean zero operations. Self-hosting means the team is responsible for resource scheduling, version upgrades, security hardening, and capacity planning. A hosted API concentrates operational pressure on the provider’s side, raising the bar for stability, metering accuracy, and cost control.

    For this reason, mature AI services rarely choose only one of these models. Instead, they support all of them on a unified technical foundation. Such an architecture can be divided into five layers:

    1. ┌──────────────────────────────────────────────────────────────────────┐
    2. │ Access layer: API gateway / auth / request validation / rate limiting │
    3. ├──────────────────────────────────────────────────────────────────────┤
    4. │ Subscription & entitlement layer: plan management / entitlement config / sell-out switches │
    5. ├──────────────────────────────────────────────────────────────────────┤
    6. │ Inference scheduling layer: model routing / queueing / caching / capacity control │
    7. ├──────────────────────────────────────────────────────────────────────┤
    8. │ Metering & billing layer: usage capture → message queue → offline metering → invoicing & settlement │
    9. ├──────────────────────────────────────────────────────────────────────┤
    10. │ Governance layer: logging & tracing / monitoring & alerting / evaluation regression / content safety │
    11. └──────────────────────────────────────────────────────────────────────┘

    The following sections walk through each layer.

    3. Subscriptions and Entitlements: From “Buying Usage Counts” to “Buying Resource Boundaries”

    3.1 The Essence of Subscriptions Is a Resource Boundary

    Individual subscription revenue flows in linearly over time, but costs fluctuate with user activity. If a plan only promises “unlimited usage,” a single high-frequency user may consume inference compute far beyond their subscription revenue. So the core of subscription design is not limiting call counts, but defining clear resource boundaries for each tier, including:

    • Available model scope: e.g., a small base model, a general chat model, a reasoning-enhanced model, a long-context model;
    • Context and output length: the maximum length a single request can carry and generate;
    • Rate and concurrency: requests per minute and concurrent in-flight requests;
    • Peak-time priority: whether paid tiers get scheduled first when resources are tight;
    • Supporting capabilities: knowledge-base capacity, API call quota, team seats, usage-detail export, data-retention policy, and so on.

    Take the common unlimited-subscription model as an example. If you only cap usage without setting rate, concurrency, and priority limits, peak-hour queueing and timeouts will keep degrading paying users, which in turn drives refunds and churn. Only by explicitly modeling these boundaries can the technical implementation stay consistent with the commercial promise.

    3.2 Entitlements as Data: Expressing Differences Through Configuration

    Entitlements should be modeled as structured configuration, not as scattered conditional checks in code. A representative structure looks like this:

    1. # Illustrative structure — shows the modeling approach only, not the specs of any real product
    2. TIERS = {
    3. "basic": {
    4. "models": ["chat_small", "chat_standard"],
    5. "max_context": 32_000,
    6. "max_output_tokens": 2_048,
    7. "rpm": 20, # requests per minute
    8. "concurrency": 2, # concurrent in-flight requests
    9. "priority": 0, # scheduling priority; higher value wins
    10. },
    11. "pro": {
    12. "models": ["chat_small", "chat_standard", "chat_reasoning"],
    13. "max_context": 128_000,
    14. "max_output_tokens": 8_192,
    15. "rpm": 60,
    16. "concurrency": 6,
    17. "priority": 1,
    18. },
    19. }
    20. # Usage-based API callers are mapped to the highest priority via the entitlement layer
    21. API_RIGHTS = {"models": "*", "max_context": 0, "rpm": 600, "concurrency": 30, "priority": 2}

    Once a request enters the system, the entitlement layer resolves and validates it:

    1. def resolve_rights(principal):
    2. """Resolve a caller identity into an entitlement object; principal may be a
    3. subscription user, a free user, or an API caller."""
    4. if principal.kind == "api_key":
    5. return API_RIGHTS
    6. if not principal.has_active_subscription:
    7. # free users get base entitlements by default
    8. return FREE_RIGHTS
    9. return TIERS[principal.plan_code]
    10. def check_request(rights, request):
    11. """Admission check for a request. Every rejection returns a distinguishable
    12. error code so the frontend can prompt users and monitoring can attribute issues."""
    13. if request.model not in rights["models"]:
    14. return Reject("MODEL_NOT_IN_PLAN")
    15. if rights["max_context"] and request.total_tokens > rights["max_context"]:
    16. return Reject("CONTEXT_TOO_LONG")
    17. if request.max_tokens > rights["max_output_tokens"]:
    18. return Reject("OUTPUT_LIMIT_EXCEEDED")
    19. return Allow()

    This design has three benefits:

    1. Adding a tier or adjusting a limit only requires changing configuration, not business code;
    2. Every rejection carries a clear error code, making it easy to monitor and analyze churn causes;
    3. Free and paid users share the same entitlement model, so you don’t need separate logic for different user groups.

    3.3 The Dual-Clock Problem: Quota Windows vs. Subscription Periods

    Two boundaries in the entitlement system are easy to get wrong: the subscription period and the metering window. For example, does a monthly plan run by calendar month or by the subscription activation date? When an auto-renewal succeeds on the last day of the month, should the remaining quota carry over into the new cycle, or expire?

    The correct approach is to model the entitlement period and the billing period separately:

    • The entitlement period determines how much the user can use right now;
    • The billing period determines how and when the invoice is issued;
    • The two are linked through a “period instance,” and on renewal a new period instance is created with an explicit quota-carryover rule.

    For usage-based API callers, bills should be issued by calendar month, and usage that has not yet been settled across the month boundary should be accounted for, to avoid duplicate or missing charges.

    4. Metering and Billing: Making Every Token Accountable

    4.1 A Unified Usage Event Model

    Whether usage comes from a subscription user, a free user, or an API caller, the server should emit a usage event in a unified format, recorded exactly once. A usage event should contain at least the following fields:

    • Caller identity: tenant, API key, or user ID;
    • Idempotency key: a globally unique request ID, used for deduplication;
    • Business reference number: used to link orders, plan periods, and invoices;
    • Model identifier and version: different versions may have different prices and must be distinguishable;
    • Input, output, and cache-hit token counts: the cache-hit portion is usually priced separately;
    • Task type: e.g., chat, reasoning-enhanced, document processing, for differentiated pricing;
    • Failure flag and error code: whether failures, timeouts, and duplicate requests are billed must be clearly agreed;
    • Server-side timestamp: settlement cycles and reconciliation are based on server time.

    4.2 Online Quota Enforcement, Offline Metering

    A common mistake is to “compute cost and deduct quota” on the request’s synchronous path. The consequences are:

    • Billing logic depends on database availability, so database jitter directly amplifies into service unavailability;
    • Changing billing rules requires halting writes or performing migrations;
    • Individual usage events are hard to trace, so invoices cannot be explained during disputes.

    A more robust pattern is online quota enforcement with offline metering:

    1. The request path performs only lightweight quota reservation, which can be implemented with a local counter plus periodic synchronization;
    2. Usage events are enqueued asynchronously (e.g., via a message queue) and consumed offline by a dedicated metering service;
    3. The metering service performs deduplication, price lookup, period aggregation, and invoice generation;
    4. Online quota enforcement and offline metering are reconciled on a schedule, with alerts when the deviation exceeds a threshold.

    The benefit is decoupling the inference path from the billing path: when the billing system is upgraded or fails, request handling is unaffected, and usage events are reliably buffered by the message queue and consumed once the system recovers.

    4.3 A Representative Metering Service Implementation

    1. import time
    2. class MeteringService:
    3. def __init__(self, pricing_table, usage_store, bill_store):
    4. self.pricing = pricing_table # (model, task_type) -> unit price
    5. self.usage = usage_store # usage store, keyed by idempotency key
    6. self.bills = bill_store # bill store
    7. self.processed = set() # set of processed idempotency keys; use a
    8. # persistent dedup table in production
    9. def consume(self, event):
    10. if event.request_id in self.processed:
    11. return # drop duplicate messages outright to guarantee idempotency
    12. # Prefer a database unique index or a distributed lock to avoid duplicate
    13. # posting under concurrent consumption
    14. self.processed.add(event.request_id)
    15. # 1. Deduplicate and validate: insert the usage record with the idempotency
    16. # key as primary key; a conflict is treated as a duplicate
    17. self.usage.insert(event)
    18. # 2. Resolve the price: prefer the model version, then fall back to model class
    19. price = self.pricing.get(event.model, event.model_version) or self.pricing.get(event.task_type)
    20. if price is None:
    21. raise UnknownPricingRule(event.model, event.model_version, event.task_type)
    22. # 3. Convert to unit cost: cache-hit input tokens are usually charged at a discount
    23. cost = price.input * event.prompt_tokens
    24. cost += price.output * event.completion_tokens
    25. cost -= price.input * (1 - price.cache_discount) * event.cached_tokens
    26. # 4. Period aggregation: accumulate by the period the server timestamp falls
    27. # into, not by the consumption time
    28. period = period_of(event.server_ts)
    29. self.bills.add_usage(event.tenant_id, event.channel, period, event.model_version,
    30. event.task_type, cost)
    31. def close_period(self, tenant_id, period):
    32. """Generate an invoice after a period closes: in-plan quota is deducted first,
    33. and the overage is settled at the agreed unit price."""
    34. summary = self.bills.summarize(tenant_id, period)
    35. plan = self.bills.period_plan(tenant_id, period)
    36. billable = max(0, summary.cost - plan.included_quota)
    37. invoice = {"tenant_id": tenant_id, "period": period,
    38. "usage_cost": summary.cost, "included": min(summary.cost, plan.included_quota),
    39. "payable": billable * plan.overage_rate}
    40. self.bills.issue(invoice)

    Three things also need attention in the implementation:

    • Failure-request billing rules: a common practice is to bill requests that consumed compute and returned content, not bill requests that fail on invalid parameters or authentication, and handle timeouts and retries per an agreed rule. Whichever rule you choose, document it clearly.
    • Subscription “overage”: a plan’s entitlement is a resource boundary rather than a pure quota, so exceeding the boundary usually shows up as a rate-limit rejection, not an automatic charge. Whether overage consumption is allowed should be declared explicitly in the plan configuration.
    • Reconciliation: periodically compare the billing system against the upstream inference service’s usage statistics. Any systematic deviation should be caught before the invoice is published externally.

    5. Inference Scheduling: Fairness and Efficiency in the Same System

    5.1 Masking Model Differences with a Unified Interface

    Hosted APIs, self-hosted open-weight models, and locally fine-tuned models often differ in interface protocol, streaming output format, and context handling. Define a unified abstraction at the routing layer to hide these differences:

    1. from abc import ABC, abstractmethod
    2. class ModelBackend(ABC):
    3. @abstractmethod
    4. def complete(self, req: dict) -> dict:
    5. """Return a unified structure: text, usage, finish_reason, etc."""
    6. class HostedBackend(ModelBackend):
    7. """Hosted API backend: handles auth, retries, and protocol adaptation"""
    8. def complete(self, req):
    9. # convert the unified request into the upstream protocol and retry recoverable errors
    10. return adapt_upstream(req)
    11. class SelfHostedBackend(ModelBackend):
    12. """Self-hosted open-weight model backend: handles instance selection and batch scheduling"""
    13. def complete(self, req):
    14. instance = pick_instance(req["model"], req.get("region"))
    15. return instance.infer(req)

    5.2 Queue Scheduling: Using Deadlines for Priority

    Different channels and plans have very different latency sensitivities: paying subscribers expect second-level responses, while batch document-processing jobs can tolerate minute-level waiting. Based on an earliest-deadline-first idea, the server can assign a deadline to each request type and then schedule them uniformly:

    1. import heapq
    2. import time
    3. # Illustrative parameters: queue tolerance (seconds) for each entitlement tier
    4. QUEUE_TOLERANCE = {"basic": 15, "pro": 8, "api": 5}
    5. DEFAULT_TOLERANCE = 20
    6. class PriorityScheduler:
    7. def __init__(self):
    8. self.heap = []
    9. self.counter = 0
    10. def submit(self, task):
    11. tolerance = QUEUE_TOLERANCE.get(task["rights"].get("tier"), DEFAULT_TOLERANCE)
    12. deadline = time.monotonic() + tolerance
    13. # counter keeps FIFO order among equal deadlines so same-tier users don't
    14. # starve each other
    15. self.counter += 1
    16. heapq.heappush(self.heap, (deadline, self.counter, task))
    17. def poll(self, now):
    18. """Return the tasks that should be scheduled now; overdue tasks are handed to
    19. a degradation policy"""
    20. due = []
    21. while self.heap and self.heap[0][0] <= now + self.look_ahead:
    22. _, _, task = heapq.heappop(self.heap)
    23. if now > task["deadline"]:
    24. degrade(task) # degrade to a smaller model, return a queueing notice,
    25. # or return a retryable error
    26. else:
    27. due.append(task)
    28. return due

    Compared with a simple “serve the high-priority queue first,” this scheduling approach has two advantages:

    1. Low-priority requests won’t be postponed indefinitely as long as they finish before their deadline, avoiding starvation;
    2. Requests that exceed their deadline can be explicitly identified and trigger degradation, rather than leaving users waiting on a loading spinner.

    5.3 Cost-Reduction Strategies: Routing, Caching, and Context Management

    Inference cost is generally determined by “compute scale × unit-time price × duration consumed,” and the engineering-side room for optimization concentrates in three places:

    1. Model routing: route tasks like intent classification, format conversion, and simple Q&A to small models, and complex reasoning to large models. Routing can be rule-based (e.g., by task-type labels) or based on a lightweight classifier.
    2. Cache reuse: use prefix caching for high-frequency, relatively stable prefixes (such as system prompts), and semantic caching for highly deterministic Q&A. Both require a matching invalidation strategy to avoid returning stale results.
    3. Context governance: replace “stuff everything in” long context with summarization/compression and retrieval augmentation; set output-length caps to prevent runaway generation.

    6. Sell-Out Control: Engineering the “Sellable” State

    6.1 Why You Need a “Sellable” State

    When compute supply is tight or business strategy changes, the product side may temporarily pause new subscriptions for new users, including pausing new activations and upgrades to lower tiers. This is the same class of problem as closing the order entry after an e-commerce item sells out; in engineering it is called sell-out control. It covers at least six points:

    • A single authoritative switch: the sellable state lives in a config center, and changes are approved by an operations role with an audit trail;
    • Channel separation: clearly distinguish “new activation,” “existing-user renewal,” “tier upgrade,” and “API activation” channels, so pausing new activations doesn’t hurt renewals;
    • Frontend consistency: the purchase entry directly shows “new activations paused” instead of letting users place an order and only then fail;
    • Rollback-safe: every change carries a reason, a scope, and a rollback plan;
    • Protection of existing subscriptions: active subscriptions are unaffected, and renewal and entitlements follow existing rules;
    • Metric linkage: the sellable state is linked to capacity metrics (e.g., GPU utilization, queue length, first-token latency), providing a quantitative basis for reopening.

    6.2 A Representative Implementation

    1. import uuid
    2. import time
    3. CHANNELS = ("new_subscription", "renewal", "upgrade", "api_activation")
    4. class SubscriptionService:
    5. def __init__(self, config_center, order_repo):
    6. self.config = config_center
    7. self.orders = order_repo
    8. def is_sellable(self, channel):
    9. if channel not in CHANNELS:
    10. raise ValueError(f"unknown channel: {channel}")
    11. # each channel is configured independently and can auto-open/close in
    12. # response to capacity metrics
    13. return self.config.get_bool(f"sale.subscription.{channel}.enabled", default=True)
    14. def purchase(self, user_id, channel, plan_code):
    15. if not self.is_sellable(channel):
    16. raise SoldOut(channel)
    17. # idempotency key: repeated requests from the same user on the same channel
    18. # return the same order
    19. idem_key = f"{user_id}:{channel}:{plan_code}"
    20. existing = self.orders.find_by_idempotency_key(idem_key)
    21. if existing:
    22. return existing
    23. order = self.orders.create(
    24. idempotency_key=idem_key,
    25. user_id=user_id,
    26. channel=channel,
    27. plan_code=plan_code,
    28. created_at=int(time.time()),
    29. )
    30. # activation, entitlement writes, and other steps are completed asynchronously downstream
    31. return order

    Watch out for three anti-patterns:

    1. Hardcoding “new users can’t buy” in business code, so any adjustment requires a release and can’t be rolled back quickly;
    2. A switch with only “buyable/not buyable” granularity, so a pause also blocks existing-user renewals;
    3. Hiding only the frontend entry while leaving no server-side check, so users can still activate by calling the API directly.

    7. Observability, Evaluation, and Governance

    7.1 The Trinity of Metrics, Logs, and Traces

    Compared with ordinary web services, AI services need extra attention to:

    • Performance: first-token latency (TTFT), generation rate (tokens/s), end-to-end P95 latency, queue waiting time;
    • Stability: rate-limit rejection rate, timeout rate, upstream model error rate;
    • Quality: evaluation-set pass rate, user feedback (thumbs up/down/regenerate), refusal rate;
    • Cost: cost per thousand tokens, average cost per request, cache hit rate, resource utilization;
    • Business: trial conversion rate, subscription retention rate, API call-volume trends.

    In implementation:

    • Unified logging conventions: generate a trace ID for each request that links the gateway, entitlement check, queueing, inference, and metering stages; user input in logs should be redacted and given a retention period.
    • Tiered alerts: separate capacity alerts (queue length, concurrency) from quality alerts (latency, error rate), with distinct thresholds and on-call response policies.
    • General-purpose cloud components: message queues, object storage, logging services, and monitoring/alerting provide common support for the above capabilities.

    7.2 Evaluation Regression: The Must-Answer Question Before a Model Upgrade

    After weights are opened, self-hosted model upgrade frequency is often higher than for hosted APIs. Every upgrade should be treated as a change that could alter the user experience. A three-level evaluation system is recommended:

    1. Offline benchmark: on a fixed evaluation set, compare accuracy, refusal rate, format compliance, and average length; any regression in a core metric blocks release;
    2. Online canary: gradually ramp traffic by proportion and compare real-user feedback rates and latency changes;
    3. Regression comparison: run old and new versions simultaneously on shadow traffic, apply statistical testing to key metrics, and only go full-scale after confirming a significant difference.

    8. Compliance and Security: The Non-Negotiable Baseline

    • License compliance: different open-source licenses impose different requirements on commercial use, attribution, patent grants, and derivative works. Verify each one before adoption and maintain a software bill of materials (SBOM) style record of dependencies.
    • Data compliance: be explicit about which data is recorded, how long it is retained, and whether it is used for model improvement, and explain this in the privacy policy. Commitments such as “data is not used for training” in subscription terms must be guaranteed by the actual configuration of the data-processing pipeline.
    • Content safety: deploy content moderation on both the input and output sides to identify illegal and harmful content; provide a manual-review channel for high-risk scenarios.
    • API security: rotate keys regularly, enforce per-caller quotas and IP allowlists, and detect and auto-ban anomalous calls to prevent runaway costs from leaked keys.

    9. Implementation Checklist

    If you are building a large-scale AI service foundation from scratch, you can proceed in the following order:

    1. Unified abstraction: first define a unified model-backend interface and request/response structure, avoiding tight coupling between the business layer and specific models;
    2. Entitlement model: make plan differences configurable, with all rejection behavior attributable and monitorable;
    3. Metering loop: build the full chain of “usage event → message queue → offline metering → invoice → reconciliation” first, then consider billing optimizations;
    4. Scheduling policy: introduce a deadline-based priority queue with a degradation mechanism to protect paying users’ experience;
    5. Sell-out control: use the config center as the single switch, with controllable channel granularity and rollback-safe changes;
    6. Observability and evaluation: put metrics, logs, and traces in place first, and fold evaluation regression into the release process;
    7. Security and compliance: build the four lines of defense — licensing, data, content, and keys — in tandem.

    10. Conclusion

    Productizing large-scale AI services is, at its core, translating “model capability” into a “measurable, schedulable, billable resource.” Tiered subscriptions define the resource boundaries, metering and billing make resource usage billable, inference scheduling guarantees fairness and efficiency under limited compute, sell-out control keeps business strategy in sync with system state, and observability and evaluation keep it all improving.

    When products start competing on engineering systems rather than single-point model scores, the teams that can host open-weight and hosted models, free and paid users, and real-time and batch tasks within the same architecture are the ones that will reliably turn model capability into user experience and business value.