Unit 7 of 12 · about 5 hours · derive, implement

Rate limits, admission control, retry amplification and load shedding

The Systems unit on overload control established retry budgets and shedding. AI requests add variable input and output work, quality failures and cascades that can multiply that work before any task completes.

You'll be able to

  • Derive attempt amplification and token-weighted admission limits for a bounded AI workflow.
  • Implement one retry owner, bounded queues and priority-aware shedding under model outages.
  • Preserve safety and verified task semantics in degraded modes rather than treating fast rejection as success.

Covers

Rate limits, queues, admission control and backpressureRetry and fallback amplification under partial outagesPriority-aware load shedding and degraded modes
1

Read

In this order, only the parts listed

0 of 3 done

  1. Adaptive rejection and retry budgetsGoogle SRE Book and SRE Workbook

    Chapter 21, The Pitfalls of "Queries per Second"; Client-Side Throttling, including the rejection-probability image; Criticality; Deciding to Retry

    Use the calculation and criticality propagation, not Google's example retry ratios as universal constants. Skip datacenter quota infrastructure.

  2. Prevent amplification and abandoned workGoogle SRE Book and SRE Workbook

    Chapter 22, Queue Management; Load Shedding and Graceful Degradation; Retries; Latency and Deadlines

    Skim the Systems fundamentals. Focus on applying the same attempt and remaining-time limits across the gateway, adapter and model client.

  3. Rate and burst are separate quantitiesRFC 2697: A Single Rate Three Color Marker

    RFC 2697, Sections 2 Configuration and 3 Metering

    The RFC defines a two-bucket packet meter. Borrow its rate/burst distinction, then explicitly derive the simpler one-bucket application limiter; do not claim RFC conformance.

2

Focus on

  • A semaphore limits concurrency, a token bucket limits admitted work over time, and a bounded queue limits waiting work. Also bound waiting producers, payload bytes and all detached attempts.
  • For an application bucket of capacity , rate and elapsed time , refill as . Atomically admit reserved work only when , then debit it. Use a monotonic clock and an explicit input/output work estimate.
  • SRE adaptive rejection is , with attempted requests , backend accepts and configured factor . Include locally rejected attempts in the history and keep criticality classes separate.
  • Make one layer own retries, with bounded attempts, jitter and the original deadline. Prefer authorized abstention or explicit failure over a cheaper answer that violates the task's quality or safety floor.
Common mistakes · 3
  • Limiting only request count when context and output lengths vary. One admitted request may consume most of the generation budget.
  • Retaining SDK retries beneath gateway retries or resetting the allowance for each fallback. Attempts multiply across layers.
  • Saying a full queue bounds latency. It bounds queued items; variable generation time still needs service deadlines and cancellation.
3

Try it yourself

Closed-book, before checking anything

Derive and run these CPU fixtures: three layers each allowing one initial attempt plus three retries can make 64 bottom-layer attempts. With 1000 attempted requests, 300 backend accepts and SRE factor 2, obtain rejection probability 0.3996003996. For a separate one-bucket limiter initially holding 100 token-work units and refilling 20 units/s, admit weight 80 at time zero, reject another weight 30 immediately without debiting, then admit weight 30 after one second and leave 10 units. Implement the last fixture with a fake clock and an atomic admission operation; test two simultaneous callers competing for the final allowance.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.Why is the three-layer example 64 attempts rather than 27?Answer

    It allows four total attempts at each layer: . Three total attempts per layer would give ; distinguish retries from total tries.

  2. 2.Does a low-latency request have to be high criticality?Answer

    No. A speculative suggestion may need a quick response but be safe to shed. Criticality expresses importance, not patience.

  3. 3.Why can an outage continue after the original fault disappears?Answer

    Queued retries and fallbacks can sustain overload. Bound new admission and recovery probes, stop expired work and drain the backlog rather than reopening full traffic immediately.

You're done when

Your hand calculations and fake-clock tests agree, concurrent callers cannot overspend one allowance, and an outage cannot exceed the declared attempt, queue and deadline bounds.

Only when you can do this without notes.

Leads to

Notes

Resources · 2 for this unit, 18 more in the section
  • Google SRE Book and SRE WorkbookGoogle · primary

    Read SRE book Chapter 21 Handling Overload ("Deciding to Retry": per-request and per-client retry budgets; client-side throttling max(0, (requests - K * accepts) / (requests + 1)) with K = 2, printed as an image; criticality) and Chapter 22 Addressing Cascading Failures (queue management, load shedding, retries with the 4^3 = 64 amplification, deadline and cancellation propagation). Then Chapters 3, 4 and 6 for error budgets, SLOs and golden signals, and Workbook Chapters 2 Implementing SLOs, 5 Alerting on SLOs (burn rates), 16 Canarying Releases and Appendix B (error budget policy). Skip SRE Chapter 10 and Workbook Chapter 17, which is about team workload. The numbers are examples to calibrate on your own workload.

  • RFC 2697: A Single Rate Three Color MarkerIETF · reference

    Use Sections 2 and 3 for the rate and burst definitions behind a token bucket. The RFC meter has two buckets; derive the one-bucket application limiter explicitly and weight it by tokens, not requests.

