Skip to content
GenAI Figure

Hands-OnAI Infrastructure & Cloud

Token budgets per tenant: a small gateway in front of a shared model endpoint

Several teams share one model endpoint. A gateway of about 170 lines of standard-library Python gives each tenant a token rate and a daily budget, refuses with 429 or 403, and keeps a ledger per request.

By Sritharan K (opens in a new tab)

Published Updated 12 min read

ConceptualThis article explains a concept. It reports no measured results.

A tenant request is identified, estimated and reserved against the tenant's token bucket and budget, then forwarded. The real usage settles the reservation and lands in the ledger. A request that does not fit gets 429.

Three teams share one model endpoint. One team's batch job can take the whole token rate, and nobody can say which team spent what. The fix for both: a gateway that knows the tenant of every request, gives each tenant a token rate and a spending cap, and records what each request really used.

I build that gateway here in Python 3.12, standard library only, about 170 lines, in front of a local stub that answers like a Chat Completions endpoint. In the load test, the batch tenant gets ten 429 responses with a Retry-After header and then a 403 when its budget of $0.05 per day runs out. The two interactive tenants get all 40 of their requests through.

The diagram plays one request, including the refusal branch.

One request through a token budget gateway

A tenant request is identified, estimated and reserved against the tenant's token bucket and budget, then forwarded. The real usage settles the reservation and lands in the ledger. A request that does not fit gets 429.

requesttenantreserve429, 403 or 413forwardusagerefundrecord200 + answerTenantappIdentifytenantEstimatetokensBucketand budgetLedgerSettleusageModelendpoint

Not started9 steps, listed below.

  1. 1The app sends a Chat Completions request with its tenant key as a Bearer token. The gateway maps the key to a tenant, or answers 401.
  2. 2The gateway estimates the input tokens from the message text and adds max_completion_tokens. That sum is the reservation.
  3. 3Under the tenant's lock it checks the budget, then takes the reservation from the bucket and holds the worst-case cost.
  4. 4Branch: when the bucket or the held budget cannot cover it, the answer is 429 with Retry-After. A spent budget gives 403.
  5. 5When the reservation fits, the gateway forwards the request to the shared model endpoint.
  6. 6The answer carries usage: prompt_tokens and completion_tokens, the real counts.
  7. 7The gateway refunds the reserved tokens the request did not use, releases the held cost and books the real cost.
  8. 8One ledger record: tenant, status, estimated and actual tokens, cost.
  9. 9The app gets the model's answer unchanged.

Conceptual illustration of the order of execution. It is not measured telemetry, and the animation speed does not represent real latency.

What a token budget is#

Each tenant gets two limits:

  • A token rate in tokens per minute, as a token bucket that holds one minute of tokens and refills continuously.
  • A budget in money per day, priced from input and output tokens.

The gateway must decide before the call, but the real counts arrive afterwards, in the answer's usage object. Counting only afterwards lets parallel requests overshoot. The Azure API Management llm-token-limit policy documents exactly that: "concurrent or near-concurrent requests can temporarily exceed the configured token limit".

So this gateway reserves first and settles afterwards. Before the call it takes an estimated worst case from the bucket: estimated input plus max_completion_tokens. After the call it refunds the rest. The budget holds the worst-case cost the same way.

The figure shows one tenant's bucket.

One tenant's token bucket over eight seconds: reservations drop it, refunds and refill raise it, a request for 1,544 tokens at 1,279 gets 429 with Retry-After 3, the retry fits.
Illustration of one bucket at 6,000 tokens per minute. Steps 1 and 2 use the first served batch request of the run below.

How the gateway works#

One request takes six steps:

  1. Identify. The Authorization: Bearer key maps to a tenant, or the answer is 401.
  2. Estimate the input at four characters per token plus four per message: a rough guess, not a tokenizer. Add max_completion_tokens (256 when the client sends none).
  3. Reserve under the tenant's lock: check the budget, take the tokens, hold the worst-case cost.
  4. Forward to the shared endpoint.
  5. Settle with the real usage: refund unused tokens, book the real cost.
  6. Record one ledger entry.

A refused request never reaches the endpoint:

CaseStatusRetry-After
The bucket cannot cover the reservation429Seconds until the refill covers it
Requests in flight hold the rest of the budget4291
The budget for the day is spent403None; resets at 00:00 UTC
The reservation exceeds the bucket's capacity413None; it can never fit
stream, n other than 1, or a bad max_completion_tokens400None

