Quota-Aware Model Pool
Treat each model's daily and per-minute allowance as a design constraint. Spend before sending, prefer scarce models for quality work, fall back when one is spent, and fail with a typed error when all are.
cd examples && pytest inference_and_serving/test_quota_aware_model_pool.pyWhat It Is
A small layer in front of several models, each with its own daily and per-minute limits (a free tier, a team budget, a contract cap). Before each call the pool spends one unit of that model's allowance, chooses the model by the kind of work, and moves to the next model when one is used up, rate-limited or failing. When everything is spent, the caller gets a typed error that says when the allowance resets. The name is ours; it combines a Model Router with a quota ledger.
The Problem It Solves
Free tiers and capped budgets turn every model call into a scarce resource. Without a pool, features fail one at a time in confusing ways: a 429 from one model takes down a feature while another model sits idle; a background job quietly eats the allowance an interactive request needed; and once the quota is gone the user sees a generic error with no hint of when to try again.
How It Works
flowchart TD
R["Request (quality or bulk)"] --> O["Order models:
scarcest first for quality,
roomiest first for bulk"]
O --> M["Next model"]
M --> D{"Daily allowance left
(provider's day)?"}
D -->|"no"| M
D -->|"yes"| P{"Under per-minute limit?"}
P -->|"no"| M
P -->|"yes"| S["Spend one unit, then call"]
S -->|"answer"| A["Return model + answer"]
S -->|"provider: quota gone"| Q["Mark spent for today"] --> M
S -->|"transient error"| RT{"Retries left?"}
RT -->|"yes"| S
RT -->|"no"| M
M -->|"none left"| E["Typed error: BudgetExhausted (retry_after),
RateLimited, or Busy"]
- Describe each model by its limits. Name, requests per day, requests per minute. Keep them in configuration, since providers change them.
- Choose the order by purpose. Quality-sensitive requests try the scarcest (usually strongest) models first. Bulk requests try the roomiest model first and leave the scarce ones alone.
- Spend before sending. Increment the day's counter first. If the process dies or the call times out, you still counted a call you may have been charged for.
- Space calls per model. A per-minute window decides whether a model can take a call now. If it can't, try another model rather than wait.
- Believe the provider. If a model says its daily quota is gone, mark it spent for the day even if your count was lower. Other callers or trials may share the quota.
- Retry only transient failures, a bounded number of times per model, then move on.
- Fail with a type. "Every model is spent" (retry after the reset), "all rate-limited" (retry in a minute) and "all failing" are different answers and should reach the caller as different errors.
- Define the day the way the provider does. If the quota resets at midnight in one time zone, count in that one, not in UTC. Anything else that says "today" (a separate daily cap on a feature, for instance) should use the same day boundary.
When to Use It
- You depend on free or hard-capped model access.
- Several models with different limits can do the same job acceptably.
- You need a feature to degrade predictably when quota runs out.
When NOT to Use It
- One model, pay-as-you-go, no hard cap. A plain Token Budget and a Circuit Breaker are enough.
- The models are not interchangeable. If outputs differ in ways that matter (format, safety behaviour), falling back changes results. Use a Model Router with explicit rules.
- You run many instances with no shared ledger. In-memory counters undercount. Use a shared store or a gateway (LLM Gateway).
Trade-offs
- The ledger is one more thing to keep correct. Counting before the call over-counts failures, which is the safe direction but wastes allowance.
- Fallback means inconsistent answers. The same prompt may be answered by a different model tomorrow. Record which model answered.
- Limits change. Hard-coding last year's free-tier numbers will either waste quota or exceed it. Make them configuration and review them.
Failure Modes
Day boundary mismatch. Your counter resets at midnight UTC and the provider's at midnight Pacific. For hours each day you either refuse allowed calls or exceed the real quota.
Per-instance state. Two instances each believe they have the whole allowance. Share the ledger or divide the limit.
A global lock around spacing. One caller waiting out one model's gap blocks calls to every other model. Keep the lock per model.
Retrying the daily limit. A 429 for a per-day quota is not transient. Distinguish it from a per-minute 429 and stop asking that model.
Implementation Example
A pool with injectable clock, day function and model callables. The tests cover purpose-based ordering, skipping a spent model, the day rollover and its retry_after, per-minute limiting, provider-reported exhaustion, bounded retries, and that a failed call still counts.
cd examples && pytest inference_and_serving/test_quota_aware_model_pool.py"""Quota-Aware Model Pool.
A pool of models, each with a daily and a per-minute allowance (a free tier, or a
budget you set yourself). A request spends one unit of a model's daily allowance
before it is sent, the pool prefers the scarce models for work that needs quality,
and falls back to the next model when one is used up, rate-limited or failing.
When every model is spent the caller gets a typed error saying when to try again.
The ledger here is in memory. With more than one process, keep it in a shared
store and make the spend a single atomic conditional update.
"""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass, field
class BudgetExhausted(Exception):
def __init__(self, retry_after: float):
super().__init__("every model has used its allowance for today")
self.retry_after = retry_after # seconds until the allowance resets
class RateLimited(Exception):
"""Every model with allowance left is over its per-minute limit right now."""
class DailyQuotaSpent(Exception):
"""Raised by a model client when the provider says today's quota is gone."""
class Busy(Exception):
"""Raised by a model client on a transient failure (HTTP 5xx, timeout)."""
@dataclass
class Model:
name: str
per_day: int
per_minute: int
call: Callable[[str], str]
@dataclass
class Pool:
models: list[Model]
now: Callable[[], float]
day_of: Callable[[float], int] # which allowance day a timestamp belongs to
seconds_left_in_day: Callable[[float], float]
attempts: int = 2
used: dict[tuple[int, str], int] = field(default_factory=dict)
recent: dict[str, list[float]] = field(default_factory=dict)
def _spent(self, m: Model, day: int) -> bool:
return self.used.get((day, m.name), 0) >= m.per_day
def _within_minute_limit(self, m: Model, t: float) -> bool:
window = [s for s in self.recent.get(m.name, []) if t - s < 60]
self.recent[m.name] = window
return len(window) < m.per_minute
def complete(self, prompt: str, quality: bool = False) -> tuple[str, str]:
"""Returns (model name, answer)."""
# Quality work tries the scarcest models first; bulk work uses the roomy one first.
order = sorted(self.models, key=lambda m: m.per_day, reverse=not quality)
minute_limited = False
for m in order:
for _ in range(self.attempts):
t = self.now()
day = self.day_of(t)
if self._spent(m, day):
break
if not self._within_minute_limit(m, t):
minute_limited = True
break
# Spend before sending: a crash or a timeout must not leave a free call uncounted.
self.used[(day, m.name)] = self.used.get((day, m.name), 0) + 1
self.recent[m.name].append(t)
try:
return m.name, m.call(prompt)
except DailyQuotaSpent:
self.used[(day, m.name)] = m.per_day # believe the provider over our own count
break
except Busy:
continue
t = self.now()
day = self.day_of(t)
if all(self._spent(m, day) for m in self.models):
raise BudgetExhausted(self.seconds_left_in_day(t))
if minute_limited:
raise RateLimited("try again in a minute")
raise Busy("every available model failed")Tool Landscape
| Tool | Notes |
|---|---|
| LLM gateways (LiteLLM, Portkey, Cloudflare AI Gateway) | Provide shared rate limits and fallbacks across processes |
| Redis / Postgres counters | A shared ledger with an atomic conditional increment |
| Provider usage dashboards | Where to read the real limits and your current consumption |
Related Patterns
- Model Router chooses by task; this chooses by task and remaining allowance.
- LLM Gateway is where a shared ledger usually lives in larger systems.
- Token Budget limits size per request; this limits number of requests.
- Circuit Breaker for LLMs handles failing models; this handles spent ones.
Further Reading
- Rate limits, Gemini API documentation
- Rate Limiting pattern, Azure Architecture Center
- Retry pattern, Azure Architecture Center
Spotted something wrong or have a production story? Edit this page on GitHub.