Also in this section

  • AlgoMaster AI Engineering - Production UnitsAlgoMaster · support

    Read the free lessons understanding-ai-application-costs (hidden costs, cost tracking, budgets) and architecture-patterns-for-ai-applications ("Why Queues Matter"), then the owned premium lessons on caching, model selection and routing, rate limiting, reliability, monitoring and CI/CD for AI. For every recommendation, run one measured workload or fault case.

  • AI Engineering Handbook - Production AIHandbook Academy · required

    Read the chapters that carry the LLM-specific half: 2.6 Gateways and routing, 2.7 Prompt caching, 3.4 Prompt versioning, 8.6 Tracing, 8.7 Monitoring and dashboards, 10.3 Cost engineering, 10.4 Latency engineering, 10.5 Shipping changes, 10.6 SLOs and incident response and 10.7 AI infrastructure patterns. Prices and model names in them date from June 2026; recompute any cost with your own numbers.

  • OpenTelemetry GenAI Semantic ConventionsOpenTelemetry · required

    The opentelemetry.io GenAI pages now point here; pin this commit (status Development). Read client-inference.md (inference span, gen_ai.usage.*: cache read and write tokens are subsets of input), gen-ai-spans.md (embeddings, retrieval, execute_tool, recording content only by opt-in) and gen-ai-agent-spans.md (invoke_agent). Emit a redacted span tree and assert required attributes and parentage.

  • LLM Cost Optimization and Observability DesignEngineering Handbook · support

    Read the LLM Cost Optimization chapter (price ladder and cost attribution), then LLM Evaluation and Observability at /curriculum/ai-ml-system-design/llm-evaluation-observability/. Use the capacity and cost equations as hypotheses, validate them against your workload and record where system behavior differs.

  • Semantic Cache and Model Router Case StudiesEngineering Handbook · support

    Read case study 8.37 (model router and gateway: routing strategies, failover before the first byte, hedging cost, budget reservation with soft and hard limits, a cost ledger) and case study 8.36 at /curriculum/case-studies/semantic-cache/ (threshold calibration, invalidation channels, singleflight, fail-open). Recompute their capacity tables: 8.36's embedding-cost and savings lines are off by orders of magnitude. Implement only the smallest cache and router needed for a three-policy comparison.

  • Prompt Caching (OpenAI)OpenAI · required

    Read "How caching works", "How prefix matching works", "Cache lifetime" and "Summary of model differences": GPT-5.6 and later use implicit and explicit breakpoints, report cache_write_tokens beside cached_tokens, and charge writes and reads differently; earlier models differ. Normalize a stored usage fixture; this is prefix reuse, not response reuse.

  • Prompt Caching (Claude)Anthropic · support

    Read explicit breakpoints, automatic prefix checking, cache limitations (minimums differ by model), tracking cache performance and what invalidates the cache. Claude reports input_tokens excluding cache reads and writes, unlike OpenAI, so normalize both before recording one input total.

  • MeanCache: User-Centric Semantic Caching for LLM Web ServicesGill et al. · required

    Read IV-A3 (true and false hits and misses), IV-B Figure 7, IV-C and IV-F (thresholds 0.83 for MPNet and 0.78 for ALBERT on its own data). Report false hits per served hit and per negative query, which have different denominators. Sweep a threshold on held-out labeled pairs before enabling any semantic cache.

  • RouteLLM: Learning to Route LLMs with Preference DataOng et al. · support

    Read Section 3.2 (call fraction, performance gap recovered, APGR, CPT) and Section 4.2. Replay the stored GSM8K outcomes in the repository (pinned 0b64fda) for a random-routing baseline. Its matrix-factorization router needs an OpenAI embedding key, and evaluate.py passes a model name where the model pair belongs.

  • FrugalGPT: How to Use Large Language Models While Reducing Cost and Improving PerformanceChen, Zaharia and Zou · support

    Read Section 3, Strategy 3 LLM cascade: escalate only when a scorer rejects the cheaper answer, and count the cost of every stage reached. Section 5 notes the scorer needs train and test from the same distribution.

  • Using Load Shedding to Avoid OverloadAmazon Builders' Library · support

    Read "Preventing work from going to waste", "Testing" (goodput should plateau, not collapse), "Visibility", "Prioritizing requests" and "Watching out for queues". Count accepted, quality-checked work as goodput, not fast rejections.

  • Per-Run Spending ControllerOpenAI Cookbook · support

    Read the article and run its code offline: count input tokens, reserve the most a response could cost, settle the actual usage, release the rest and stop before the next call would exceed the run budget. Port the reserve and settle rule to your gateway with exact arithmetic.

  • Optimizing Agents for Cost and QualityOpenAI Cookbook · support

    Run it with live calls off: a baseline, then controls, routing, caching and a split workflow, each accepted only if a small evaluation set still passes. The numbers are modeled; copy the study design, not the results.

  • vLLM Automatic Prefix CachingvLLM · support

    Read the introduction, enabling APC, example workloads and limits: prefix caching skips repeated prefill but does not shorten decoding. Measure cold and warm requests and a changed prefix on your local server, with the model, template and settings fixed; any local server with an equivalent feature works.

  • LiteLLM Routing, Reliability and BudgetsLiteLLM · reference

    Use the routing, fallbacks and cooldowns, budget reservation and fail-closed rate-limit sections as a reference design for your own small gateway. A fallback must recheck the caller's model access and budget against the actual target.

  • The Tail at ScaleJeffrey Dean and Luiz André Barroso · depth

    Read printed pages 77 and 78 on hedged and tied requests and their limit when slowness is correlated across replicas. Never hedge a side-effecting tool call or two generations on one saturated GPU.

  • Full Stack Deep Learning - LLM BootcampFull Stack Deep Learning · reference

    Read the LLMOps chapter summaries "Iteration and prompt management", "Testing LLMs: What works?" and "Evaluation metrics for LLMs". Skip the 2023 model-choice sections, which are out of date.

  • Made With MLMade With ML · optional

    Read the online evaluation section only if the rollout card needs a classical-ML comparison; the course has no LLM application content.