11B.7 Rate Limits Across Teams, Throughput Options, Kill Switches and Spend Alerts

ProductionLesson 7 of 88,110 words6 parts
Module 11B · 0 of 8 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8

11B.6 answered "how much money may each owner spend?". This lesson answers four operational questions that come right after. How do five teams share one provider rate limit without starving each other? When should traffic go on-demand, to a batch API, or onto reserved (provisioned) capacity? How do you stop everything fast when something goes wrong, and who is allowed to? And how do you get warned about runaway spend in minutes, not at the end of the month? You will build a fair-share limiter, a kill switch with roles and an audit trail, a spend-alert evaluator, and a break-even calculator for throughput options, all in plain Python with a fake clock.

What you'll learn

  • Why a provider's TPM and RPM limits are shared by everyone on your account, and how OpenAI projects and Anthropic workspaces let you carve them up
  • A fair-share design: a guaranteed bucket per team plus a spare pool, priorities, and reserved capacity, so a noisy neighbour cannot take another team's share
  • How to read 429 responses and rate-limit headers from OpenAI and Anthropic, and the three different things a 429 can mean
  • How to choose between on-demand, flex, fast, batch, background and provisioned throughput on OpenAI, Anthropic, Azure, Amazon Bedrock and Google Vertex AI (what exists, as of 1 December 2026), with a break-even formula
  • Kill switch design: feature flag, circuit breaker and spend threshold, scopes, who may trip it, fail-closed behaviour, audit logs and drills
  • Spend alerts: threshold ladders, burn-rate forecasts, anomaly detection on a robust statistic, and how to avoid alert fatigue
  • How to measure your own alert rules against labelled incidents

What you don't need

  • API keys. Everything runs offline with a fake clock and made-up traffic. Provider facts come from official documentation read on 1 December 2026; no real calls are made.
  • Docker, Redis or a feature-flag service. The flag store is an in-memory stand-in; Part 4 explains the real options.
  • Per-owner budgets and chargeback: that was 11B.6. Per-request retry mechanics: 03.8 and 03.9.

Setup

Python 3.11+ and the standard library only. No packages to install.

bash
uv init guard --bare --python 3.13 && cd guard
# nothing to install: every sample uses only the standard library

As of 1 December 2026. Rate-limit tiers, header names, discounts and provisioned-throughput options in this lesson were read from the providers' documentation on that date and are marked. They change often: treat them as dated facts, and read the page before you size anything. The throughput prices in Part 3's calculator are made up to show arithmetic and are labelled as such.

Every code block starts with a comment giving its file name. Save the files in one folder and run them with python3.


What you must be able to do after this lesson#

  • Explain why a provider rate limit is shared by every team on an account, and why a workspace or project limit is a ceiling and not a guaranteed share
  • Build a fair-share limiter with a guaranteed bucket per team, a spare pool and priority classes, and show with a simulation that a noisy neighbour cannot starve the others
  • Classify a 429 as a rate limit, a ramp limit or a spend cap, and feed headers and 429s back into the shared limiter
  • Choose between on-demand, batch and provisioned throughput with a break-even calculation, moving deferrable work to batch first
  • Design a kill switch with scopes, roles, a time to live, an audit log and fail-closed behaviour, and say how you would drill it
  • Write threshold, burn-rate and anomaly spend alerts with a floor and a cooldown, and tune them on labelled incidents

Why this matters for an AI engineer#

The first time two teams share a provider account, one of them finds out about the other from a wall of 429 errors. The first time an agent loops overnight, someone asks "can we just turn it off?" and nobody knows how. These are not model problems; they are operations problems that every production LLM system hits.

You'll hear... You'll understand it after...
"The batch job took down the support bot." 1.2 Why teams collide and 1.4 Try it
"Give each team 20% of our TPM." 1.3 A fair-share design
"429 with no Retry-After? Is that a rate limit?" 2.1 Three kinds of 429
"Should we buy provisioned throughput?" Part 3 and 3.2 The break-even
"Where is the big red button?" Part 4
"Who is allowed to press it?" 4.3 Who can trip it, and fail closed by default
"We found out Monday that the loop ran all weekend." Part 5

Part 1: One limit, many teams#

1.1 What the provider limits, and who shares it#

