Lesson 08 · 40 minutes
Control cost and capacity with budgets, load shedding and a capacity estimate
- Give each client a daily budget in requests and tokens
- Estimate capacity from a measured request time
- Shed load in the gateway with a 503 and a retry hint, and read the effect of each limit
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
Finance has two questions about the model service. "What is the most that one client can cost us in a day?" and "How many requests a second can we take before it falls over?" The rate limit of lesson 3 answers neither: it limits the speed, not the total, and it knows nothing about the capacity of the service. You add a budget for each client and a way to say "not now" when the service is full, and you calculate the capacity from a number that you measure.
Recall
Lesson 3: what does the rate limit do when a key sends 20 requests in one second and the limit is 5 in 60 seconds?
It lets 5 pass and refuses 15 with 429 and a Retry-After hint. After the window the key may send again.
Lesson 3: which status does an unknown key get, and which a body that is too large?
401 for an unknown key (the authenticate stage) and 413 for a body over max_body (limit_size).
The idea
Four limits protect cost and capacity, and each one answers a different question. Lesson 7 of "Web applications and APIs" and lesson 8 of "Securing LLM applications" cover the first three. New here are budgets in units, load shedding and a capacity estimate.
| Limit | Question | A client that exceeds it gets |
|---|---|---|
| Body size | How much may one request cost to read? | 413 |
| Rate per key | How fast may one client go? | 429 and Retry-After |
| Daily budget | How much may one client use in a day? | 429, and a header with what is left |
| Load shedding | Is the service full right now? | 503 and Retry-After |
A budget counts requests and units. For a language model a unit is a token, a piece of text. Our classifier has no tokens, so the gateway estimates one unit for every 4 bytes of the body, as many gateways do before the model reports the real count. A budget also limits a stolen key: a thief spends only what is left of one day.
Capacity follows from two numbers. If one request needs t seconds of a worker and you have w workers, you can finish w / t requests a second. Never plan for 100 percent: near it the queue grows quickly, and a target of about 70 percent leaves room. Little's law says that the number of requests in service equals the arrival rate times the time of one request.
A queue turns a burst into a delay, and a full queue must refuse. Load shedding refuses at once, with a 503 and a hint for when to come back, so that the admitted requests still finish in time. The gateway of this course keeps no queue: it admits a request when fewer than max_inflight are in service, and sheds it otherwise. The replay in step 4 shows what a queue would change.
- Client → Gateway: request
- Gateway: fewer than max_inflight in service?
- Gateway → Service: yes, forward it
- Gateway → Client: no, 503 and Retry-After
Worked example
1. Write the settings
gateway.json gets two new numbers: max_inflight (the requests that may be in service at once) and service_ms (the time of one request, which the gateway uses for the retry hint). 20 ms is a planning value for a heavier model than this one; step 5 measures the real time. budget.json gives each client its limits for one day (the requests below use 11 units each, so 100 requests come first). A client that is not in the file gets 403.
cat > gateway.json <<'EOT'
{"rate": 100, "window": 60, "max_body": 1024, "max_inflight": 4, "service_ms": 20}
EOT
cat > budget.json <<'EOT'
{"alpha": {"requests": 100, "units": 2000}, "beta": {"requests": 100, "units": 2000}}
EOT2. Update the gateway, then save the budget and the load stages
The gateway needs four changes. INFLIGHT counts the requests in service now. context carries that count as inflight, so that a test can set it. forward adds one before the call to the service and takes it off after. A start-up loop imports each module that KR_EXTRA names (for example KR_EXTRA=budget) and calls its install function, which adds stages. Every other line is the same as in lesson 3. Replace gateway.py with the finished file; the block is collapsed, so open it only to copy it or to compare.
The finished file: gateway.py
gateway.py
"""gateway.py: the only door to the model service. It checks, counts, writes an audit line and forwards."""
import importlib
import json
import os
import sys
import threading
import time
import urllib.error
import urllib.request
from datetime import date
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import keystore
CONFIG = {"rate": 5, "window": 60, "max_body": 1024} # gateway.json replaces these at start
SERVICE = os.environ.get("KR_SERVICE", "http://127.0.0.1:8421")
TOKEN = os.environ.get("KR_GATEWAY_TOKEN", "")
AUDIT, KEYS = "audit.log", "keys.json"
HITS, INFLIGHT, LOCK = {}, [0], threading.Lock() # INFLIGHT[0] counts the requests that are being served now
def route(ctx):
if ctx["path"] != "/predict":
return 404, "not found"
if ctx["method"] != "POST":
return 405, "use POST"
def authenticate(ctx):
auth = ctx["headers"].get("Authorization", "")
record = keystore.lookup(auth[7:], ctx["today"], KEYS) if auth[:7].lower() == "bearer " else None
if not record:
ctx["out"]["WWW-Authenticate"] = "Bearer"
return 401, "missing, unknown or expired key"
ctx["client"], ctx["key_id"] = record["client"], record["id"]
if "predict" not in record["scopes"]:
return 403, "this key may not call predict"
def limit_size(ctx):
if ctx["length"] > CONFIG["max_body"]:
return 413, f"body over {CONFIG['max_body']} bytes"
def limit_rate(ctx):
with LOCK:
hits = [t for t in HITS.get(ctx["key_id"], []) if ctx["now"] - t < CONFIG["window"]]
allowed = len(hits) < CONFIG["rate"]
if allowed:
hits.append(ctx["now"])
else:
ctx["out"]["Retry-After"] = str(int(CONFIG["window"] - (ctx["now"] - hits[0])) + 1)
HITS[ctx["key_id"]] = hits
if not allowed:
return 429, "too many requests"
STAGES = [route, authenticate, limit_size, limit_rate]
def context(method, path, headers, length, now=None, today=None, inflight=None):
"""What the stages need to know about one request. `out` holds headers for the answer."""
return {"method": method, "path": path, "length": length, "out": {},
"headers": {name.title(): value for name, value in headers.items()},
"now": time.monotonic() if now is None else now, "today": today or date.today().isoformat(),
"inflight": INFLIGHT[0] if inflight is None else inflight}
def decide(ctx):
"""Run the stages in order. The first one that objects decides: (status, message)."""
for stage in STAGES:
verdict = stage(ctx)
if verdict:
return verdict
return 200, "allowed"
def audit(ctx, status, reason):
line = {"time": time.strftime("%Y-%m-%dT%H:%M:%S"), "client": ctx.get("client", "-"), "key": ctx.get("key_id", "-"),
"path": ctx["path"].split("?")[0][:40], "status": status, "reason": reason, "bytes": ctx["length"]}
with open(AUDIT, "a") as f:
f.write(json.dumps(line) + "\n")
def forward(ctx, body):
headers = {"Content-Type": ctx["headers"].get("Content-Type", ""), "X-Gateway-Token": TOKEN, "X-Client": ctx["client"]}
with LOCK:
INFLIGHT[0] += 1
try:
with urllib.request.urlopen(urllib.request.Request(SERVICE + "/predict", body, headers), timeout=5) as r:
return r.status, r.read()
except urllib.error.HTTPError as error:
return error.code, error.read()
except OSError:
return 502, b'{"error": "service unavailable"}'
finally:
with LOCK:
INFLIGHT[0] -= 1
class Handler(BaseHTTPRequestHandler):
server_version, sys_version = "kr-gateway", ""
timeout = 10 # a silent client cannot hold a thread for ever
def handle_one(self):
try:
length = max(0, int(self.headers.get("Content-Length") or 0))
except ValueError:
length = -1
ctx = context(self.command, self.path, self.headers, length)
status, reason = (400, "bad Content-Length") if length < 0 else decide(ctx)
if status == 200:
status, answer = forward(ctx, self.rfile.read(length))
reason = "forwarded"
else:
answer = json.dumps({"error": reason}).encode()
audit(ctx, status, reason)
self.send_response(status)
for name, value in ctx["out"].items():
self.send_header(name, value)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(answer)))
self.end_headers()
self.wfile.write(answer)
do_GET = do_POST = do_PUT = do_DELETE = handle_one
def log_message(self, *args):
pass
def load_config(path="gateway.json"):
with open(path) as f:
CONFIG.update(json.load(f))
if not all(isinstance(CONFIG.get(k), int) and CONFIG[k] > 0 for k in ("rate", "window", "max_body")):
sys.exit("gateway.json needs positive numbers for rate, window and max_body")
if __name__ == "__main__":
if not TOKEN:
sys.exit("set KR_GATEWAY_TOKEN first")
load_config()
for name in filter(None, os.environ.get("KR_EXTRA", "").split(",")):
importlib.import_module(name).install(STAGES, CONFIG)
server = ThreadingHTTPServer(("127.0.0.1", int(sys.argv[1]) if len(sys.argv) > 1 else 8420), Handler)
print("gateway ready, stages:", [s.__name__ for s in STAGES], file=sys.stderr, flush=True)
server.serve_forever()check_budget adds the request and its units to what the client has spent today. check_load sheds. The retry hint is the time in which the requests in service would finish, rounded up to whole seconds, and at least 1. install adds the load stage before the budget stage, after the stages of lesson 3. A shed request is therefore not charged to the budget, but it still counts for the rate limit. The budget check and the count happen in one locked step, as in lesson 3, because the gateway serves requests in parallel threads.
budget.py
"""budget.py: a daily budget for each client, and load shedding. The gateway loads it with KR_EXTRA=budget."""
import json
import math
import threading
LOCK = threading.Lock() # the gateway serves requests in parallel threads
BUDGETS, SPENT = {}, {} # budget.json, and what each client spent today: (client, day) -> [requests, units]
CONFIG = {}
def units_of(length):
"""An estimate of the tokens in a body: one token for every 4 bytes. A real gateway counts what the model reports."""
return length // 4 + 1
def check_budget(ctx):
budget = BUDGETS.get(ctx["client"])
if budget is None:
return 403, "this client has no budget"
units = units_of(ctx["length"])
with LOCK: # the check and the count are one step, so two parallel requests cannot both take the last place
spent = SPENT.setdefault((ctx["client"], ctx["today"]), [0, 0])
if spent[0] + 1 > budget["requests"] or spent[1] + units > budget["units"]:
return 429, "daily budget used"
spent[0] += 1
spent[1] += units
left = budget["requests"] - spent[0]
ctx["out"]["X-Budget-Requests-Left"] = str(left)
def check_load(ctx):
"""Shed at once when `max_inflight` requests are being served: a 503 with a hint for when to come back."""
if ctx["inflight"] >= CONFIG["max_inflight"]:
wait = ctx["inflight"] * CONFIG["service_ms"] / 1000 / CONFIG["max_inflight"]
ctx["out"]["Retry-After"] = str(max(1, math.ceil(wait)))
return 503, "busy, try again later"
def install(stages, config, path="budget.json"):
"""Called by the gateway. The load stage comes before the budget stage, so that a shed request is not charged."""
CONFIG.update(config)
with open(path) as f:
BUDGETS.update(json.load(f))
stages.extend([check_load, check_budget])3. Save the capacity script
capacity is the calculation. replay runs a list of arrival times (in milliseconds) through workers workers and a queue of queue_max places, and reports how many requests were served, how many were shed, and the longest wait. It is a small simulation, so it gives the same answer on every machine.
capacity.py
"""capacity.py: estimate the capacity of a service, and replay a burst through a queue."""
def capacity(service_ms, workers, target=0.7):
"""Requests per second that the service can take. `target` keeps some room: a queue grows fast near 100 percent."""
return round(workers * 1000 / service_ms * target, 1)
def replay(arrivals_ms, service_ms, workers, queue_max):
"""Replay requests that arrive at the given times (in ms). A request that finds every worker busy and a full queue is shed.
Return (served, shed, longest wait in ms)."""
free_at = [0] * workers # when each worker is free again
starts = [] # when every accepted request starts
served = shed = longest = 0
for t in arrivals_ms:
waiting = sum(1 for s in starts if s > t)
worker = min(range(workers), key=free_at.__getitem__)
if free_at[worker] > t and waiting >= queue_max:
shed += 1
continue
start = max(t, free_at[worker])
free_at[worker] = start + service_ms
starts.append(start)
served += 1
longest = max(longest, start - t)
return served, shed, longest
if __name__ == "__main__":
burst = [i * 5 for i in range(20)] # 20 requests, one every 5 ms: 200 requests a second
print("capacity at 12 ms and 4 workers:", capacity(12, 4), "requests a second")
print("workers queue served shed longest wait")
for workers, queue in [(2, 0), (2, 5), (2, 100), (4, 0), (4, 5)]:
served, shed, wait = replay(burst, 30, workers, queue)
print(f"{workers:7} {queue:5} {served:7} {shed:4} {wait:7} ms")4. Run the tests, then the replay
test_budget.py checks the stages with fixed numbers: a budget of 100 requests and 400 units admits 15 requests of 100 bytes (26 units each), a client without a budget gets 403, and 20 requests that arrive while the count of requests in service grows are split into 4 admitted and 16 shed. Open the block and save the file.
The finished file: test_budget.py
test_budget.py
"""test_budget.py: tests for the budget, the load shedding and the capacity script."""
import unittest
import budget
import capacity
import gateway
DAY = "2026-11-30"
budget.BUDGETS.update({"alpha": {"requests": 100, "units": 400}, "tiny": {"requests": 2, "units": 1000}})
budget.CONFIG.update(max_inflight=4, service_ms=20)
class BudgetTests(unittest.TestCase):
def setUp(self):
budget.SPENT.clear()
def test_units_budget_allows_15_requests_of_100_bytes(self):
results = [budget.check_budget(self._ctx(100)) for _ in range(20)]
self.assertEqual(sum(r is None for r in results), 15)
def test_requests_budget(self):
results = [budget.check_budget(self._ctx(10, "tiny")) for _ in range(5)]
self.assertEqual(sum(r is None for r in results), 2)
def test_unknown_client_has_no_budget(self):
self.assertEqual(budget.check_budget(self._ctx(10, "nobody"))[0], 403)
def test_load_shedding(self):
busy, shed, hints = 0, 0, set()
for _ in range(20):
ctx = self._ctx(10, inflight=busy)
if budget.check_load(ctx):
shed += 1
hints.add(ctx["out"]["Retry-After"])
else:
busy += 1
self.assertEqual((busy, shed, hints), (4, 16, {"1"}))
def test_capacity(self):
self.assertEqual(capacity.capacity(12, 4), 233.3)
self.assertEqual(capacity.replay([i * 5 for i in range(20)], 30, 2, 5), (13, 7, 85))
def _ctx(self, length, client="alpha", inflight=0):
ctx = gateway.context("POST", "/predict", {}, length, today=DAY, inflight=inflight)
ctx["client"] = client
return ctx
if __name__ == "__main__":
unittest.main()Then run them.
python test_budget.py
python capacity.py.....
----------------------------------------------------------------------
Ran 5 tests in 0.001s
OK
capacity at 12 ms and 4 workers: 233.3 requests a second
workers queue served shed longest wait
2 0 8 12 0 ms
2 5 13 7 85 ms
2 100 20 0 180 ms
4 0 14 6 0 ms
4 5 19 1 40 msWith a queue of 100, nothing is shed, but the longest wait is 180 ms: the burst has become a delay. Four workers with no queue still shed 6, because 4 workers cannot take 200 requests a second at 30 ms each (the capacity is 133). More workers or a shorter request time is the only real cure.
5. Measure the request time
Capacity needs a measured time. Start the service and send 200 requests, one after the other. The median is the middle value, and the 95th percentile is the value that 95 percent of the requests beat.
export KR_GATEWAY_TOKEN=$(cat secrets/gateway.token)
python service.py 8421 2> service.log > /dev/null &
echo $! > service.pid
sleep 1
python - <<'EOT'
import json, os, time, urllib.request
body = json.dumps({"failed": 5, "new_device": 1, "km": 100}).encode()
headers = {"Content-Type": "application/json", "X-Gateway-Token": os.environ["KR_GATEWAY_TOKEN"]}
times = []
for _ in range(200):
start = time.perf_counter()
urllib.request.urlopen(urllib.request.Request("http://127.0.0.1:8421/predict", body, headers)).read()
times.append((time.perf_counter() - start) * 1000)
times.sort()
print(f"median {times[100]:.1f} ms, 95th percentile {times[190]:.1f} ms")
EOTmedian 1.3 ms, 95th percentile 3.5 msThis is about one millisecond because the model is a few multiplications. Your number will differ. A real model needs far longer, and then the same calculation gives a small capacity. Plan with the 95th percentile, not the median.
6. Shed load for real
Start the gateway with the extra stage. Send 60 requests, 30 at a time (xargs -P 30 runs 30 commands at once), and count the status codes.
KR_EXTRA=budget python gateway.py 8420 2> gateway.log > /dev/null &
echo $! > gateway.pid
sleep 1
KEY=$(cat secrets/alpha.key)
BODY='{"failed": 5, "new_device": 1, "km": 100}'
seq 60 | xargs -P 30 -I{} curl -s -o /dev/null -w '%{http_code}\n' -X POST -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d "$BODY" http://127.0.0.1:8420/predict | sort | uniq -c
curl -s -i -X POST -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d "$BODY" http://127.0.0.1:8420/predict | grep -i -E '^HTTP|budget'
kill $(cat gateway.pid) $(cat service.pid) 35 200
25 503
HTTP/1.0 200 OK
X-Budget-Requests-Left: 64Some requests were admitted and some were shed with 503. Your counts differ with the timing. More than 4 passed, because the gateway counts the requests in service when a request arrives and adds its own only when it forwards: a burst can get through the check together. A strict limit needs the check and the count in one locked step. The last request got an answer and a header with the requests that are left in today's budget.
Your turn
A team plans a service with a request time of 40 ms and three workers. A burst of 25 requests arrives, one every 4 ms (the arrival times are [i * 4 for i in range(25)]). Use capacity.capacity with a target load of 60 percent for the steady load. Then use capacity.replay with a queue of 4 places to find the smallest number of workers that sheds none of the burst.
A normal client sends 40 requests of 60 bytes a day. Finance wants the smallest daily units limit in budget.json that still allows that day, so that a stolen key costs no more. Use budget.units_of. Last, use Little's law (requests in service = arrival rate times request time) for 30 requests a second.
Check yourself
Why does the gateway shed at once and not hold the request until the service is free?
A held request uses a connection and memory, and the client waits for an answer that may come too late. A long queue makes every request slow, and then clients retry and add load. A quick 503 with a hint keeps the admitted requests fast.
A client reads Retry-After and all clients retry exactly at that second. What goes wrong?
They all come back together, and the service is hit by a second burst. Clients should add a random delay (jitter) and grow the wait after each failure (exponential back-off).
The daily budget is kept in memory. What are the limits of that?
A restart resets it, and two gateways each hold their own count, so the client gets double. A real gateway keeps budgets in a shared store. For a paid model, also check the bill of the provider: your count is an estimate.
Field notes
- For an LLM, count the tokens that the model reports (input and output) and set a limit on the output length of each request. Long outputs are what cost most. The OWASP Top 10 for LLM Applications (2025 edition) names unbounded consumption (cost, denial of service) as a risk.
- Alert on the budget at 80 percent, and on a client that spends it all in an hour. A stolen key looks like that.
- Set a timeout for the gateway's own call to the service (this one has 5 seconds) and a read timeout for the client socket (
timeout = 10in the handler). Without them, slow requests and slow clients pile up until the gateway is full. - Measure in production: the 95th percentile of the real request time, the share of 503 answers, and the budget use of each client. Capacity changes with the model, the data and the traffic.
- Managed gateways offer rate limits, quotas, autoscaling and queues as settings. This lesson tells you what to ask for.