Free self-study · No account needed · Progress stays in this browser. Back it up before clearing site data or changing devices.

← Week 23: Production AI Architecture

Week 23 / Lesson 2

Operating under load and overload

Bound queued work and isolate failures while keeping cached data correctly scoped.

Section 2.1 1 of 7

Overview

Focus

Bound queued work and isolate failures while keeping cached data correctly scoped.

Your route through the lesson

  • 2.2 Queues, backpressure, and dead-letter outcomes
  • 2.3 Rate limits and cancellation
  • 2.4 Permission-aware caches, monitoring, and failure isolation
  • 2.5 Put it into practice
  • 2.6 Guided comparison
  • 2.7 A shared cache leaking another user’s answer

All required teaching is included here. Review selections are saved. Choose a correct answer for every question to continue; retries are unlimited. Study time and personal notes are optional.

Section 2.2 2 of 7

Queues, backpressure, and dead-letter outcomes

Focus

Bound queue capacity and give overload and failed jobs explicit outcomes.

A queue holds admitted work until a worker can execute it. First-in, first-out ordering processes older entries before newer ones. Capacity must be bounded: an unlimited backlog can consume memory and make old requests useless long before the service crashes. Backpressure tells callers to slow down or retry later when capacity is exhausted.

Python queue.Queue(maxsize=2) creates a thread-safe queue with room for two waiting items. put_nowait attempts admission immediately and raises queue.Full when no slot exists. get_nowait removes an available item, and task_done records completed queue work. The standard-library queue reference explains these semantics without any package installation.

A failed job needs a terminal outcome after bounded retries. A dead-letter record preserves its identifier, error category, attempts, and ownership for inspection rather than cycling forever. Queue size alone is insufficient monitoring: a short queue with one hour-old job can be worse than a longer fast-moving queue. Record enqueue time, start time, deadline, and completion or cancellation state. Keep sensitive payloads protected in both active and failed-job storage.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A size-two queue already holds two jobs. What does put_nowait do for a third?
2. A job fails after its retry limit. What is an explicit terminal path?
3. A queue has one job waiting an hour. Which metric exposes the concern?

Section 2.3 3 of 7

Rate limits and cancellation

Focus

Apply per-identity rate limits and propagate cancellation to queued work.

A rate limit bounds admissions over time, while queue capacity bounds currently waiting work. They solve related but different problems. A fixed-window limiter might allow two requests per identity per minute. Track counts by identity and window; one user's burst should not automatically consume another user's allowance.

If Alice has used two slots in the current window, her next request can receive a rate-limit response with a retry hint. Bob with zero uses can still be admitted if service capacity exists. Rate limiting does not create worker capacity, so a request can pass its identity limit and still encounter a full queue. Keep those error categories separate.

Cancellation should remove or mark queued work before it starts where possible, and workers should check deadlines before expensive stages. A canceled request may already have committed an effect, so preserve the operation ledger and reconcile it. An identity change or policy revocation can also invalidate queued permission. Recheck authorization at execution time for privileged work rather than treating earlier admission as a permanent grant.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. Alice reaches her per-minute limit while Bob has zero usage. What follows?
2. A request passes its rate limit but the queue is full. What should be reported?
3. Permission is revoked while a privileged job waits. What should the worker do?

Section 2.4 4 of 7

Permission-aware caches, monitoring, and failure isolation

Focus

Scope caches by permissions and isolate failing workloads while monitoring age and outcomes.

A cache reuses a prior computation. Its key must include every property that changes the permitted answer: identity or tenant, permission revision, source version, model or prompt version where relevant, and task input. A cache keyed only by question text can return Alice's private answer to Bob.

For a simple example, use the tuple ("alice","acl1","i1","balance") as a Python dictionary key. A tuple is an immutable ordered group. Bob's otherwise identical request has a different key and must miss. Permission revocation should change the permission revision or invalidate affected entries. Reauthorization is still required; possession of a cache key does not grant access.

Monitor accepted, rejected, completed, canceled, and failed jobs, plus queue age and per-stage latency. Isolate background indexing from interactive work with separate bounded capacity so one failing dependency cannot exhaust every lane. Cached errors also need deliberate policy: indefinitely reusing an unavailable result can conceal recovery. Record cache hit status and evidence age in traces while avoiding private payloads in ordinary logs.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A private-answer cache uses only question text. What risk follows?
2. Permission changes from acl1 to acl2. What should happen to acl1 cache entries?
3. Background indexing fills every interactive worker. What design helps?

