Token-Based Billing for LLM Services: Metering, Subscriptions, and E-Commerce Channel Fulfillment

    LLM vendors are increasingly listing token-based subscription plans on e-commerce storefronts, turning compute consumption into a resource that can be measured, priced, and traded. This article explains, from an engineering perspective, how to build the billing and delivery backbone such a model requires. It covers token metering and how to standardize token counting across tokenizer versions, plan design (quota-based versus subscription-based, plus multi-tier models and expiry rules), a four-layer decoupled architecture spanning transaction, fulfillment, gateway, and metering/settlement, the differences between official storefronts and reseller distribution, security and abuse prevention for resold tokens, and reconciliation, refunds, and after-sales support. It closes with observability and capacity-planning guidance, aiming to give developers a reference design for metering usage accurately, delivering quota reliably, and keeping accounts consistent and risks under control.

    Large language models are moving onto the “e-commerce shelf.” Recently, several LLM vendors have been talking to e-commerce channels about opening official flagship stores that sell subscription plans centered on token quotas. Some vendors have already moved in and listed subscription products aimed at intelligent coding scenarios, compatible with several mainstream coding tools. In parallel, some e-commerce platforms have launched dedicated token top-up sections, bringing in multiple LLM vendors through two models at once: official flagship stores and reseller distribution. Subscription purchases used to rely mainly on vendor-owned channels such as the vendor’s own website; today, developers can top up or renew model capacity much like buying a physical product. The essence of this shift is converting “compute consumption,” which was previously hard to estimate, into a measurable, priceable, and tradable commodity.

    Commoditizing model services is not new in itself. API services billed per call or per token, and subscription-based code-completion and writing tools, are all familiar forms. The key change this time is the channel: e-commerce platforms offer relatively mature order, payment, invoicing, and after-sales systems that can significantly lower the purchase barrier for both enterprise and individual users. But a completed sale is only the beginning. How to meter usage, issue and deduct quota, reconcile accounts, and prevent resale and abuse are the factors that truly determine experience and cost.

    This article breaks down four core areas from an engineering perspective—token metering, subscription billing, quota management, and channel fulfillment—and offers reference architecture designs and implementation recommendations you can apply directly.

    1. Foundations: What a Token Is and Why It Is the Billing Unit

    1.1 From Per-Call to Per-Unit

    Traditional software is priced by license or by seat, and cost is unrelated to how intensively it is used. LLMs are different: behind every conversation and every code completion lies an uncertain amount of inference compute. The longer the input, the more output generated, and the longer the conversation history carried in the context, the greater the consumption—and it is hard to estimate precisely in advance. A token can describe the scale of both input and output while also reflecting occupancy of the context window, which makes it the most natural unit for measuring inference cost. As a result, “billing by token” evolved from an internal cost-accounting method into a pricing unit offered to users.

    1.2 Standardizing the Basis to Avoid “Same Name, Different Quantity”

    A token is the basic unit an LLM uses to process text. A tokenizer splits text into a sequence of tokens according to specific rules, and English, Chinese, code, and numbers produce different segmentation results. The same passage can map to noticeably different token counts under different tokenizers, which is exactly why “standardizing the token-metering basis” must be solved first.

    There are four practical ways to approach this:

    • Fix the tokenizer: Adopt one fixed tokenizer externally and manage it with versioning. Once a billing tokenizer is released it stays stable; upgrades are handled under a “new basis for new plans” rule.
    • Define conversion rules: For quota products converted by character count, specify which tokenizer and which language the conversion uses. To avoid disputes, publish the conversion table so users can estimate for themselves before buying.
    • Distinguish counting scopes: Usually only the prompt and the model output are counted, excluding fixed overhead such as tool definitions and system instructions; the service terms govern the specifics.
    • Align front-end and back-end implementations: The front end and back end should reuse the same tokenizer library to avoid mismatches between what the page shows and what the backend settles.
    1. # Example: unified token counting
    2. # Pin the tokenizer and mapping-table versions; upgrades apply only to "new plans"
    3. from tokenizer_registry import get_tokenizer
    4. def count_tokens(text: str, tokenizer_version: str = "stable") -> dict:
    5. tok = get_tokenizer(tokenizer_version)
    6. return {
    7. "input_tokens": len(tok.encode(text)), # number of tokens in the prompt
    8. "tokenizer_version": tokenizer_version, # store in usage records for later auditing
    9. }

    2. Plan Design: Turning Tokens into Sellable Billing Units

    2.1 Two Common Plan Types

    By billing structure, token-quota plans fall into two broad categories:

    • Quota-based: Buy a fixed token quota once and use it until it is exhausted. Low barrier to entry, suitable for trials and low-frequency users, similar to a “data pack.”
    • Cycle-based: Subscribe weekly or monthly and receive a fixed quota each billing cycle. More predictable cash flow, suitable for high-frequency use, similar to a “monthly plan.”

    Real products often appear as a combination of “cycle subscription + fixed quota + pay-as-you-go overage,” meaning users can keep buying at a per-unit price once the in-plan quota runs out. There is also a “cycle-based + non-expiring quota” cumulative model, where each period’s quota adds up and expires only over a longer window, suited to teams with fluctuating usage.

    2.2 Key Billing Dimensions

    Beyond quota and cycle, a complete billing model also needs to account for the following:

    • Multiple model tiers: Lightweight and flagship models have different unit prices, and a plan may restrict which models it covers.
    • Input versus output: Output generation generally costs more than input, so the two should be priced separately.
    • Cache hits: In services that support prefix caching, repeated context may hit the cache, and the billing basis for cached portions must be defined in advance.
    • Service-form differences: Multi-turn, long-context scenarios such as intelligent coding tools consume far more than ordinary Q&A; plans for these scenarios usually carry larger quotas and are often tied to a specific client.
    • Expiry and downgrade: Define whether unused quota expires; when quota runs out, whether to reject requests, automatically downgrade to a lightweight model, or switch to pay-as-you-go.
    • Conversion and disclosure: Prices and conversion ratios should be published in the product details, and the metering basis should be disclosed in the service terms.

    2.3 Design Principles

    A good billing model should make it so that “users can calculate, the system can calculate, and both come up with the same number”:

    1. Estimable: Provide users with a consumption-estimation tool, or recommend plans based on historical usage;
    2. Explainable: Make quota balances and consumption details transparent to users, filterable by time, model, and client;
    3. Traceable: Map each deduction to a specific call record so disputes can be handled.

    3. Reference Architecture: Decoupling Transaction, Fulfillment, Metering, and Settlement into Four Layers

    The hard part of selling tokens through e-commerce is not payment—it is how to “accurately and reliably deliver the service to the user after payment.” A four-layer decoupled architecture is recommended:

    Layer Responsibilities Key design points
    Transaction Integrate with e-commerce platforms or resellers; complete ordering and payment Unified order protocol; confirm payment status via callbacks or active polling
    Fulfillment Create subscriptions, issue quotas, generate and deliver keys Idempotency, transaction guarantees, order state machine, failure compensation
    Gateway / access API gateway authentication, routing, rate limiting, and canary releases Model routing, per-plan rate limiting, fast failure
    Metering & settlement Collect usage, convert to quota consumption, deduct from the ledger, reconcile and bill Idempotent deduction, auditable ledger, multi-source reconciliation

    Two supporting capabilities are also needed:

    • Observability: Use logging and monitoring/alerting to centrally track call volume, success rate, latency, and quota consumption.
    • Elasticity and asynchrony: Use a container platform to run inference and gateway services with elastic scaling, and use a message queue to carry order and usage events for peak shaving and reliable delivery.

    3.1 Transaction Layer: Abstracting Away Channel Differences

    E-commerce channels integrate in different ways: some push orders proactively through open APIs, others require the service provider to poll order status on a schedule; under the reseller model, a reseller may open accounts centrally and then redistribute. The transaction layer should map order fields into a unified internal model:

    1. Channel order: channel_order
    2. ├─ channel # identifies the sales channel
    3. ├─ external_id # unique on the channel side; used for idempotency and reconciliation
    4. ├─ sku # maps to a quota/cycle plan
    5. ├─ pay_status # pending / paid / refunded
    6. ├─ amount
    7. └─ buyer # must be securely mapped to the platform's internal account system

    The key point: the external order ID must be persisted as an idempotency key, with “channel + external order ID” as a unique index. Channel retries, duplicate user orders, or duplicate message delivery will not cause duplicate fulfillment.

    3.2 Fulfillment Layer: Turning “Paid” into “Usable Quota”

    Fulfillment is the bridge between the transaction and the inference service, and it is best driven by a state machine:

    1. pending ──payment success──> pending-fulfillment ──fulfillment success──> active ──expiry/refund──> closed
    2. │
    3. └──fulfillment failure──> awaiting-retry ──retry success──> active
    • Atomic posting: Creating the quota record and generating the key should happen in the same transaction, avoiding “key without quota” or “quota without key.”
    • Idempotent writes: Fulfillment requests carry the order idempotency key, and duplicate requests simply return the first result.
    • Compensation and retries: Failed fulfillments enter a compensation queue and retry with exponential backoff; those that still fail after several attempts move to manual handling.
    • Delivery notification: Credentials such as keys are delivered through a secure channel. If channel rules do not allow displaying sensitive information directly, offer a redemption code that the user can redeem and bind themselves.
    1. # Example: idempotency-key-based provisioning
    2. def provision(channel_order: dict) -> dict:
    3. key = f"{channel_order['channel']}:{channel_order['external_id']}"
    4. existing = quota_store.find_by_idempotency_key(key)
    5. if existing:
    6. return existing # return the first provisioning result for duplicate notifications
    7. with transaction():
    8. quota = quota_store.create(
    9. idempotency_key=key,
    10. user_id=channel_order["buyer"],
    11. plan=channel_order["sku"],
    12. total=PLAN_DEFS[channel_order["sku"]]["quota"],
    13. used=0,
    14. )
    15. api_key = key_service.issue(user_id=channel_order["buyer"], quota_id=quota.id)
    16. order_state.mark_provisioned(channel_order["external_id"])
    17. return {"quota_id": quota.id, "api_key": api_key}

    3.3 Gateway Layer: The Gatekeeper Role

    The API gateway is the entry point for the model service and handles authentication, quota checks, model routing, rate limiting, usage instrumentation, and canary releases.

    Quota checks are best done at the gateway using a local cache with asynchronous synchronization, avoiding a ledger lookup on every request. But a local cache can only “intercept obviously insufficient requests”; whether a request is ultimately allowed still depends on the result of an atomic deduction.

    Quota control should also distinguish “total quota” from “concurrency and rate limits”:

    • Quota is a cumulative resource for total-volume control;
    • Concurrency and rate limits protect against burst traffic.

    The two need to be designed separately.

    3.4 Metering & Settlement Layer: The Deduction Ledger Is the Core of the Whole System

    The metering service collects usage events from the inference path, and the settlement service converts them into quota consumption using the price table and deducts accordingly. An “append-only, no-modify” ledger model is recommended:

    • Record top-ups, gifts, adjustments, consumption, and refunds as distinct entry types;
    • Derive the balance from the entries rather than directly modifying a field;
    • Use the “request unique ID” as the unique key on the entries table so duplicate events are recorded only once.
    1. # Example: idempotent deduction with row locking to prevent concurrent over-deduction
    2. def deduct(quota_id: int, usage: dict, request_id: str):
    3. cost = price_table.cost(usage) # convert usage into a quota cost via the price table
    4. with transaction():
    5. quota = quota_store.lock_for_update(quota_id) # row lock for concurrency safety
    6. if quota.balance < cost:
    7. return False # insufficient balance; the gateway rejects this request
    8. ledger.append(
    9. request_id=request_id, # unique key: duplicate events won't create duplicate entries
    10. quota_id=quota_id,
    11. delta=-cost,
    12. detail=usage, # keep raw input/output usage for auditing
    13. )
    14. quota_store.update_balance(quota_id, quota.balance - cost)
    15. return True

    4. Channel Distribution: Official Flagship Stores Versus the Reseller Model

    E-commerce platforms typically host two sales forms at once:

    • Official flagship store: Operated directly by the model service provider, with a short fulfillment path and complete order information;
    • Reseller distribution: Third-party resellers open stores and sell, so the model service provider may only see the reseller’s bulk orders.

    Under the reseller model, resellers pre-purchase general quota packs or redemption codes and then resell them through methods such as “one code, many uses.” This gives rise to three engineering needs:

    • Redemption-code security: Codes must be high-entropy and randomly generated, single-use, and revocable in bulk;
    • Multi-level reconciliation: End-user consumption must be aggregated by reseller, forming a three-tier “reseller—end user—usage” account structure;
    • Quota-pool management: Issuing, reclaiming, and freezing quota in a pool needs clear state transitions so that already-sold quota is not resold.

    For this reason, the transaction layer should reserve channel identifiers and a reseller dimension from the start, rather than reworking the design when onboarding a new channel.

    5. Security and Risk Control: Making It Both Easy to Sell and Easy to Control

    A token is a digital resource that can be copied infinitely and transferred instantly. Once it enters open e-commerce channels, it is exposed to a more complex risk environment, so a multi-dimensional protection system is needed:

    • Tiered credentials: Issue separate keys for different plans and users, supporting individual revocation and rotation, with keys generated and stored only on the server side;
    • Multi-dimensional rate limiting: Beyond requests per minute (RPM), also set thresholds for tokens per minute (TPM), concurrency, and daily cumulative consumption, configured differently by plan tier;
    • Resale detection: A single key being called heavily from multiple regions with abnormal concurrency in a short window is a typical sign of resale. Combine signals such as call fingerprints, client identifiers, and behavior sequences to assess this, and temporarily freeze and escalate to manual review when necessary;
    • Data security: User prompts may contain business data or personal sensitive information, so encrypt in transit and at rest; avoid retaining raw prompt text in logs and usage details, and desensitize when retention is genuinely required;
    • Content compliance: Apply content-safety policies at both entry and exit to block violating inputs and outputs, and retain the necessary audit records.

    6. Reconciliation, Refunds, and After-Sales: The “Last Mile” of Commoditization

    After model services enter retail channels, reconciliation frequency rises from monthly to daily or even hourly. It is recommended to establish four data sources:

    1. Channel-side payment and refund records;
    2. Internal order and fulfillment status;
    3. The quota ledger entries;
    4. Actual call and usage logs.

    Reconcile through the three-level linkage of “external order ID + idempotency key + request unique ID.” Differences can be handled in three categories:

    Difference type Typical cause Recommended handling
    Under-recorded Usage events lost or delayed Recompute offline using data retained in the logging service, then backfill entries
    Over-recorded Duplicate event delivery, concurrent double deduction Rely on idempotency keys and the ledger’s unique index to dedupe; reverse entries if needed
    Inconsistent basis Different front-end/backend counting methods, different cache-metering rules Cross-check against tokenizer version and price-table version; disclose and explain to users

    For refunds, define the rules for refunding unused quota in advance, and reverse-reduce the ledger through refund entries. For after-sales, provide usage-detail queries and the ability to trace the billing basis back to a specific request, so support staff have evidence to rely on and disputes decrease.

    7. Observability and Capacity Planning

    After commoditization, model-service traffic characteristics resemble those of consumer applications:

    • Short-term peaks may appear around promotions, back-to-school season, and version releases;
    • Intelligent coding tools are called heavily during daytime working hours;
    • User behavior differs markedly across plan tiers.

    Two approaches help here:

    • Monitoring first: Core metrics include call success rate, time-to-first-token latency, tokens-per-minute throughput, quota-deduction failure rate, and the count and amount of reconciliation differences.
    • Balancing capacity and cost: Use container-platform elastic scaling and message-queue peak-shaving to smooth peak traffic onto backend compute; combined with historical consumption data, estimate scaling and procurement pace by plan tier.

    On Baidu AI Cloud, teams can combine cloud building blocks such as containers, message queues, logging, and monitoring to stand up the metering and settlement pipeline these model-service use cases require, then extend it incrementally as their business grows.

    Conclusion

    Model services entering e-commerce channels is fundamentally about turning “compute consumption” into a resource that can be measured, priced, and traded. From an engineering standpoint, what really needs to be answered boils down to four questions:

    • By what basis do we meter?
    • By what model do we bill?
    • How do we deliver quota to users accurately and reliably?
    • How do we continuously keep accounts consistent and risks under control?

    Building metering basis, plan models, the four-layer decoupled architecture, channel distribution, and the security and reconciliation system around these four questions in turn is what lets model services move steadily and sell durably across broader channels.