RFC 6585 (opens in a new tab) defines 429 for rate limiting, optionally with Retry-After. A spent budget gets 403 because no retry helps before the next day, as in the llm-token-limit policy.

Each tenant has one lock for its bucket and budget, so check and take are one step; it is not held during the model call. The ledger has its own lock.

Where it fits, and where it does not#

Three tenants call the gateway with a Bearer key. It holds keys, prices, a bucket and budget per tenant and a ledger, forwards to the shared endpoint and refuses with 400, 403, 413 or 429.
The gateway between the tenants and the shared endpoint, with the demo's limits. Prices are illustrations.

It fits a few internal teams on one deployment, and self-hosted servers without per-tenant limits. It does not fit:

  • Several gateway instances. Each process has its own buckets, so the limits multiply. That needs a shared store or a product.
  • Public, billed access that must survive restarts and audits.
  • Mostly streaming traffic. Usage then arrives in the last chunk, only if the client sets stream_options.include_usage. This gateway refuses stream, because an answer it cannot read would go uncounted.

The build#

Three files. The stub is not a model: it counts tokens its own way, picks a random answer length and sleeps to simulate generation. Its response follows the Chat Completions shape, usage object included.

stub_backend.pypython
"""Stub model backend: answers in the Chat Completions shape. Not a model.

Latency and output length are simulated. Python 3.12, standard library only.
"""
import json, random, re, sys, time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer


def count_tokens(text):  # the stub's own tokenizer: words and punctuation marks
    return len(re.findall(r"\w+|[^\w\s]", text))