Section 2.5 5 of 7

Put it into practice

Focus

Execute bounded admission, age accounting, rate-limit scope, and private-cache checks.

Save week23.py and run python week23.py --lesson 2. The script fills a real standard-library queue with j1 and j2, then catches queue.Full for j3. It removes the oldest entry and checks its synthetic age using enqueue time ten and current time thirty: the age is twenty time units.

The cache test inserts Alice's private answer under a tuple containing identity, permission version, source version, and question. Bob's corresponding lookup must return None. A small fixed-window counter then shows Alice at her declared limit while Bob remains below his own. These time and rate values are explicitly simulated, not measured service traffic.

Expected output reports an overload response category of 503, oldest simulated age twenty, and a private-cache miss for Bob. The actual queue behavior executes locally; the HTTP overload response is represented as a contract value rather than served by this lesson's queue code. Extend this same artifact with a canceled job and a dead-letter list. Assert that cancellation prevents its tool function from being called and that failure records retain ownership.

Download this week’s Python lab ↓

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A job enqueues at 10 and current simulated time is 30. What is its age?
2. Bob looks up Alice’s identity-scoped key variant. What is expected?
3. The lab prints overload_response=503 without serving that queue over HTTP. What ran?

Section 2.6 6 of 7

Guided comparison

Focus

Interpret each queue and cache assertion without overclaiming service performance.

The worked queue has a strict two-item waiting bound. The third insertion raises an exception caught by the admission logic, so overload is visible rather than silently losing the request. Removing j1 confirms first-in, first-out ordering. The age calculation uses declared simulated timestamps and therefore tests arithmetic, not real queue latency.

The cache test changes only identity while preserving the other key fields. Its miss demonstrates why identity must participate in private-response reuse. It does not prove that the cached content itself is correct, current, or properly redacted. Those require their own checks. The rate-limit fixture likewise demonstrates separate counters rather than a production distributed limiter.

For integration, place these policies at the actual service admission and execution boundaries. Return distinct rate-limit and capacity responses, record job identifiers, and test cancellation before tool effects. A service with several processes needs shared or coordinated counters if limits are global. Do not extrapolate a dictionary counter to cluster-wide enforcement. The weekly extension adds those boundary checks to the same narrow service rather than building an unrelated queue product.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. The third queue insertion is rejected explicitly. What property is shown?
2. An identity-scoped cache misses correctly for Bob. What is still unproven?
3. A dictionary rate counter lives in one process. What remains needed for a global multi-process limit?

Section 2.7 7 of 7

A shared cache leaking another user’s answer

Focus

Repair a shared cache that exposes another identity’s answer.

A finance assistant caches the answer to "What is my balance?" under that question text alone. Alice asks first and receives her private balance. Bob asks the same text and receives Alice's cached response without a new retrieval. The cache has bypassed the otherwise correct database permission filter.

The repair scopes keys by authorized identity or tenant, permission revision, source version, and relevant generation configuration. The service authenticates and authorizes before cache lookup, checks freshness, and invalidates entries when access changes. A regression test primes the cache as Alice, requests the same text as Bob, and asserts both no disclosure and the expected authorized Bob behavior.

This is a boundary failure even if the model never generated a new token for Bob. Security analysis must include shortcuts such as caches, memory, and replay records, not only retrieval and tools. A denial path also needs care: cached private error messages can leak resource existence. Return the permitted error shape and keep detailed diagnostics in scoped operational records. Performance optimization should preserve the original access contract at every reuse point.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. Alice’s answer is cached under question text only; Bob asks the same text. Where is the boundary failure?
2. When should authorization occur relative to private cache lookup?
3. A cached error reveals a private document exists. Is that relevant?

Your personal notes

Optional, ungraded, and saved only in this browser. Export a backup from the Academy homepage to keep them.

References and further reading
Ask your own AI assistant

Copy this prompt into an assistant you already use. Nothing is sent automatically, and your personal notes are not included.

Next lesson: Deploying and rolling out a coherent service →