Multi-Model Quota Calculation: Pricing, Reconciliation, and Preventing Double Deductions

    As AI platforms integrate multiple models with varying inference capabilities and resource costs, calculating usage quotas and preventing double deductions become critical. This article explores a scalable multi-model architecture covering model routing, metering boundaries, and atomic deduction implementation. It details how to handle token and non-token usage, ensure idempotent deductions with a ledger system, manage streaming tasks with frozen quotas, and design a robust rules engine for limited-time discounts.

    1. Background

    Early intelligent office and development tools typically offered only a single model. As the number of available models increases, the differences in inference capabilities, response speeds, and resource overheads grow significantly. Processing the same task with different models can consume several times more computing power. If a platform still charges based on request counts or a uniform token count, users lack a basis for selection, and costs are difficult to attribute to specific features.

    Multi-model integration must therefore answer three questions: how to uniformly access different models, how to let users or systems select models based on tasks, and how to convert the resource consumption of different models into a unified quota standard.

    This article addresses these three questions and answers several common queries: how to reconcile multi-model quotas, how to prevent double deductions, whether cache hits should be billed separately, and how to restore the original price when multiple limited-time discounts overlap.

    2. Layered Integration and Model Routing

    A scalable multi-model system typically consists of four layers:

    1. Model Registry Layer: Records model identifiers, capability tags, pricing multipliers, and enabled status.
    2. Adapter Layer: Converts unified requests into the call format of each model, masking differences in parameters and return values.
    3. Routing and Selection Layer: Determines which model will handle the current request based on user selection, task type, or fallback strategy.
    4. Metering and Quota Layer: Records actual consumption and deducts account quota according to pricing rules.

    Model registry information is centrally managed, and business code does not hardcode model names. In the following registry example, fields and values are for demonstration only and do not represent real prices.

    1. from decimal import Decimal
    2. MODEL_REGISTRY = {
    3. "model-a": {
    4. "tier": "general",
    5. "capabilities": {"chat", "code"},
    6. "input_multiplier": Decimal("1.0"),
    7. "cache_multiplier": Decimal("0.2"),
    8. "output_multiplier": Decimal("1.0"),
    9. "cost_calibrated_at": "2026-10-01",
    10. "calibration_basis": "Vendor pricing page, 2026-10 version",
    11. "enabled": True,
    12. "rollout_percent": 100,
    13. },
    14. "model-b": {
    15. "tier": "light",
    16. "capabilities": {"chat"},
    17. "input_multiplier": Decimal("0.5"),
    18. "cache_multiplier": Decimal("0.1"),
    19. "output_multiplier": Decimal("0.5"),
    20. "cost_calibrated_at": "2026-10-01",
    21. "calibration_basis": "Vendor pricing page, 2026-10 version",
    22. "enabled": True,
    23. "rollout_percent": 100,
    24. },
    25. }

    The purpose of each field is as follows:

    • capabilities: Capability tags. Uses enumeration values maintained uniformly by the team to avoid inconsistent spelling across different locations.
    • cache_multiplier: The multiplier for cache hit inputs. Usually the ratio of the vendor’s cache unit price to the standard input unit price; it cannot directly use the standard input multiplier.
    • cost_calibrated_at: The date of the last multiplier calibration. Exceeding an agreed cycle (e.g., 30 days) triggers a review.
    • calibration_basis: Calibration basis. Records which version of the price list the multiplier comes from, facilitating verification during disputes.
    • rollout_percent: Grayscale rollout percentage. New models can be opened to a small portion of accounts first, and fully rolled out after confirming cost and stability.

    The routing layer relies solely on the registry. When adding a new model, simply supplement the registry information and adapter; the billing and interface logic need no changes. Routing failures (model not enabled or outside the grayscale range) should return a clear error and select an alternative model according to a pre-configured fallback order. After fallback, billing uses the alternative model’s multiplier, and the ledger records the model actually executed.

    3. Metering Boundaries: Defining Base Usage

    “Total input plus output token count multiplied by a multiplier” is only the simplest case. Before implementation, the following boundaries must be clearly defined.

    First, total input and cache hits must be separated. The input token count returned by most vendors already includes the cache hit portion. If you multiply this total directly by the standard input multiplier, the cache portion will be billed twice. Therefore, subtraction must be done before accounting:

    Uncached input tokens = Total input tokens - Cache hit tokens

    The ledger stores uncached input tokens (base_in) and cache hit tokens (base_cache_hit) separately; their sum equals the total input.

    Second, input, cache, and output use different multipliers. Most models have higher output overheads than inputs, so input and output multipliers are configured separately. Cache hits use a dedicated cache multiplier.

    The billing formula is as follows:

    Actual deducted quota = Uncached input tokens × Effective input multiplier + Cache hit tokens × Effective cache multiplier + Output tokens × Effective output multiplier

    Where the effective multiplier is provided by the rules engine in Section 5. Without any active promotions, the effective multiplier equals the base multiplier in the registry.

    Consider a numerical example. A request has a total input of 5,000 tokens, of which 4,000 hit the cache, and 500 output tokens. Assuming the effective multipliers for this period are 0.3 for input, 0.03 for cache, and 0.3 for output:

    • Uncached input: 1000 × 0.3 = 300
    • Cache hit: 4000 × 0.03 = 120
    • Output: 500 × 0.3 = 150
    • Total: 570.0000 quota

    Third, non-token usage must define base units. Image generation is billed per piece, voice per second, and tool calls per invocation. Each type of usage first declares its base unit and quota conversion factor in the registry, and is then uniformly converted into quota. For example, a standard resolution image counts as 1 base unit, and high-resolution tiers are multiplied by a tier factor.

    When converting non-token usage, it is recommended to check the following points item by item:

    • Are base units written into the registry rather than scattered in the calling code?
    • Are failed requests billed? The recommended rule is not to bill if the model does not return a valid result, and to record the failure reason in the ledger.
    • Is there a limit on the number of tool calls, and is the handling of excess parts clearly defined?
    • Do multiple billing items for the same request enter the same ledger entry, correlated using the same request_id?

    Fourth, precision and rounding. Quota is stored as a decimal number, not a floating-point number. The balance field in the database uses the DECIMAL type. The calculation process retains enough digits, and rounding to 0.0001 (ROUND_HALF_UP) is performed only once at the final total of a request, with the rounding rule uniformly specified in the code. Rounding item by item accumulates errors, leading to reconciliation mismatches.

    The completeness of the ledger records is more important than the calculation itself. In the event of a dispute, only a ledger that retains base usage, multipliers, and rule versions can restore the entire process of a deduction.

    4. Deduction Implementation: Idempotency, Atomicity, and Ledger

    The deduction logic must simultaneously handle three types of risks: the same request being submitted repeatedly, concurrent requests competing for the same account balance, and a successful deduction but a failed ledger write. The following code covers these three risks in a single transaction. Here, UniqueViolation represents the unique constraint conflict exception thrown by the database driver.

    1. import json
    2. from decimal import Decimal, ROUND_HALF_UP
    3. QUANT = Decimal("0.0001")
    4. class QuotaExceeded(Exception):
    5. pass
    6. class TransientError(Exception):
    7. pass
    8. def compute_charge(base_in, base_cache_hit, base_out, prices):
    9. raw = (Decimal(base_in) * prices["input"]
    10. + Decimal(base_cache_hit) * prices["cache"]
    11. + Decimal(base_out) * prices["output"])
    12. return raw.quantize(QUANT, rounding=ROUND_HALF_UP)
    13. def deduct_quota(db, req):
    14. # req fields: request_id, account_id, model_id, base_in, cache_hit_tokens,
    15. # base_out, user_groups, occurred_at (UTC time)
    16. try:
    17. with db.transaction():
    18. # 1. Idempotency: The same request_id is recorded only once
    19. done = db.ledger.find_one(request_id=req.request_id)
    20. if done is not None:
    21. return done.charged
    22. # 2. Calculate effective multipliers and the deduction amount for this request
    23. prices, versions = resolve_price(
    24. req.model_id, req.user_groups, req.occurred_at, is_holiday
    25. )
    26. charge = compute_charge(
    27. req.base_in, req.cache_hit_tokens, req.base_out, prices
    28. )
    29. # 3. Atomic deduction: Conditional update, affected row count is 0 if balance is insufficient
    30. updated = db.execute(
    31. "UPDATE accounts SET balance = balance - %s "
    32. "WHERE id = %s AND balance >= %s",
    33. (charge, req.account_id, charge),
    34. )
    35. if updated.rowcount == 0:
    36. raise QuotaExceeded(req.account_id, required=charge)
    37. # 4. Append-only ledger, saving price snapshot and rule versions
    38. db.ledger.insert(
    39. request_id=req.request_id,
    40. account_id=req.account_id,
    41. model_id=req.model_id,
    42. base_in=req.base_in,
    43. base_cache_hit=req.cache_hit_tokens,
    44. base_out=req.base_out,
    45. multiplier_in=prices["input"],
    46. multiplier_cache=prices["cache"],
    47. multiplier_out=prices["output"],
    48. rule_version=json.dumps(versions, sort_keys=True),
    49. charged=charge,
    50. )
    51. return charge
    52. except UniqueViolation:
    53. # Another concurrent request has already completed the accounting.
    54. # The transaction above has rolled back, and the balance was not deducted twice.
    55. existing = db.ledger.find_one(request_id=req.request_id)
    56. if existing is None:
    57. raise TransientError(req.request_id)
    58. return existing.charged

    Key points of this code include:

    • The conditional update (balance >= charge) performs the balance check and deduction in the same statement, avoiding concurrent over-deductions caused by “read-then-write”.
    • The ledger’s request_id has a unique index. When two concurrent requests pass the idempotency check simultaneously, the latter insertion fails due to the unique constraint, the entire transaction rolls back, and the balance is not deducted twice.
    • After the unique constraint conflict is caught, the code reads the existing ledger record and returns the original result. The caller receives the same charged value as the first request.
    • If the record cannot be found after the conflict, it indicates an abnormal state, and a TransientError is raised. The caller should retry using the same request_id, and the idempotency check ensures no duplicate deduction.

    The caller’s handling can be summarized in the following table.

    Return Result Meaning Caller Action
    Returns charged Deduction successful Continue processing the request
    Returns existing charged Duplicate request or concurrent conflict Use the original result directly, do not call the model again
    QuotaExceeded Insufficient balance Reject the request, prompt for recharge or switch to a lower-cost model
    TransientError Abnormal state Retry with the same request_id

    The ledger table structure is as follows:

    1. CREATE TABLE quota_ledger (
    2. id BIGINT PRIMARY KEY,
    3. request_id VARCHAR(64) NOT NULL UNIQUE,
    4. entry_type VARCHAR(16) NOT NULL DEFAULT 'charge',
    5. ref_request_id VARCHAR(64) NULL,
    6. account_id BIGINT NOT NULL,
    7. model_id VARCHAR(64) NOT NULL,
    8. base_in INT NOT NULL,
    9. base_cache_hit INT NOT NULL DEFAULT 0,
    10. base_out INT NOT NULL,
    11. multiplier_in DECIMAL(10,4) NOT NULL,
    12. multiplier_cache DECIMAL(10,4) NOT NULL,
    13. multiplier_out DECIMAL(10,4) NOT NULL,
    14. rule_version VARCHAR(255) NOT NULL,
    15. charged DECIMAL(18,4) NOT NULL,
    16. created_at TIMESTAMP NOT NULL
    17. );

    The ledger is append-only; historical records are not modified. When a deduction needs to be reversed, a reversal entry is written: entry_type is reversal, request_id uses the original record with a suffix (e.g., req-001:rev), ref_request_id points to the original record, and charged is the negative of the original amount. The unique constraint on request_id also prevents the same deduction from being reversed twice.

    Streaming Output and Long Tasks: Pre-freeze, Post-settle

    Streaming output or long tasks cannot determine usage at the start. These requests adopt a “pre-freeze, post-settle” approach:

    1. Before the request starts, freeze the quota based on the estimated upper limit (cap); the frozen record status is FROZEN.
    2. After the task is completed, settle based on the actual amount (actual), release the difference between cap and actual, and change the status to SETTLED.
    3. If the task fails or times out, release all frozen quota, and the status changes to RELEASED.

    The state can only flow unidirectionally from FROZEN. Settlement and release both use conditional updates to check the current status, preventing the same freeze from being settled twice. The accounts table needs to add a frozen field to record the currently frozen quota.

    1. -- Freeze: Pre-deduct the upper limit amount
    2. UPDATE accounts
    3. SET balance = balance - :cap, frozen = frozen + :cap
    4. WHERE id = :acc AND balance >= :cap;
    5. -- Settle: Release the difference based on the actual amount
    6. UPDATE accounts
    7. SET frozen = frozen - :cap, balance = balance + :cap - :actual
    8. WHERE id = :acc AND frozen >= :cap;

    During settlement, the frozen record’s status needs to be changed from FROZEN to SETTLED, and only executed if the status is still FROZEN. The two steps are completed in the same transaction. actual must not be greater than cap. Excess parts beyond the upper limit should be truncated or rejected on the model call side, and the account balance must not be allowed to go negative.

    5. Designing Limited-Time Discount Rules

    Limited-time discounts usually take two forms: directly replacing the multiplier for a specified model (override), or discounting the original multiplier (discount). Both should be managed by the same rules engine and not scattered in conditional logic within the business code.

    The rule design needs to clarify the following:

    • Timezone: Rules are interpreted in a unified timezone (in this example, America/New_York), while the database stores everything in UTC.
    • Time Window: Uses a left-closed, right-open interval [start, end). Exactly 02:00 is no longer in the period ending at 02:00. All-day rules have the same start and end times.
    • Holiday Source: Holidays and working days are provided by a versioned calendar service, and the calendar version number is also written to the ledger.
    • Target Objects: Each rule specifies the applicable set of models and user groups. All accounts have the group:all tag by default.
    • Multiplier Range: Override rules must provide all three multipliers: input, cache, and output. Discount rules apply to all three dimensions simultaneously.
    • Stacking Order: For each request, first take the highest priority override rule, then take the highest priority discount rule, and finally truncate at the minimum multiplier limit. Rules of the same kind do not stack.
    • Minimum Multiplier: The effective multiplier cannot be lower than MIN_MULTIPLIER, preventing configuration errors from resulting in zero or negative prices.

    The rule definition and matching code are as follows:

    1. from datetime import time
    2. from zoneinfo import ZoneInfo
    3. TZ = ZoneInfo("America/New_York")
    4. MIN_MULTIPLIER = Decimal("0.1")
    5. DIMS = ("input", "cache", "output")
    6. RULES = [
    7. {
    8. "id": "promo-night-override",
    9. "version": 3,
    10. "kind": "override",
    11. "priority": 10,
    12. "value": {"input": Decimal("0.3"),
    13. "cache": Decimal("0.03"),
    14. "output": Decimal("0.3")},
    15. "models": {"model-b"},
    16. "users": {"group:beta"},
    17. "window": (time(22, 0), time(23, 59)),
    18. "days": "any",
    19. },
    20. {
    21. "id": "evening-discount",
    22. "version": 1,
    23. "kind": "discount",
    24. "priority": 5,
    25. "value": Decimal("0.9"),
    26. "models": {"model-a"},
    27. "users": {"group:all"},
    28. "window": (time(20, 0), time(2, 0)),
    29. "days": "any",
    30. },
    31. {
    32. "id": "weekend-discount",
    33. "version": 2,
    34. "kind": "discount",
    35. "priority": 8,
    36. "value": Decimal("0.8"),
    37. "models": {"model-a", "model-b"},
    38. "users": {"group:all"},
    39. "window": (time(0, 0), time(0, 0)),
    40. "days": "holiday",
    41. },
    42. ]
    43. def is_active(rule, now_local, is_holiday):
    44. start, end = rule["window"]
    45. t = now_local.time()
    46. if start == end:
    47. in_window = True
    48. elif start < end:
    49. in_window = start <= t < end
    50. else:
    51. # Periods crossing midnight are evaluated in two segments
    52. in_window = t >= start or t < end
    53. if not in_window:
    54. return False
    55. if rule["days"] == "any":
    56. return True
    57. day_kind = "holiday" if is_holiday(now_local.date()) else "workday"
    58. return rule["days"] == day_kind
    59. def resolve_price(model_id, user_groups, occurred_at, is_holiday):
    60. model = MODEL_REGISTRY[model_id]
    61. now_local = occurred_at.astimezone(TZ)
    62. matched = [
    63. r for r in RULES
    64. if model_id in r["models"]
    65. and r["users"] & user_groups
    66. and is_active(r, now_local, is_holiday)
    67. ]
    68. overrides = sorted((r for r in matched if r["kind"] == "override"),
    69. key=lambda r: (-r["priority"], r["id"]))
    70. discounts = sorted((r for r in matched if r["kind"] == "discount"),
    71. key=lambda r: (-r["priority"], r["id"]))
    72. top_override = overrides[0] if overrides else None
    73. top_discount = discounts[0] if discounts else None
    74. prices = {}
    75. for dim in DIMS:
    76. value = model[f"{dim}_multiplier"]
    77. if top_override:
    78. value = top_override["value"][dim]
    79. if top_discount:
    80. value = value * top_discount["value"]
    81. prices[dim] = max(value, MIN_MULTIPLIER)
    82. applied = [r for r in (top_override, top_discount) if r is not None]
    83. versions = {r["id"]: r["version"] for r in applied}
    84. return prices, versions

    In the code, the keys of the model dictionary are input_multiplier, cache_multiplier, and output_multiplier, corresponding one-to-one with the values in DIMS.

    The following table lists the calculation results for several typical scenarios. The values are illustrative and explain the stacking logic.

    Scenario Matched Rule Effective Multiplier (Input / Cache / Output)
    model-b, workday 22:30, beta group promo-night-override 0.3 / 0.03 / 0.3
    model-b, holiday 10:00, all users weekend-discount 0.4 / 0.08 / 0.4
    model-b, holiday 22:30, beta group promo-night-override 0.3 / 0.03 / 0.3