class Stub(BaseHTTPRequestHandler):
    def do_POST(self):
        body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
        prompt = sum(count_tokens(m["content"]) + 3 for m in body["messages"])
        limit = body.get("max_completion_tokens", 256)
        output = random.randint(limit // 4, limit)  # simulated answer length
        time.sleep(0.05 + output / 1000)  # simulated: 1,000 output tokens per second
        answer = {
            "id": f"chatcmpl-{random.getrandbits(32):08x}", "object": "chat.completion",
            "created": int(time.time()), "model": body["model"],
            "choices": [{"index": 0, "finish_reason": "length" if output == limit else "stop",
                         "message": {"role": "assistant", "content": "lorem " * output}}],
            "usage": {"prompt_tokens": prompt, "completion_tokens": output,
                      "total_tokens": prompt + output},
        }
        data = json.dumps(answer).encode()
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def log_message(self, *args):
        pass


ThreadingHTTPServer(("127.0.0.1", int(sys.argv[1])), Stub).serve_forever()

The gateway makes a random key per tenant at startup and writes them to a file created with mode 600, for the load test. Prices are illustrations. A failed call is settled too: no connection or an error status refunds everything; a timeout or a broken answer books the worst case, since the endpoint may have billed it.

gateway.pypython
"""Token budgets per tenant in front of one shared model endpoint.

Python 3.12, standard library only. All state is in memory in this one process.
Usage: python3.12 gateway.py <gateway port> <backend URL>
"""
import json, math, os, secrets, sys, threading, time, urllib.error, urllib.request
from datetime import datetime, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

PORT, BACKEND = int(sys.argv[1]), sys.argv[2]
# Illustrative prices in USD per 1 million tokens. Not a real price list.
PRICES = {"stub-model": {"input": 2.50, "output": 10.00}}


def cost(model, input_tokens, output_tokens):
    price = PRICES[model]
    return (input_tokens * price["input"] + output_tokens * price["output"]) / 1e6


def estimate_input(messages):
    """A rough guess before the call: 4 characters per token plus 4 per message."""
    return sum(math.ceil(len(m["content"]) / 4) + 4 for m in messages)


def today():
    return datetime.now(timezone.utc).date()


class Tenant:
    def __init__(self, name, tokens_per_minute, budget_per_day):
        self.name, self.key = name, "gw-" + secrets.token_urlsafe(16)
        self.capacity = self.level = float(tokens_per_minute)
        self.rate = tokens_per_minute / 60  # refill in tokens per second
        self.budget, self.spent, self.held = budget_per_day, 0.0, 0.0
        self.day, self.stamp = today(), time.monotonic()
        self.lock = threading.Lock()  # guards level, stamp, spent, held and day

    def _refill(self):  # the caller holds self.lock
        now = time.monotonic()
        self.level = min(self.capacity, self.level + (now - self.stamp) * self.rate)
        self.stamp = now
        if today() != self.day:  # a new budget period
            self.day, self.spent = today(), 0.0

    def reserve(self, tokens, worst_cost):
        """Check and take in one step: returns (verdict, seconds to wait)."""
        with self.lock:
            self._refill()
            if tokens > self.capacity:
                return "too_large", 0
            if self.spent + worst_cost > self.budget:
                return "budget", 0
            if self.spent + self.held + worst_cost > self.budget:
                return "held", 1  # requests in flight hold the rest: try again soon
            if tokens > self.level:
                return "rate", math.ceil((tokens - self.level) / self.rate)
            self.level -= tokens
            self.held += worst_cost
            return "ok", 0

    def settle(self, reserved, used, worst_cost, actual_cost):
        """Give back what the request did not use, or take the overrun."""
        with self.lock:
            self._refill()
            self.level = min(self.capacity, self.level + reserved - used)
            self.held -= worst_cost
            self.spent += actual_cost


TENANTS = {t.key: t for t in [Tenant("batch-etl", 6_000, 0.05),
                              Tenant("support-bot", 8_000, 1.00),
                              Tenant("code-review", 6_000, 0.50)]}
LEDGER, LEDGER_LOCK = [], threading.Lock()


def record(tenant, status, estimated, reserved, used_in=0, used_out=0, usd=0.0):
    entry = {"t": round(time.time(), 3), "tenant": tenant.name, "status": status,
             "estimated_in": estimated, "reserved": reserved, "actual_in": used_in,
             "actual_out": used_out, "cost_usd": round(usd, 6)}
    with LEDGER_LOCK:
        LEDGER.append(entry)


def report():
    with LEDGER_LOCK:
        rows = list(LEDGER)
    totals = {t.name: {"ok": 0, "429": 0, "403": 0, "reserved": 0, "used": 0,
                       "cost_usd": 0.0, "budget_usd": t.budget} for t in TENANTS.values()}
    for r in rows:
        line = totals[r["tenant"]]
        line["cost_usd"] = round(line["cost_usd"] + r["cost_usd"], 6)
        if r["status"] != 200:
            line[str(r["status"])] = line.get(str(r["status"]), 0) + 1
            continue
        line["ok"] += 1
        line["reserved"] += r["reserved"]
        line["used"] += r["actual_in"] + r["actual_out"]
    return {"tenants": totals, "ledger": rows}


class Gateway(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == "/report":
            return self.reply(200, report())
        self.reply(404, {"error": "not found"})

    def do_POST(self):
        auth = self.headers.get("Authorization", "")
        tenant = TENANTS.get(auth.removeprefix("Bearer "))
        if tenant is None:
            return self.reply(401, {"error": "unknown tenant key"})
        body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
        max_out = body.setdefault("max_completion_tokens", 256)  # never forward without a cap
        if (body.get("model") not in PRICES or body.get("stream") or body.get("n", 1) != 1
                or type(max_out) is not int or max_out < 1):
            return self.reply(400, {"error": "needs a known model, no stream, n=1, "
                                             "max_completion_tokens of at least 1"})
        estimated = estimate_input(body["messages"])
        reserved = estimated + max_out
        worst = cost(body["model"], estimated, max_out)

        verdict, wait = tenant.reserve(reserved, worst)
        if verdict != "ok":
            status, message, headers = {
                "rate": (429, "token rate limit, retry later", {"Retry-After": str(wait)}),
                "held": (429, "budget held by requests in flight", {"Retry-After": str(wait)}),
                "budget": (403, "daily budget spent, resets at 00:00 UTC", {}),
                "too_large": (413, "request is larger than the per-minute limit", {}),
            }[verdict]
            record(tenant, status, estimated, reserved)
            return self.reply(status, {"error": message}, headers)

        try:
            request = urllib.request.Request(BACKEND, data=json.dumps(body).encode(),
                                             headers={"Content-Type": "application/json"})
            with urllib.request.urlopen(request, timeout=60) as response:
                answer = json.load(response)
            used_in = answer["usage"]["prompt_tokens"]
            used_out = answer["usage"]["completion_tokens"]
        except urllib.error.URLError:  # no connection or an error status: refund it all
            tenant.settle(reserved, 0, worst, 0.0)
            record(tenant, 502, estimated, reserved)
            return self.reply(502, {"error": "model endpoint failed"})
        except Exception:  # timeout or broken answer: tokens may be billed, book the worst case
            tenant.settle(reserved, reserved, worst, worst)
            record(tenant, 502, estimated, reserved, usd=worst)
            return self.reply(502, {"error": "model endpoint failed, worst case booked"})

        actual = cost(body["model"], used_in, used_out)
        tenant.settle(reserved, used_in + used_out, worst, actual)
        record(tenant, 200, estimated, reserved, used_in, used_out, actual)
        self.reply(200, answer)

    def reply(self, status, payload, headers=None):
        data = json.dumps(payload).encode()
        self.send_response(status)
        for name, value in {"Content-Type": "application/json", **(headers or {})}.items():
            self.send_header(name, value)
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def log_message(self, *args):
        pass


if __name__ == "__main__":
    # Demo only: hand the generated keys to the load test through a private file.
    with open(os.open("tenant-keys.json", os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), "w") as f:
        json.dump({t.name: t.key for t in TENANTS.values()}, f)
    ThreadingHTTPServer(("127.0.0.1", PORT), Gateway).serve_forever()

The load test: the batch tenant on four threads, each interactive tenant on one with 40 small requests.

loadtest.pypython
"""Load test: a batch tenant on four threads, two interactive tenants on one each."""
import json, sys, threading, time, urllib.error, urllib.request

GATEWAY = f"http://127.0.0.1:{sys.argv[1]}"
KEYS = json.load(open("tenant-keys.json"))
START, PRINT, DONE = time.monotonic(), threading.Lock(), threading.Event()


def log(text):
    with PRINT:
        print(f"{time.monotonic() - START:5.1f}s  {text}", flush=True)


def call(tenant, prompt, max_out):
    body = {"model": "stub-model", "max_completion_tokens": max_out,
            "messages": [{"role": "user", "content": prompt}]}
    request = urllib.request.Request(
        GATEWAY + "/v1/chat/completions", data=json.dumps(body).encode(),
        headers={"Authorization": f"Bearer {KEYS[tenant]}", "Content-Type": "application/json"})
    try:
        with urllib.request.urlopen(request, timeout=60) as response:
            return response.status, json.load(response), None
    except urllib.error.HTTPError as error:
        return error.code, json.load(error), error.headers.get("Retry-After")


def batch(prompt):  # until the budget is refused or the test ends
    while not DONE.is_set():
        status, answer, retry_after = call("batch-etl", prompt, 1_000)
        if status != 200:
            log(f"batch-etl {status}  Retry-After: {retry_after}  {answer['error']}")
        if status == 403:
            return
        if status == 429:
            time.sleep(int(retry_after))


def interactive(tenant, prompt, served):
    for _ in range(40):
        served[tenant] += call(tenant, prompt, 150)[0] == 200
        time.sleep(0.5)


long_doc = "Invoice line: 4 units of part A-1042 at 12.50 EUR, shipped 26 November. " * 30
question = "Summarise the open review comments on this pull request in three bullets. " * 4
served = {"support-bot": 0, "code-review": 0}
threads = [threading.Thread(target=batch, args=(long_doc,)) for _ in range(4)]
threads += [threading.Thread(target=interactive, args=(n, question, served)) for n in served]
for t in threads:
    t.start()
for t in threads[4:]:
    t.join()
DONE.set()
for t in threads[:4]:
    t.join()

log(f"interactive requests served of 40: {served}")
with urllib.request.urlopen(GATEWAY + "/report") as response:
    report = json.load(response)
for name, t in report["tenants"].items():
    print(f"{name:<12} ok {t['ok']:>2}  429 {t.get('429', 0)}  403 {t.get('403', 0)}  reserved"
          f" {t['reserved']:>5}  used {t['used']:>5}  ${t['cost_usd']:.4f} of ${t['budget_usd']:.2f}")
for name in report["tenants"]:  # the first served request of each tenant, from the ledger
    print(json.dumps(next(r for r in report["ledger"] if r["tenant"] == name and r["status"] == 200)))

The run#

bash
python3.12 stub_backend.py 18431 &
python3.12 gateway.py 18432 http://127.0.0.1:18431/v1/chat/completions &
python3.12 loadtest.py 18432

The output of a run on 28 November 2026 with Python 3.12.14, with repeated refusals cut. Times and counts change per run.

text
  0.0s  batch-etl 429  Retry-After: 2  token rate limit, retry later
  0.6s  batch-etl 429  Retry-After: 8  token rate limit, retry later
  0.7s  batch-etl 429  Retry-After: 5  token rate limit, retry later
[3 more 429 lines]
  8.6s  batch-etl 429  Retry-After: 5  token rate limit, retry later
 13.7s  batch-etl 429  Retry-After: 1  budget held by requests in flight
[2 more 429 lines]
 14.3s  batch-etl 403  Retry-After: None  daily budget spent, resets at 00:00 UTC
[3 more 403 lines]
 26.6s  interactive requests served of 40: {'support-bot': 40, 'code-review': 40}
batch-etl    ok  6  429 10  403 4  reserved  9264  used  7034  $0.0432 of $0.05
support-bot  ok 40  429 0  403 0  reserved  9120  used  6061  $0.0441 of $1.00
code-review  ok 40  429 0  403 0  reserved  9120  used  6011  $0.0436 of $0.50
{"t": 1795870309.012, "tenant": "batch-etl", "status": 200, "estimated_in": 544, "reserved": 1544, "actual_in": 603, "actual_out": 448, "cost_usd": 0.005987}
{"t": 1795870308.691, "tenant": "support-bot", "status": 200, "estimated_in": 78, "reserved": 228, "actual_in": 55, "actual_out": 133, "cost_usd": 0.001468}
{"t": 1795870308.636, "tenant": "code-review", "status": 200, "estimated_in": 78, "reserved": 228, "actual_in": 55, "actual_out": 83, "cost_usd": 0.000968}

What it shows:

  • The rate limit bites first. A batch request reserves 1,544 tokens, 544 estimated plus 1,000 for the answer. A bucket of 6,000 covers three; the fourth thread gets 429.
  • Holds are not spending. At 13.7 s the requests in flight held the rest of the budget: 429, not 403. My first version answered 403 there, and a batch thread gave up early.
  • Then the budget. After six requests the batch tenant has spent $0.0432. One more could cost $0.0114, which does not fit in $0.05: 403. The last cents stay unused.
  • The interactive tenants are untouched: 40 of 40 each, on their own buckets and budgets.
  • Settling matters: 27,504 tokens reserved, 19,106 used.
  • The estimate misses both ways: 603 input tokens against 544 estimated for the batch prompt, 55 against 78 for the interactive one.

Pros, cons and limits#

Build it yourselfGateway product
FitYour tenants, prices and refusal rulesThe policies the product offers
EffortSmall to start; you own state, failover and auditsConfiguration, plus the product's charges
ScaleOne process, unless you add a shared storeSeveral instances, with documented caveats

Limits of the demo:

  • In memory, one process. A restart loses buckets, spending and ledger.
  • An estimate before the call. The budget can be overrun by the input tokens the estimate missed.
  • Retry-After counts only the refill. Refunds can free tokens sooner, and other threads can take the refill first, so a retry can be refused again, as at 8.6 s.
  • No streaming, no TLS, no authentication on /report, and only the input checks shown.

Build it or buy it#

Build it for a few tenants, one instance and your own rules. Buy it for several instances, identity integration or audited billing. As of 28 November 2026:

  • Azure API Management has the llm-token-limit policy: a token rate and quota per counter key, with optional prompt estimation. It counts per gateway, not across regions.
  • AI Gateway, Microsoft's managed gateway for model and tool traffic, generally available, has policies such as token limits and cost limits on usage and estimated spend. Cost limits can differ per API key or Microsoft Entra identity.
  • Kinference, an open-source control plane for Kubernetes and vLLM from Buoyant (opens in a new tab), latest release v0.1.0-alpha.8, tracks metrics per tenant (opens in a new tab). Its home page lists per-tenant token limits, but its feature page says token-based rate limiting comes in a future release.

Next step: run the three files with your own tenants and prices, then read the section on token counts and estimation in the llm-token-limit policy reference (opens in a new tab).

References

  1. Create chat completion (API reference) (opens in a new tab). OpenAI.
  2. Limit large language model API token usage (llm-token-limit policy) (opens in a new tab). Microsoft Learn.
  3. Use model router with AI Gateway (opens in a new tab). Microsoft Learn.
  4. Token-based rate limiting (opens in a new tab). Kinference.