OpenAI Anthropic
Scope "Limits are set at the organization and project level, not the user level", and they vary by model Set at the organization level; you can set lower limits per workspace
Shared pools Models listed under a "shared limit" on your limits page draw from one pool (for example a shared 3.5M TPM across a group of models) Per model class. Some models share a combined bucket (for example Claude Opus 4.5 to 4.8 share one; Opus 5.5 and Opus 5 have separate ones)
Per-team carve-out Per-project rate and spend limits (project limits cannot exceed organization limits) Per-workspace limits (cannot exceed the organization's); read and set them with the Rate Limits API
Why a generous cap hurts Counts the larger of max_tokens and an estimate from the request's character count, so a big output cap reserves TPM max_tokens does not count for OTPM, only tokens actually generated; cache reads do not count for ITPM

Two lessons from the table.

First, everything is per account, not per team. The provider does not know your teams exist. If your support bot and your nightly summarizer share a project (OpenAI) or workspace (Anthropic), they share one limit, and whichever sends more wins.

Second, the providers' own carve-outs differ in what they protect. Anthropic's rate-limits page gives the example: an organization with 40,000 ITPM might limit one workspace to 30,000 ITPM, and "the other 10,000 input tokens per minute, plus any of the 30,000 that workspace doesn't use, stay available to other workspaces". So a workspace limit is a ceiling on one neighbour, which protects the others. It is not a guaranteed floor for any team. To give a team a guaranteed share you cap everyone else, or you do the guaranteeing yourself in a gateway, which is what the next sections build.

1.2 Why teams collide#

Three mechanisms turn one team's burst into everyone's outage.

  1. Shared bucket, first come first served. With one bucket, the team that sends the most requests gets the most tokens. A batch job that fires 6,000 tokens a second takes almost all of a 60,000-per-minute limit, and a support bot that needs 400 tokens a second gets what is left.
  2. Retry amplification. When requests get 429s, every client retries. A team that is being limited sends more traffic, not less, which makes it worse for everyone (03.8, Part 7 explains jitter; 03.8, 5.5 explains why exactly one layer should own retries).
  3. Reserved output. On OpenAI the limit counts the larger of max_tokens and your prompt estimate. A team that sets max_output_tokens=32000 "just in case" burns TPM for tokens it never generates.

1.3 A fair-share design#

The design below is simple and works for most organizations. Let the provider give your whole account C tokens per minute.

  • Each team i gets a guaranteed share g_i. Its own token bucket refills at g_i per minute.
  • Whatever is left, S = C - sum(g_i), is a spare pool with its own bucket.
  • A request first tries its team's guaranteed bucket. If that is empty, it may borrow from the spare pool. Because the refill rates add up to exactly C, the organization can never send more than the provider allows.
  • Priority classes decide who may borrow. Interactive traffic (a user waiting) may always try the spare pool. Batch traffic (nobody waiting) may borrow only while the pool is more than half full, so it can never drain the headroom interactive traffic depends on.
  • Reserved capacity is the sum of the guarantees. Keep it below C (here 70%) so there is always a spare pool. A pool of zero means no team can burst and idle capacity is wasted.
  • A denied request gets a retry-after computed from the bucket: (tokens needed - tokens available) / refill rate. The caller waits that long (or queues), instead of hammering.
  • Reserve, then settle: reserve the estimated tokens (input estimate plus output cap) before sending, and give back the difference when the real usage arrives. 03.8, 9.5 uses the same idea for one app; this is the multi-team version.

Where does this code live? In a gateway that all teams call, or in a shared library backed by a shared store (Redis). One process holding the buckets only works if one process makes all the calls.

python
# fair_share.py: one provider limit shared by several teams, with guarantees and a spare pool (lesson 11B.7)
"""A provider gives your whole organization C tokens per minute (TPM). This module splits it:
each team has a GUARANTEED bucket (its reserved share) and may borrow from a shared SPARE bucket.
The refill rates add up to C, so the organization can never send more than the provider allows.
Standard library only; time comes from a clock you pass in."""
from __future__ import annotations

from dataclasses import dataclass


class FakeClock:
    def __init__(self) -> None:
        self.now = 0.0

    def __call__(self) -> float:
        return self.now

    def advance(self, seconds: float) -> None:
        self.now += seconds


class TokenBucket:
    """Capacity refills continuously (like the provider's own limiter), up to `capacity`."""
    def __init__(self, rate_per_s: float, capacity: float, clock) -> None:
        self.rate, self.capacity, self.clock = rate_per_s, capacity, clock
        self.level, self._t = capacity, clock()

    def _refill(self) -> None:
        now = self.clock()
        self.level = min(self.capacity, self.level + (now - self._t) * self.rate)
        self._t = now

    def peek(self) -> float:
        self._refill()
        return self.level

    def try_take(self, n: float) -> bool:
        self._refill()
        if n <= self.level:
            self.level -= n
            return True
        return False

    def give_back(self, n: float) -> None:       # settle: hand back what the estimate over-reserved
        self._refill()
        self.level = min(self.capacity, self.level + n)

    def seconds_until(self, n: float) -> float:
        self._refill()
        if n <= self.level:
            return 0.0
        return float("inf") if self.rate == 0 else (n - self.level) / self.rate   # no spare pool: never


@dataclass(frozen=True)
class Admit:
    ok: bool
    source: str = ""            # "guaranteed" | "spare" | ""
    retry_after_s: float = 0.0


class FairShareLimiter:
    def __init__(self, total_tpm: int, guarantees_tpm: dict[str, int], clock,
                 batch_may_borrow_above: float = 0.5, burst_s: float = 10.0) -> None:
        if sum(guarantees_tpm.values()) > total_tpm:
            raise ValueError("guarantees add up to more than the provider limit")
        self.clock = clock
        self.team = {t: TokenBucket(g / 60, g / 60 * burst_s, clock) for t, g in guarantees_tpm.items()}
        spare_tpm = total_tpm - sum(guarantees_tpm.values())
        self.spare = TokenBucket(spare_tpm / 60, spare_tpm / 60 * burst_s, clock)
        self.batch_floor = batch_may_borrow_above           # batch work borrows only if the pool is this full
        self.stats: dict[str, dict[str, float]] = {t: {"guaranteed": 0, "spare": 0, "denied": 0} for t in guarantees_tpm}

    def acquire(self, team: str, tokens: int, priority: str = "interactive") -> Admit:
        """Reserve `tokens` (input estimate + output cap). Guaranteed share first, then the spare pool."""
        if self.team[team].try_take(tokens):
            self.stats[team]["guaranteed"] += tokens
            return Admit(True, "guaranteed")
        spare_ok = priority == "interactive" or self.spare.peek() >= self.batch_floor * self.spare.capacity
        if spare_ok and self.spare.try_take(tokens):
            self.stats[team]["spare"] += tokens
            return Admit(True, "spare")
        wait = min(self.team[team].seconds_until(tokens), self.spare.seconds_until(tokens)
                   if spare_ok else float("inf"))
        self.stats[team]["denied"] += tokens
        return Admit(False, retry_after_s=round(wait, 1))

    def settle(self, team: str, source: str, reserved: int, actual: int) -> None:
        bucket = self.team[team] if source == "guaranteed" else self.spare
        bucket.give_back(max(reserved - actual, 0))


class SharedFifoLimiter:
    """The naive design, for comparison: one bucket for everybody, first come first served."""
    def __init__(self, total_tpm: int, clock, burst_s: float = 10.0) -> None:
        self.bucket = TokenBucket(total_tpm / 60, total_tpm / 60 * burst_s, clock)
        self.stats: dict[str, dict[str, float]] = {}

    def acquire(self, team: str, tokens: int, priority: str = "interactive") -> Admit:
        s = self.stats.setdefault(team, {"guaranteed": 0, "spare": 0, "denied": 0})
        if self.bucket.try_take(tokens):
            s["spare"] += tokens
            return Admit(True, "spare")
        s["denied"] += tokens
        return Admit(False, retry_after_s=round(self.bucket.seconds_until(tokens), 1))

    def settle(self, *args) -> None:
        pass

1.4 Try it: a noisy neighbour, with and without guarantees#

The simulation gives the organization 60,000 tokens per minute. Support (interactive) and search (interactive) send steady traffic; batch-etl floods with 60 times more than its guarantee. Arrival order within each second is shuffled with a fixed seed, so neither design is favoured by the order of the loop. Save as demo_fair.py:

python
# demo_fair.py: a noisy neighbour, with and without guarantees (lesson 11B.7). Run: python3 demo_fair.py
import random

from fair_share import FairShareLimiter, FakeClock, SharedFifoLimiter

TOTAL_TPM = 60_000                                    # what the provider gives the whole organization
GUARANTEES = {"support": 24_000, "search": 12_000, "batch-etl": 6_000}   # 42k reserved, 18k spare


def simulate(make_limiter, label: str) -> None:
    clock = FakeClock()
    lim = make_limiter(clock)
    # Each second: "etl" tries 6,000 tokens of batch work (a flood), support tries 400 tokens
    # (steady, interactive), search tries 200 tokens. Every request is 200 tokens.
    rng = random.Random(7)                            # arrival order within a second is random, not rigged
    for second in range(120):
        arrivals = ([("batch-etl", "batch")] * 30 + [("support", "interactive")] * 2
                    + [("search", "interactive")])
        rng.shuffle(arrivals)
        for team, priority in arrivals:
            lim.acquire(team, 200, priority=priority)
        clock.advance(1)
    print(f"--- {label}")
    print(f"{'team':<10} {'asked':>9} {'served':>9} {'served %':>9}   of which spare")
    for team in ("support", "search", "batch-etl"):
        s = lim.stats.get(team, {"guaranteed": 0, "spare": 0, "denied": 0})
        served = s["guaranteed"] + s["spare"]
        asked = served + s["denied"]
        print(f"{team:<10} {asked:>9,.0f} {served:>9,.0f} {100 * served / asked:>8.0f}%   {s['spare']:>9,.0f}")


simulate(lambda c: SharedFifoLimiter(TOTAL_TPM, c), "one shared bucket, first come first served")
simulate(lambda c: FairShareLimiter(TOTAL_TPM, GUARANTEES, c), "guaranteed shares plus a spare pool")
Output10 lines
--- one shared bucket, first come first served
team           asked    served  served %   of which spare
support       48,000     8,200       17%       8,200
search        24,000     3,400       14%       3,400
batch-etl    720,000   117,400       16%     117,400
--- guaranteed shares plus a spare pool
team           asked    served  served %   of which spare
support       48,000    48,000      100%           0
search        24,000    24,000      100%           0
batch-etl    720,000    50,200        7%      37,400

Reading it. With one shared bucket, every team is served in proportion to how much it sends, so the flood wins: batch-etl gets 117,400 tokens, and support, which asked for far less, gets only 17% of what it needs. With guarantees plus a spare pool, support and search are served 100%, because their traffic fits inside their guaranteed buckets, and batch-etl is held to its 6,000-per-minute guarantee plus what the spare pool lets a batch job borrow (37,400 tokens here). Total throughput is lower for the flooding team and perfectly fine for the others. That is the whole point.

1.5 When a request is denied#

A limiter returns "not now". What the caller does next is a design decision.

Strategy Use when Notes
Wait (sleep retry_after) Short waits, background work Never a tight loop; add jitter
Queue by priority Interactive work that can tolerate seconds A priority queue ordered by (priority, deadline); drop entries past their deadline
Degrade The user is waiting Shorter output cap, a smaller model, or a cached answer (11B.6, 4.3)
Shed The system is overloaded Refuse the lowest priority first, with a clear message; better than timing everyone out
Defer to batch Nobody is waiting Move it to a batch API (Part 3); it has its own limits

Part 2: 429s, headers and the feedback loop#

Deep-dive

2.1 Three kinds of 429#

A 429 can mean three different things, and treating them all as "slow down" is a classic bug. 03.8, 4.2 teaches the split in full, 03.8, 4.4 builds a classifier, and 03.8, 9.4 covers ramp limits. In short:

  • A rate limit (RPM, TPM, ITPM, OTPM): wait at least Retry-After, add jitter, retry, and slow the shared limiter.
  • A ramp limit (Anthropic ramp_limit_exceeded, OpenAI slow_down): hold traffic at the level that works and grow it in small steps. This is a multi-team problem because a batch job that starts at full speed trips it for everyone.
  • A spend or quota cap (Anthropic enforced_spend_limit_reached with no retry-after, or OpenAI billing codes): do not retry. Alert a human and trip the kill switch (Part 4) for the affected scope.

A limit you set yourself on Anthropic returns 400 (invalid_request_error), not 429, so your classifier must tell the two apart.

2.2 Rate-limit headers#

Both providers return headers that say how much of each limit is left, and a gateway should read them on every response. 03.8, 9.3 lists the header names, the reset formats (an OpenAI duration against an Anthropic RFC 3339 timestamp) and a parser with tests. Two points matter for a shared limiter (as of 1 December 2026):

  • Per project and per workspace. OpenAI adds x-ratelimit-*-project-tokens headers only when a project-scoped limit applies. Anthropic's anthropic-ratelimit-tokens-* headers show the most restrictive limit in effect, which can be your workspace limit, and anthropic-workspace-id names the workspace the request counted against.
  • Do not use them for exact accounting. Anthropic rounds the token remaining values "to the nearest thousand". Use them as a signal, as 2.3 does.

2.3 Closing the loop#

A shared limiter that only knows its configured numbers will drift from the provider's reality (another service on the account, a lowered tier, a model in overload). Close the loop with three inputs:

  1. Headers. When remaining-tokens drops below, say, 10% of limit-tokens, slow the spare pool (for example halve its refill rate) until it recovers.
  2. 429s. On a rate-limit 429, pause the global bucket for Retry-After, then resume at a reduced rate and increase slowly (additive increase, multiplicative decrease, the way TCP does). Do not retry on a spend-cap 429; trip the kill switch (Part 4) for the affected scope and alert.
  3. Provider caps you read at startup. Anthropic's Rate Limits API returns your organization's and workspaces' configured limits, so your guarantees can be validated against the real total instead of a number someone typed into a config file.

Part 3: On-demand, batch or provisioned#

Deep-dive

3.1 What exists#

Throughput options differ along three axes: price, latency promise and capacity promise. The options below existed in the providers' documentation on 1 December 2026. Names and terms change, so check the pages.

Option What you get Price signal Provider facts (1 December 2026)
On-demand (standard) Best-effort capacity shared with other customers; default List price The default on every provider
Flex Cheaper synchronous calls that may queue or fail when capacity is tight About the batch price OpenAI Flex: priced near batch; OpenAI's pricing page says "Flex remains available on the models listed here as we wind down the beta" and no new models get it. Gemini also lists a flex tier (see 03.9, 12.1). Anthropic has none
Fast (formerly priority) Faster output and more consistent latency, no commitment Roughly 2x standard OpenAI: service_tier="fast" ("priority" is the same; renamed Fast mode on 30 July 2026); up to 2.5x faster; standard and Fast share one rate limit; ramp rule applies. Anthropic: speed="fast" on selected models, with its own rate limit; for Claude Opus 5.5, $8 input and $40 output per million tokens against $4 and $20 standard
Background Asynchronous requests with a completion window 30% off for a 2-hour window, 40% off for an 8-hour window on listed OpenAI models OpenAI pricing page; shares a queued-token pool with Batch
Batch Asynchronous jobs, results within a window, own rate limits 50% off input and output OpenAI Batch API: 24-hour window, up to 50,000 requests and 200 MB per file. Anthropic Message Batches: up to 100,000 requests or 256 MB per batch, "most batches completing within 1 hour", expire after 24 hours, results kept 29 days. Anthropic's Fast mode cannot be used with batch
Provisioned (reserved capacity) A fixed amount of capacity held for you, whether or not you use it A fixed price per unit per hour or per term See below
Anthropic Priority Tier Prioritised capacity under a commitment Commitment fee Legacy. Anthropic's page says "Priority Tier capacity commitments are no longer available for purchase"; existing commitments run to their end date. If you need guaranteed capacity, contact sales
OpenAI Scale Tier Purchased capacity bundles (TPM) Contract OpenAI's Fast mode page says Scale Tier still exists and is separate from Fast mode. Its terms and prices were not verified for this lesson (unverified as of 1 December 2026)

Provisioned throughput on the clouds, as documented on 1 December 2026:

Platform Unit Terms Notes
Azure (Foundry) PTU (provisioned throughput unit); TPM per PTU varies by model Hourly billing, or Azure Reservations for 1 month or 1 year Three deployment types: Global, Data Zone, Regional Provisioned. "A provisioned deployment holds a fixed amount of processing capacity exclusively for your deployment's use, whether or not requests are being made." Quota does not guarantee capacity: a deployment can fail if the region is full. Spillover can route overflow to a standard deployment (header x-ms-spillover-deployment). Azure also lists priority processing: pay per token at a priority rate with a defined latency target
Amazon Bedrock Model unit (MU); input and output tokens per minute per MU Hourly billing; no commitment, 1 month or 6 months "If you customized a model, you must purchase Provisioned Throughput to be able to use it." Billing continues until you delete it; longer commitments are discounted
Google Vertex AI Throughput measured per model "Fixed-cost, fixed-term subscription available in several term-lengths" The overview page names no units or term lengths; read the supported-models page. Whether and how Claude models on Vertex AI can be provisioned was not verified (unverified as of 1 December 2026)

3.2 The break-even in code#

The decision comes down to utilization. One provisioned unit costs P dollars an hour and can process T tokens an hour. On-demand costs c dollars per million tokens. The unit beats on-demand only if it is busy at least this fraction of the time:

text
break-even utilization = P / (T / 1,000,000 x c)

Below that utilization you are paying for idle capacity. The calculator below uses made-up numbers to show the shape of the decision; replace them with your quote. It also shows the two effects that beginners miss: overflow (traffic above the unit's capacity still needs somewhere to go) and that moving deferrable work to batch first can make provisioned capacity unnecessary. Save as throughput_choice.py:

python
# throughput_choice.py: on-demand, batch or provisioned? A break-even calculator (lesson 11B.7)
"""All prices below are MADE-UP round numbers, only to show the arithmetic. Provisioned prices depend on the
provider, model, region and commitment: read your provider's page and your quote. Batch is 50% off on both
OpenAI and Anthropic (verified 2026-12-01). Standard library only."""
from dataclasses import dataclass


@dataclass(frozen=True)
class Plan:
    blended_usd_per_m: float = 3.00        # on-demand price per million tokens, input and output blended (made up)
    unit_tokens_per_hour: float = 600_000  # capacity of one provisioned unit (made up)
    unit_usd_per_hour: float = 1.00        # price of one provisioned unit per hour, used or not (made up)
    batch_discount: float = 0.50           # verified for OpenAI Batch and Anthropic Message Batches


def day_profile() -> list[float]:
    """Tokens per hour: quiet nights, a business-hours plateau, an evening shoulder."""
    return [150_000] * 8 + [900_000] * 9 + [400_000] * 4 + [150_000] * 3


def on_demand_cost(tokens: list[float], p: Plan) -> float:
    return sum(tokens) / 1e6 * p.blended_usd_per_m


def provisioned_cost(tokens: list[float], units: int, p: Plan) -> tuple[float, float, float]:
    """Pay for `units` every hour; overflow above their capacity spills to on-demand.
    Returns (total cost, utilization of the units, share of tokens that overflowed)."""
    cap = units * p.unit_tokens_per_hour
    overflow = sum(max(t - cap, 0) for t in tokens)
    served = sum(min(t, cap) for t in tokens)
    fixed = units * p.unit_usd_per_hour * len(tokens)
    util = served / (cap * len(tokens)) if cap else 0.0
    return fixed + overflow / 1e6 * p.blended_usd_per_m, util, overflow / sum(tokens)


def break_even_utilization(p: Plan) -> float:
    """A unit beats on-demand only if it is busy at least this fraction of the time."""
    return p.unit_usd_per_hour / (p.unit_tokens_per_hour / 1e6 * p.blended_usd_per_m)


if __name__ == "__main__":
    p, tokens = Plan(), day_profile()
    base = on_demand_cost(tokens, p)
    print(f"tokens per day: {sum(tokens):,.0f}; peak hour {max(tokens):,.0f}; average hour {sum(tokens) / 24:,.0f}")
    print(f"break-even utilization for one unit: {break_even_utilization(p):.0%}")
    print(f"\n{'option':<34} {'$ per day':>10} {'vs on-demand':>13} {'unit utilization':>17} {'overflow':>9}")
    print(f"{'on-demand only':<34} {base:>10.2f} {'100%':>13}")
    for units in (1, 2, 3):
        cost, util, over = provisioned_cost(tokens, units, p)
        print(f"{f'{units} provisioned unit(s) + spillover':<34} {cost:>10.2f} {cost / base:>12.0%} {util:>17.0%} {over:>8.0%}")
    deferrable = 0.30                         # share of tokens that can wait up to 24 hours (reports, evals, backfills)
    batched = base * (1 - deferrable) + base * deferrable * (1 - p.batch_discount)
    print(f"{'on-demand + 30% moved to batch':<34} {batched:>10.2f} {batched / base:>12.0%}")
    # Best mix: move the deferrable tokens to batch FIRST, then size the provisioned baseline on what is left.
    rest = [t * (1 - deferrable) for t in tokens]
    best = min(range(0, 4), key=lambda n: provisioned_cost(rest, n, p)[0] if n else on_demand_cost(rest, p))
    cost, util, over = provisioned_cost(rest, best, p) if best else (on_demand_cost(rest, p), 0, 1)
    mix = cost + base * deferrable * (1 - p.batch_discount)
    tail = f"{util:>17.0%} {over:>8.0%}" if best else f"{'-':>17} {'-':>9}"
    print(f"{f'batch 30% + {best} provisioned unit(s)':<34} {mix:>10.2f} {mix / base:>12.0%} {tail}")
Output10 lines
tokens per day: 11,350,000; peak hour 900,000; average hour 472,917
break-even utilization for one unit: 56%

option                              $ per day  vs on-demand  unit utilization  overflow
on-demand only                          34.05          100%
1 provisioned unit(s) + spillover       32.10          94%               60%      24%
2 provisioned unit(s) + spillover       48.00         141%               39%       0%
3 provisioned unit(s) + spillover       72.00         211%               26%       0%
on-demand + 30% moved to batch          28.94          85%
batch 30% + 0 provisioned unit(s)       28.94          85%                 -         -

Reading it. The break-even is 56% utilization. One unit runs at 60% utilization and handles 76% of the tokens, with 24% spilling over to on-demand, so it is a 6% saving. Two units cost 41% more than on-demand, because the second unit sits idle (39% utilization) outside business hours. Moving 30% of the tokens to batch saves 15% with no commitment at all, and once that is done the best number of provisioned units is zero. The lesson for planning: order the decisions. First move everything that can wait to batch. Then size provisioned capacity only for the steady baseline of what is left. Then let on-demand absorb the peaks.

3.3 A decision table#

Your situation Start with Why
Nobody is waiting; results can arrive within hours Batch (or background) 50% off, own rate limits, no impact on interactive traffic
A user is waiting; traffic is spiky or small On-demand, with the fair-share limiter from Part 1 No idle cost
A user is waiting; latency matters more than price Fast mode (OpenAI Fast, Anthropic fast mode on supported models) Pay per token for speed, no commitment
A user is waiting; traffic is large, steady and predictable; you need a capacity promise or steady latency Provisioned (Azure PTU, Bedrock Provisioned Throughput, Vertex Provisioned Throughput), sized for the baseline, with spillover to on-demand Utilization must beat the break-even
You hit ramp limits when a job starts Spread the start; or use batch (Anthropic's Message Batches are not subject to ramp limits) Ramp limits punish step changes
You need data residency Check the regional or data-zone option first Residency can add a premium (about 10% on OpenAI regional endpoints for models released on or after 5 March 2026, and 1.1x for Anthropic's inference_geo: "us", both checked 1 December 2026)

3.4 Batch also protects your rate limit#

A practical benefit that is easy to miss: batch jobs use separate limits. OpenAI says "Batch API jobs don't count toward standard per-model request or token rate limits" (they count against a queued-token limit per model, shared with background requests). Anthropic's Message Batches have their own RPM and "batch requests in the processing queue" limits per tier (200,000 on Start, 300,000 on Build, 500,000 on Scale) and are not subject to ramp limits. So moving nightly or eval work to batch frees the on-demand limit for users, and you can run it without the fair-share limiter's spare pool. 03.9, Parts 6 to 11 teaches the lifecycle, and 11B.1, 4.5 gives the cost rule for deciding which workloads can wait.

3.5 Allocating committed capacity#

A provisioned commitment is a shared cost. Charge it by each team's share of the commitment (the capacity they asked for), and charge the overflow (on-demand spillover) by tokens, so the team that sized the commitment does not leave others paying for its idle hours (11B.6, 6.3). Azure documents a way to "distribute reservation costs across teams or projects for internal cost attribution".


Part 4: Kill switches#

4.1 What a kill switch is#

A kill switch is a control that stops model traffic quickly, at a scope you choose, without a code deploy. There are three kinds, and a mature system has all three.

Kind Trigger Who or what trips it Example
Manual flag A person decides A named role, with a reason "The ranker is looping after deploy 4812: stop it"
Spend threshold Spend in a sliding window crosses a limit Automation "More than $5 in 10 minutes on feature:ranker"
Circuit breaker Repeated provider failures Automation Three failures in a row: stop sending for 30 seconds, then probe

The first two stop your spending. The circuit breaker stops you hammering a failing provider and lets you fall back (11C.3). Which degraded mode users will tolerate when a switch trips is a product decision: see 13A.6, 6.6.

4.2 Scopes#

A switch that can only turn off everything is too scary to use, so it never gets pressed. Make it granular:

  • * (everything), the nuclear option;
  • provider:openai (a provider is misbehaving or you hit its cap);
  • team:search, feature:ranker (one runaway owner);
  • tenant:acme (one abusive or compromised customer);
  • tool:send_email (an agent tool, not a model call; see 08A.5 for the security view and 08A.12 for approval gates).

A call checks a list of scopes, widest first, and is stopped if any is tripped. That is the check(*scopes) call below.

4.3 Who can trip it, and fail closed by default#

Four design decisions, in order of how often they go wrong.

  1. Who may trip, who may reset. Tripping must be easy for the people on call (anyone paged should be able to stop a loop at 3 a.m.) and impossible for everyone else. Give each role a list of scopes it may change; a team lead may trip their own team and features, on-call may trip anything. Automation (the spend breaker) has its own role. Resetting should be at least as restricted as tripping, and it should require a reason.
  2. Audit every action, including refusals: who, role, scope, action, reason, time. You will need this in the post-incident review and for compliance (14A.6).
  3. Fail closed. If the flag store cannot be reached, what happens? Closed means the calls are refused: safe for expensive or risky features, but an outage of your flag store becomes an outage of your product. Open means calls continue unchecked: available, but unprotected. The rule: closed by default, and open only for scopes you explicitly list (a cheap, low-risk feature), with an alert either way. Cache the last good value locally for a few seconds so a brief store blip does not stop everything.
  4. Give a trip a time to live. A trip with a TTL expires by itself, so a forgotten switch does not leave a feature off for a week. Use no TTL for incidents that need a human decision.

4.4 The code#

python
# kill_switch.py: a kill switch with scopes, roles, an audit trail and fail-closed reads (lesson 11B.7)
"""Three stop mechanisms, one decision point:
  1. a manual KillSwitch that named roles can trip (scopes: "*", "team:search", "feature:triage-bot");
  2. a SpendBreaker that trips a scope by itself when spend runs too fast;
  3. a CircuitBreaker that opens after repeated provider failures and probes again later.
Standard library only."""
from __future__ import annotations


class StoreDown(Exception):
    """The flag store (Redis, a feature-flag service, a database) cannot be reached."""


class FlagStore:
    """In-memory stand-in for the shared store. `down=True` simulates an outage."""
    def __init__(self) -> None:
        self._flags: dict[str, dict] = {}
        self.down = False

    def get(self, scope: str) -> dict | None:
        if self.down:
            raise StoreDown(scope)
        return self._flags.get(scope)

    def put(self, scope: str, value: dict | None) -> None:
        if value is None:
            self._flags.pop(scope, None)
        else:
            self._flags[scope] = value


class KillSwitch:
    def __init__(self, store: FlagStore, clock, trip_roles: dict[str, set[str]],
                 fail_open_scopes: frozenset[str] = frozenset()) -> None:
        self.store, self.clock, self.trip_roles = store, clock, trip_roles
        self.fail_open_scopes = fail_open_scopes     # scopes allowed to keep running if the store is down
        self.audit: list[dict] = []

    def _authorise(self, scope: str, who: str, role: str) -> None:
        allowed = self.trip_roles.get(role, set())
        if "*" not in allowed and scope not in allowed:
            self.audit.append({"t": self.clock(), "who": who, "role": role, "scope": scope, "action": "REFUSED"})
            raise PermissionError(f"role {role!r} may not change {scope!r}")

    def trip(self, scope: str, who: str, role: str, reason: str, ttl_s: float | None = None) -> None:
        self._authorise(scope, who, role)
        expires = None if ttl_s is None else self.clock() + ttl_s
        self.store.put(scope, {"tripped": True, "by": who, "reason": reason, "expires": expires})
        self.audit.append({"t": self.clock(), "who": who, "role": role, "scope": scope, "action": "TRIP", "reason": reason})

    def reset(self, scope: str, who: str, role: str, reason: str) -> None:
        self._authorise(scope, who, role)
        self.store.put(scope, None)
        self.audit.append({"t": self.clock(), "who": who, "role": role, "scope": scope, "action": "RESET", "reason": reason})

    def check(self, *scopes: str) -> tuple[bool, str]:
        """Call before every model call, with the scopes this call belongs to, widest first.
        Reading failures are FAIL-CLOSED unless the scope is explicitly listed as fail-open."""
        for scope in scopes:
            try:
                flag = self.store.get(scope)
            except StoreDown:
                if scope in self.fail_open_scopes:
                    continue
                return False, f"store unreachable, failing closed for {scope}"
            if flag and flag["tripped"]:
                if flag["expires"] is not None and self.clock() >= flag["expires"]:
                    self.store.put(scope, None)       # a trip with a TTL expires by itself
                    continue
                return False, f"{scope} stopped by {flag['by']}: {flag['reason']}"
        return True, "ok"


class SpendBreaker:
    """Trips a scope when spend inside a sliding window crosses a limit."""
    def __init__(self, switch: KillSwitch, scope: str, limit_usd: float, window_s: float, clock) -> None:
        self.switch, self.scope, self.limit, self.window, self.clock = switch, scope, limit_usd, window_s, clock
        self.events: list[tuple[float, float]] = []

    def record(self, cost_usd: float) -> None:
        now = self.clock()
        self.events.append((now, cost_usd))
        self.events = [(t, c) for t, c in self.events if now - t < self.window]
        spent = sum(c for _, c in self.events)
        if spent > self.limit:
            self.switch.trip(self.scope, "spend-breaker", "automation",
                             f"${spent:.2f} in the last {self.window / 60:.0f} min (limit ${self.limit:.2f})")


class CircuitBreaker:
    """closed -> open after `threshold` consecutive failures; open -> half-open after `cooldown_s`;
    half-open lets ONE probe through: success closes it, failure re-opens it."""
    def __init__(self, threshold: int, cooldown_s: float, clock) -> None:
        self.threshold, self.cooldown, self.clock = threshold, cooldown_s, clock
        self.state, self.failures, self.opened_at, self._probe_out = "closed", 0, 0.0, False

    def allow(self) -> bool:
        if self.state == "open" and self.clock() - self.opened_at >= self.cooldown:
            self.state, self._probe_out = "half-open", False
        if self.state == "closed":
            return True
        if self.state == "half-open" and not self._probe_out:
            self._probe_out = True
            return True
        return False

    def record(self, ok: bool) -> None:
        if ok:
            self.state, self.failures = "closed", 0
            return
        self.failures += 1
        if self.state == "half-open" or self.failures >= self.threshold:
            self.state, self.opened_at = "open", self.clock()

Save a driver as demo_guard.py (the same file also runs the alert demo in Part 5):

python
# demo_guard.py: kill switch, breakers and alerts working together (lesson 11B.7). Run: python3 demo_guard.py
import random

from alerts import AlertEvaluator
from fair_share import FakeClock
from kill_switch import CircuitBreaker, FlagStore, KillSwitch, SpendBreaker

clock = FakeClock()
store = FlagStore()
roles = {"oncall": {"*"}, "search-lead": {"team:search", "feature:ranker"}, "automation": {"*"}}
switch = KillSwitch(store, clock, roles, fail_open_scopes=frozenset({"feature:autocomplete"}))

print("== 1. Manual trip, roles, audit")
print(switch.check("*", "team:search", "feature:ranker"))
switch.trip("feature:ranker", "asha", "search-lead", "ranker loop after deploy 4812", ttl_s=3600)
print(switch.check("*", "team:search", "feature:ranker"))
print(switch.check("*", "team:support", "feature:triage-bot"), "<- other teams keep running")
try:
    switch.trip("*", "ben", "search-lead", "turn everything off")
except PermissionError as e:
    print("refused:", e)
clock.advance(3601)
print(switch.check("feature:ranker"), "<- the one-hour TTL expired")

print("\n== 2. Fail closed when the store is down")
store.down = True
print(switch.check("*", "feature:triage-bot"))
print(switch.check("feature:autocomplete"), "<- explicitly fail-open (a free, low-risk feature)")
store.down = False

print("\n== 3. A spend breaker trips a scope by itself")
breaker = SpendBreaker(switch, "feature:ranker", limit_usd=5.0, window_s=600, clock=clock)
for minute in range(8):
    clock.advance(60)
    breaker.record(1.25)                                   # a loop spending $1.25 a minute
    ok, why = switch.check("feature:ranker")
    print(f"minute {minute + 1}: allowed={ok} {'' if ok else why}")
    if not ok:
        break
print("audit:", [(a['who'], a['action']) for a in switch.audit])

print("\n== 4. Circuit breaker around a failing provider")
cb = CircuitBreaker(threshold=3, cooldown_s=30, clock=clock)

def attempt(label: str, provider_ok: bool) -> None:
    allowed = cb.allow()
    if allowed:
        cb.record(provider_ok)
    print(f"{label:<30} allowed={allowed!s:<5} state={cb.state}")

for n in range(3):
    attempt(f"call {n + 1} (provider fails)", False)
attempt("call 4 right after", True)
clock.advance(31)
attempt("call 5 after cooldown (probe)", False)       # the single probe fails: open again
attempt("call 6 right after", True)
clock.advance(31)
attempt("call 7 after cooldown (probe)", True)        # the probe succeeds: closed again
attempt("call 8", True)

print("\n== 5. Alerts over 48 hours, a loop starts at hour 30")
rng = random.Random(3)
ev = AlertEvaluator(budget_usd=400, period_hours=72)
for hour in range(48):
    base = 3.0 + 1.5 * (9 <= hour % 24 <= 17) + rng.uniform(-0.3, 0.3)
    spend = base if hour < 30 else 20.0 + rng.uniform(-1, 1)       # loop from hour 30
    ev.observe(hour, spend)
for a in ev.alerts:
    print(f"h{a.hour:>2} {a.severity:<6} {a.kind:<10} {a.message}")
Output28 lines
== 1. Manual trip, roles, audit
(True, 'ok')
(False, 'feature:ranker stopped by asha: ranker loop after deploy 4812')
(True, 'ok') <- other teams keep running
refused: role 'search-lead' may not change '*'
(True, 'ok') <- the one-hour TTL expired

== 2. Fail closed when the store is down
(False, 'store unreachable, failing closed for *')
(True, 'ok') <- explicitly fail-open (a free, low-risk feature)

== 3. A spend breaker trips a scope by itself
minute 1: allowed=True 
minute 2: allowed=True 
minute 3: allowed=True 
minute 4: allowed=True 
minute 5: allowed=False feature:ranker stopped by spend-breaker: $6.25 in the last 10 min (limit $5.00)
audit: [('asha', 'TRIP'), ('ben', 'REFUSED'), ('spend-breaker', 'TRIP')]

== 4. Circuit breaker around a failing provider
call 1 (provider fails)        allowed=True  state=closed
call 2 (provider fails)        allowed=True  state=closed
call 3 (provider fails)        allowed=True  state=open
call 4 right after             allowed=False state=open
call 5 after cooldown (probe)  allowed=True  state=open
call 6 right after             allowed=False state=open
call 7 after cooldown (probe)  allowed=True  state=closed
call 8                         allowed=True  state=closed

Reading sections 1 to 4 of the output:

  1. Manual trip. feature:ranker is stopped by asha (a search-lead); team:support keeps running; ben, also a search-lead, is refused when he tries to trip *, and the refusal is in the audit log. After an hour, the TTL expires and the check passes again.
  2. Fail closed. When the store is down, * and feature:triage-bot are refused (closed). feature:autocomplete was listed as fail-open, so it keeps working.
  3. Spend breaker. A loop spends $1.25 a minute. At minute 5 the 10-minute window holds $6.25, over the $5 limit, so the breaker trips feature:ranker by itself. The audit log shows the automation as the actor.
  4. Circuit breaker. After three failures it opens. After the cooldown, one probe is let through; here it fails, so it opens again. After a second cooldown the probe succeeds and it closes. The "one probe only" rule matters: if a hundred requests all probe at once, you are back to hammering.

4.5 Where to check, and what happens next#

  • Check before every model call and before every tool that has side effects. An agent that is mid-run when you trip its scope should stop at the next step, not finish a 40-step plan. Put the check at the same seam as the budget check (08A.3 shows the loop's pre-call hook).
  • Decide what happens to calls in flight. Usually: let them finish (cancelling wastes the tokens already spent), but start no new ones. For long-running background agents (08A.13), pause them at a safe checkpoint.
  • Give users a message. "This feature is temporarily unavailable" with a request ID is enough. Log the scope that blocked the call.
  • Drill it. A kill switch that has never been pressed in production hours is a hypothesis. Press it in staging every quarter and record the time from "decided" to "no new calls".
  • Keep the read path fast and local. The flag lookup is on the critical path of every call. Cache for a few seconds, and never make it a remote call that can add seconds of latency.

Part 5: Spend alerts#

5.1 What to alert on#

03.7, 12.5 has a catalogue of cost signals (spend per feature versus its average, p95 cost per request, cache hit ratio, truncation share, unknown-cost share), and 11A.2 covers metrics and alerting in general. This part adds three rule shapes for spend and shows how to keep them quiet.

Rule shape Question Good at Weak at
Threshold ladder Has cumulative spend crossed 50%, 80%, 100% of the period budget? Slow overspend; matches how finance thinks A fast loop: by the time you hit 50%, the damage is done
Burn rate At the current pace, does the budget run out before the period ends? Catching overspend days early Sudden spikes (pace is an average)
Anomaly Is this hour far above normal? Loops and retry storms, within an hour A slow, steady rise that never looks abnormal

You need all three because they fail differently. The ladder is the safety net, burn rate is the early warning, and anomaly is the fast detector.

5.2 The code#

The anomaly rule uses a robust z-score: how many "typical deviations" this hour is above the median, where "typical deviation" is the median absolute deviation (MAD) scaled to match a standard deviation. The median and MAD are not distorted by an earlier spike the way a mean and standard deviation are, which matters because a runaway loop is exactly an outlier you do not want to teach the detector to ignore.

python
# alerts.py: spend alerts that catch loops early without paging on noise (lesson 11B.7)
"""Three alert kinds over an hourly spend series (USD per hour):
  threshold  - cumulative spend crosses 50 / 80 / 100 percent of the period budget;
  burn rate  - at the current pace the budget runs out before the period ends;
  anomaly    - this hour is far above the trailing normal (robust z-score on median and MAD).
Threshold alerts fire once per period; the others fire at most once per cooldown, so a loop does not send 400 pages. Standard library only."""
from __future__ import annotations

from dataclasses import dataclass
from statistics import median


@dataclass(frozen=True)
class Alert:
    hour: int
    kind: str
    severity: str          # info | ticket | page
    message: str


def robust_z(history: list[float], value: float) -> float:
    """How many 'typical deviations' above the median is `value`? MAD resists the outliers a loop creates."""
    m = median(history)
    mad = median(abs(x - m) for x in history) or 1e-9
    return (value - m) / (1.4826 * mad)


class AlertEvaluator:
    def __init__(self, budget_usd: float, period_hours: int, cooldown_hours: int = 6,
                 min_history: int = 12, z_page: float = 6.0, floor_usd: float = 1.0) -> None:
        self.budget, self.period = budget_usd, period_hours
        self.cooldown, self.min_history, self.z_page, self.floor = cooldown_hours, min_history, z_page, floor_usd
        self.series: list[float] = []
        self.last_fired: dict[str, int] = {}
        self.alerts: list[Alert] = []

    def _fire(self, hour: int, name: str, kind: str, severity: str, message: str, once: bool = False) -> None:
        last = self.last_fired.get(name)
        if last is not None and (once or hour - last < self.cooldown):
            return
        self.last_fired[name] = hour
        self.alerts.append(Alert(hour, kind, severity, message))

    def observe(self, hour: int, spend_usd: float) -> None:
        history = self.series[-48:]                       # trailing two days of normal
        self.series.append(spend_usd)
        total = sum(self.series)
        for pct, sev in ((0.5, "info"), (0.8, "ticket"), (1.0, "page")):
            if total >= pct * self.budget:
                self._fire(hour, f"budget-{int(pct * 100)}", "threshold", sev,
                           f"{int(pct * 100)}% of ${self.budget:,.0f} budget used (${total:,.2f})", once=True)
        recent = self.series[-3:]
        pace = sum(recent) / len(recent)                  # average of the last three hours
        projected = total + pace * (self.period - hour - 1)
        if projected > self.budget and total < self.budget:
            hours_left = (self.budget - total) / pace if pace else float("inf")
            self._fire(hour, "burn-rate", "burn rate", "ticket",
                       f"at ${pace:,.2f}/h the budget is gone in {hours_left:,.0f} h; period has {self.period - hour - 1} h left")
        if len(history) >= self.min_history and spend_usd >= self.floor:
            z = robust_z(history, spend_usd)
            if z >= self.z_page:
                self._fire(hour, "anomaly", "anomaly", "page",
                           f"${spend_usd:,.2f} this hour vs median ${median(history):,.2f} (robust z = {z:,.0f})")

Section 5 of the demo_guard.py output above replays 48 hours of spend with a loop that starts at hour 30:

text
== 5. Alerts over 48 hours, a loop starts at hour 30
h30 ticket burn rate  at $9.07/h the budget is gone in 30 h; period has 41 h left
h30 page   anomaly    $20.84 this hour vs median $3.12 (robust z = 48)
h34 info   threshold  50% of $400 budget used ($204.73)
h36 ticket burn rate  at $19.64/h the budget is gone in 8 h; period has 35 h left
h36 page   anomaly    $19.60 this hour vs median $3.18 (robust z = 25)
h40 ticket threshold  80% of $400 budget used ($325.81)
h42 ticket burn rate  at $20.39/h the budget is gone in 2 h; period has 29 h left
h42 page   anomaly    $19.33 this hour vs median $3.76 (robust z = 12)
h44 page   threshold  100% of $400 budget used ($407.19)

Reading it. At hour 30, the first hour of the loop, the evaluator already raises an anomaly page (robust z = 48: the hour cost $20.84 against a median of $3.12) and a burn-rate ticket. The threshold ladder follows later (50% at hour 34, 80% at hour 40, 100% at hour 44). The ladder alone would have told you four hours later, and 100% would have arrived with the money already spent. The anomaly page repeats at hours 36 and 42 because of the six-hour cooldown: it keeps nagging while the loop continues, but it does not send a page every hour.

5.3 Keeping alerts useful#

  • A floor. Do not page on an anomaly smaller than a minimum amount (floor_usd). A tripling from $0.02 to $0.06 an hour is a statistical anomaly and a financial non-event.
  • A minimum history. The detector needs enough normal hours (here 12) before it judges. A brand-new feature gets only the threshold ladder.
  • A cooldown per alert name, and thresholds that fire once per period. Repeating the same page every hour teaches people to ignore it.
  • Severity maps to an action. Info goes to a channel, a ticket goes to the owning team's queue, a page wakes someone, and an auto-trip (the spend breaker from Part 4) is for cases where waiting for a human costs more than a false positive. Decide which alerts may trip a switch by themselves, and document it.
  • Route by owner. Tags from 11B.6, Part 5 tell you which team to page. An alert that goes to a shared channel nobody owns is not an alert.
  • Put a runbook link in the alert, with the scope name to trip.
  • Alert on your own data first. Provider dashboards and reports lag: Anthropic's analytics typically refresh within 4 hours and can take up to 24 (03.7, 13.2), and Google's spend-based limits warn of overages during a latency period of around 10 minutes. Use provider alerts as a second line, not the first. OpenAI offers organization spend alerts and a hard limit, Anthropic organization and workspace spend limits (03.7, 12.4).

Part 6: Evaluate it#

Rate limits, kill switches and alerts are controls, so the useful questions are "does it protect the victim?", "does it stop in time?" and "does it page when it should and only then?". Modules 10A and 10B teach evaluation in general. Start with the concept lessons in 10A, then the DeepEval lessons in 10B, then the optional Inspect lessons.

What to measure for this lesson's topic

  1. Isolation. Under a noisy neighbour, the share of a victim team's requests that are served (target: at least 95% when it stays inside its guarantee). The simulation in 1.4 is this test.
  2. 429 rate by team and retries per success, to see who is hurting whom.
  3. Time to stop. From "someone decides to trip" (or the spend breaker fires) to "no new model calls in that scope". Drill it.
  4. False trips. Kill-switch activations that were not real incidents.
  5. Alert quality. Detection delay per incident, and false pages per week, on replayed history.
  6. Throughput choice. Cost per successful task and p95 latency per option on a replayed day (10A.7, 5.6).

A concrete tiny eval: replaying incidents against your alert rules. Inputs: 14 days of hourly spend with three labelled incidents (a loop at 6x for 10 hours, a retry storm at 4x for 6 hours, a bigger loop at 8x for 20 hours) and a harmless nightly batch spike now and then. Metric: hours from incident start to the first page, and pages outside incidents. Pass rule: every incident paged within 2 hours, and at most 2 false pages in the fortnight. Save as alert_eval.py next to alerts.py:

python
# alert_eval.py: measure your alert rules against labelled incidents (lesson 11B.7)
"""Replay 14 days of hourly spend with three known incidents. Pass rules: every incident is paged within
2 hours of its start, and there are at most 2 pages outside incidents in the fortnight."""
import random

from alerts import AlertEvaluator

HOURS = 14 * 24
INCIDENTS = [(60, 10, 6.0), (150, 6, 4.0), (260, 20, 8.0)]       # (start hour, length in hours, multiplier)


def series(seed: int) -> list[float]:
    rng = random.Random(seed)
    out = []
    for h in range(HOURS):
        base = 3.0 + 1.5 * (9 <= h % 24 <= 17) + rng.uniform(-0.4, 0.4)
        if h % 24 == 3 and rng.random() < 0.2:                    # a harmless nightly batch spike now and then
            base += 3.0
        for start, length, mult in INCIDENTS:
            if start <= h < start + length:
                base *= mult
        out.append(base)
    return out


def evaluate(seed: int, **kw) -> dict:
    ev = AlertEvaluator(budget_usd=10_000, period_hours=HOURS, **kw)   # budget high: only anomaly rules matter here
    for h, v in enumerate(series(seed)):
        ev.observe(h, v)
    pages = [a.hour for a in ev.alerts if a.severity == "page"]
    delays = []
    for start, length, _ in INCIDENTS:
        hit = [h for h in pages if start <= h < start + length]
        delays.append(None if not hit else hit[0] - start)
    inside = {h for p in pages for start, length, _ in INCIDENTS if start <= p < start + length for h in [p]}
    false_pages = len([p for p in pages if p not in inside])
    return {"delays": delays, "false_pages": false_pages}


for label, kw in (("z_page=6 (default)", {}), ("z_page=3 (too sensitive)", {"z_page": 3.0}),
                  ("z_page=20 (too relaxed)", {"z_page": 20.0})):
    res = evaluate(seed=4, **kw)
    caught = all(d is not None and d <= 2 for d in res["delays"])
    ok = caught and res["false_pages"] <= 2
    print(f"{label:<26} detection delays (hours) {res['delays']}  false pages {res['false_pages']}  -> {'PASS' if ok else 'FAIL'}")
Output3 lines
z_page=6 (default)         detection delays (hours) [0, 0, 0]  false pages 0  -> PASS
z_page=3 (too sensitive)   detection delays (hours) [0, 0, 0]  false pages 3  -> FAIL
z_page=20 (too relaxed)    detection delays (hours) [0, None, 0]  false pages 0  -> FAIL

The default threshold passes: every incident is paged in the first hour and there are no false pages. A too-sensitive threshold (z_page=3) catches everything but raises three false pages. A too-relaxed threshold (z_page=20) misses the second incident entirely. This is how you tune a rule: against labelled history, with both kinds of error counted, not by feel. Re-run it whenever you change the rule or find a new incident worth adding.

The tests for this lesson's code (14 tests: the fair-share rules, the kill-switch rules, the circuit breaker and the alert evaluator) are the other half of the evaluation. Save as test_guard.py:

python
# test_guard.py: fair share, kill switch and alerts under test (lesson 11B.7). Run: python3 -m unittest -v
import random
import unittest

from alerts import AlertEvaluator, robust_z
from fair_share import FairShareLimiter, FakeClock
from kill_switch import CircuitBreaker, FlagStore, KillSwitch, SpendBreaker


class FairShareTests(unittest.TestCase):
    def test_guarantees_cannot_exceed_the_provider_limit(self):
        with self.assertRaises(ValueError):
            FairShareLimiter(1_000, {"a": 600, "b": 600}, FakeClock())

    def test_a_flooding_team_cannot_touch_another_teams_guarantee(self):
        clock = FakeClock()
        lim = FairShareLimiter(6_000, {"a": 3_000, "b": 1_000}, clock)   # 2,000 spare
        for _ in range(500):                                            # a floods
            lim.acquire("a", 100, priority="batch")
        self.assertEqual(lim.acquire("b", 100).source, "guaranteed")    # b is untouched

    def test_batch_cannot_borrow_from_a_drained_spare_pool(self):
        clock = FakeClock()
        lim = FairShareLimiter(6_000, {"a": 1_000}, clock)
        lim.spare.level = 0.2 * lim.spare.capacity
        lim.team["a"].level = 0
        self.assertFalse(lim.acquire("a", 10, priority="batch").ok)
        self.assertTrue(lim.acquire("a", 10, priority="interactive").ok)

    def test_denial_reports_a_usable_retry_after(self):
        clock = FakeClock()
        lim = FairShareLimiter(600, {"a": 600}, clock, burst_s=1)         # 10 tokens/s, capacity 10
        self.assertTrue(lim.acquire("a", 10).ok)
        denied = lim.acquire("a", 10)
        self.assertEqual((denied.ok, denied.retry_after_s), (False, 1.0))
        clock.advance(1.0)
        self.assertTrue(lim.acquire("a", 10).ok)

    def test_settle_gives_back_the_over_reservation(self):
        clock = FakeClock()
        lim = FairShareLimiter(600, {"a": 600}, clock, burst_s=10)
        admit = lim.acquire("a", 80)
        before = lim.team["a"].level
        lim.settle("a", admit.source, reserved=80, actual=30)
        self.assertEqual(lim.team["a"].level, before + 50)


class KillSwitchTests(unittest.TestCase):
    def setUp(self):
        self.clock, self.store = FakeClock(), FlagStore()
        self.ks = KillSwitch(self.store, self.clock, {"lead": {"team:x"}, "oncall": {"*"}, "automation": {"*"}},
                             fail_open_scopes=frozenset({"feature:free"}))

    def test_only_listed_roles_may_trip_a_scope_and_refusals_are_audited(self):
        with self.assertRaises(PermissionError):
            self.ks.trip("*", "bob", "lead", "no")
        self.assertEqual(self.ks.audit[-1]["action"], "REFUSED")
        self.ks.trip("team:x", "amy", "lead", "loop")
        self.assertFalse(self.ks.check("*", "team:x")[0])
        self.assertTrue(self.ks.check("*", "team:y")[0])

    def test_store_outage_fails_closed_unless_scope_is_listed(self):
        self.store.down = True
        self.assertFalse(self.ks.check("feature:paid")[0])
        self.assertTrue(self.ks.check("feature:free")[0])

    def test_ttl_trip_expires_and_reset_clears(self):
        self.ks.trip("team:x", "amy", "oncall", "test", ttl_s=60)
        self.clock.advance(61)
        self.assertTrue(self.ks.check("team:x")[0])
        self.ks.trip("team:x", "amy", "oncall", "again")
        self.ks.reset("team:x", "amy", "oncall", "fixed")
        self.assertTrue(self.ks.check("team:x")[0])

    def test_spend_breaker_trips_only_when_the_window_total_crosses(self):
        sb = SpendBreaker(self.ks, "team:x", limit_usd=3.0, window_s=100, clock=self.clock)
        for _ in range(3):
            sb.record(1.0)
            self.clock.advance(10)
        self.assertTrue(self.ks.check("team:x")[0])
        sb.record(1.0)
        self.assertFalse(self.ks.check("team:x")[0])

    def test_old_spend_falls_out_of_the_window(self):
        sb = SpendBreaker(self.ks, "team:x", limit_usd=3.0, window_s=100, clock=self.clock)
        sb.record(2.5)
        self.clock.advance(200)
        sb.record(2.5)
        self.assertTrue(self.ks.check("team:x")[0])


class CircuitBreakerTests(unittest.TestCase):
    def test_open_probe_close(self):
        clock = FakeClock()
        cb = CircuitBreaker(2, 10, clock)
        cb.record(False)
        cb.record(False)
        self.assertFalse(cb.allow())
        clock.advance(10)
        self.assertTrue(cb.allow())          # the one probe
        self.assertFalse(cb.allow())         # no second probe while it is out
        cb.record(True)
        self.assertEqual(cb.state, "closed")


class AlertTests(unittest.TestCase):
    def test_quiet_noise_raises_no_anomaly(self):
        rng = random.Random(1)
        ev = AlertEvaluator(budget_usd=10_000, period_hours=720)
        for h in range(72):
            ev.observe(h, 4 + rng.uniform(-0.5, 0.5))
        self.assertEqual([a for a in ev.alerts if a.kind == "anomaly"], [])

    def test_thresholds_fire_once_and_a_loop_pages_once_per_cooldown(self):
        ev = AlertEvaluator(budget_usd=100, period_hours=720, cooldown_hours=6)
        for h in range(24):
            ev.observe(h, 1.0)
        for h in range(24, 36):
            ev.observe(h, 30.0)
        names = [a.message[:3] for a in ev.alerts if a.kind == "threshold"]
        self.assertEqual(names, ["50%", "80%", "100"])
        pages = [a for a in ev.alerts if a.kind == "anomaly"]
        self.assertEqual([a.hour for a in pages], [24, 30])

    def test_robust_z_ignores_a_single_past_spike(self):
        history = [4.0, 4.1, 3.9, 4.0, 4.2, 3.8, 90.0, 4.0, 4.1, 3.9, 4.0, 4.0]
        self.assertGreater(robust_z(history, 20.0), 6)


if __name__ == "__main__":
    unittest.main()

Real output of python3 -m unittest -v:

text
test_quiet_noise_raises_no_anomaly (test_guard.AlertTests.test_quiet_noise_raises_no_anomaly) ... ok
test_robust_z_ignores_a_single_past_spike (test_guard.AlertTests.test_robust_z_ignores_a_single_past_spike) ... ok
test_thresholds_fire_once_and_a_loop_pages_once_per_cooldown (test_guard.AlertTests.test_thresholds_fire_once_and_a_loop_pages_once_per_cooldown) ... ok
test_open_probe_close (test_guard.CircuitBreakerTests.test_open_probe_close) ... ok
test_a_flooding_team_cannot_touch_another_teams_guarantee (test_guard.FairShareTests.test_a_flooding_team_cannot_touch_another_teams_guarantee) ... ok
test_batch_cannot_borrow_from_a_drained_spare_pool (test_guard.FairShareTests.test_batch_cannot_borrow_from_a_drained_spare_pool) ... ok
test_denial_reports_a_usable_retry_after (test_guard.FairShareTests.test_denial_reports_a_usable_retry_after) ... ok
test_guarantees_cannot_exceed_the_provider_limit (test_guard.FairShareTests.test_guarantees_cannot_exceed_the_provider_limit) ... ok
test_settle_gives_back_the_over_reservation (test_guard.FairShareTests.test_settle_gives_back_the_over_reservation) ... ok
test_old_spend_falls_out_of_the_window (test_guard.KillSwitchTests.test_old_spend_falls_out_of_the_window) ... ok
test_only_listed_roles_may_trip_a_scope_and_refusals_are_audited (test_guard.KillSwitchTests.test_only_listed_roles_may_trip_a_scope_and_refusals_are_audited) ... ok
test_spend_breaker_trips_only_when_the_window_total_crosses (test_guard.KillSwitchTests.test_spend_breaker_trips_only_when_the_window_total_crosses) ... ok
test_store_outage_fails_closed_unless_scope_is_listed (test_guard.KillSwitchTests.test_store_outage_fails_closed_unless_scope_is_listed) ... ok
test_ttl_trip_expires_and_reset_clears (test_guard.KillSwitchTests.test_ttl_trip_expires_and_reset_clears) ... ok

----------------------------------------------------------------------
Ran 14 tests in 0.001s

OK

Where to go next in Modules 10A and 10B


Common misconceptions#

  • "Our provider limit is per team." It is per account (organization, project or workspace). The provider does not know your teams exist.
  • "A workspace or project limit guarantees a team its share." It caps that workspace. It protects the others by capping one neighbour; it is not a floor.
  • "A 429 means slow down." It can also mean a ramp limit, or a spend cap where retrying is pointless.
  • "Provisioned throughput is always cheaper at scale." Only above the break-even utilization, after you have moved everything deferrable to batch.
  • "Batch is just a discount." It is also a separate rate-limit pool that keeps heavy offline work off your interactive limit.
  • "A kill switch is one big off button." It is a set of scopes, with roles, a TTL and an audit log. A switch only ever used as * never gets used.
  • "If the flag store is down, let traffic through." For expensive or risky features, fail closed; list the few that may fail open.
  • "Mean and standard deviation are fine for spikes." A loop is an outlier that inflates both. Use median and MAD.
  • "Alert at 80% of the monthly budget and we are safe." A fast loop can use 80% in an hour. Add burn rate and anomaly rules.

Key takeaways#

  • Provider limits are shared by everything on one account. Carve them up with projects or workspaces, and enforce guarantees yourself in a gateway.
  • Fair share = guaranteed bucket per team + spare pool + priority for who may borrow. Refill rates sum to the provider limit.
  • A 429 can be a rate limit, a ramp limit or a spend cap. Only the first two are retried, and one layer owns retries.
  • Read the rate-limit headers and feed them back into your limiter; charge retries to the team that caused them.
  • Order the throughput decision: batch what can wait, provision only the steady baseline, let on-demand take the peaks. Provisioned wins only above its break-even utilization.
  • A kill switch needs scopes, roles, a TTL, an audit trail and fail-closed behaviour, and it needs to be drilled.
  • Use three alert shapes (threshold, burn rate, anomaly), a robust statistic, a floor and a cooldown. Tune them on labelled incidents.

Terms introduced in this lesson#

Term Meaning
Noisy neighbour A tenant that uses so much of a shared resource that others suffer
Token bucket A rate limiter whose capacity refills continuously up to a maximum; a request spends tokens from it
Guaranteed share The part of a shared limit reserved for one team
Spare pool Capacity not guaranteed to anyone, which teams may borrow when their own share is empty
Reserved capacity The sum of the guarantees, kept below the total so a spare pool remains
Priority class A label (interactive, batch) that decides who may borrow from the spare pool
Retry-after How long to wait before trying again; a header from the provider or a value from your limiter
Ramp limit A cap on how fast usage on a model may grow, separate from the per-minute limits
Flex A cheaper synchronous tier that may queue or fail under load
Fast mode A faster, more expensive tier with no commitment (OpenAI; Anthropic on selected models)
Batch API An asynchronous API with a completion window, a discount and its own limits
Provisioned throughput Reserved model capacity billed per unit per hour or per term, used or not
PTU / model unit The capacity unit of Azure (PTU) and Amazon Bedrock (model unit) provisioned throughput
Spillover Routing overflow from a full provisioned deployment to a standard one
Break-even utilization The share of time a provisioned unit must be busy to beat on-demand
Kill switch A control that stops model traffic at a chosen scope, quickly and without a deploy
Scope (kill switch) The level a switch applies to: everything, a provider, a team, a feature, a tenant or a tool
Fail closed / fail open What happens when the flag store is unreachable: refuse calls, or allow them
Circuit breaker A guard that stops calls after repeated failures, then lets one probe through
Spend breaker A guard that trips a scope when spend in a sliding window crosses a limit
Burn rate The pace at which a budget is being used, compared with the time left in the period
Robust z-score A distance from the median in units of the median absolute deviation, resistant to outliers
Alert fatigue Ignoring alerts because too many are noise

Exercises#

  1. Borrow another team's idle guarantee. Change FairShareLimiter.acquire so a team may also take from another team's bucket when that bucket is more than 80% full, but only for interactive traffic. Re-run demo_fair.py and check that the victim team's served percentage does not drop. Hint: peek at the other buckets in a loop and take from the fullest; add a test that a flooding team cannot touch another team's guarantee below the 80% mark.
  2. Add a retry-after to the demo. Make the simulation retry denied requests after their retry_after_s (use the clock) and report how many seconds each team waited in total. Hint: keep a heap of (ready_time, team, tokens) and advance the clock to the earliest ready time.
  3. A second kill-switch rule. Add a rule that automatically trips provider:anthropic when the circuit breaker has opened three times in an hour, with a 15-minute TTL. Test it with the fake clock. Hint: count opens in CircuitBreaker.record and call KillSwitch.trip with the automation role.
  4. Tune an alert. Add a fourth incident to alert_eval.py (a slow rise: spend grows 5% an hour for 40 hours). Does the anomaly rule catch it? Which rule does? Hint: the burn-rate rule is the one built for slow rises; change the budget so it can fire.
  5. Break-even with your numbers. Replace the made-up prices in throughput_choice.py with a real quote (one provisioned unit's hourly price and its tokens per hour, and your on-demand blended price). Compute the break-even utilization and compare it with your traffic profile. Hint: derive your blended price from your input to output token ratio and the two list prices.
  6. Write the runbook. Write a one-page runbook for "spend alert fired": who is paged, what they check first, which scope they trip, how they confirm it worked, and how they reset. Hint: use the audit log fields as a checklist.

Check yourself#

  1. Why does a provider rate limit not protect one of your teams from another?
  2. In the fair-share design, why must the refill rates add up to the provider limit?
  3. Why may batch traffic borrow from the spare pool only when it is more than half full?
  4. Name the three things a 429 can mean and what to do for each.
  5. What does Anthropic's workspace limit give you, and what does it not give you?
  6. Why can a larger max_output_tokens lower your throughput on OpenAI but not on Anthropic's OTPM?
  7. When does provisioned throughput beat on-demand, and what should you do before buying it?
  8. What does "fail closed" mean for a kill switch, and when might you choose "fail open"?
  9. Why use median and MAD instead of mean and standard deviation for spend anomalies?
  10. Why should an alert have a floor and a cooldown?

Further resources#

Existing lessons:

Official documentation (read on 1 December 2026):


← 11B.6 — Budgets, Quotas, Cost Attribution and Chargeback | Module 11B overview | 11B.8 — The Cost of Agents and Long Contexts, Prompt Caching per Provider, and the Cost of Running Evals →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close