CD0024 AI Rate-Limiter Retry

Mode D · AI-Assisted 60 Min Python 3.10+ 3 Phases · 3 Draft Flaws

Shopify’s REST Admin API meters every app with a leaky bucket. Standard plans get a burst of 40 requests per store and a steady leak of 2 requests per second, and a request that overflows the bucket comes back as HTTP 429 with a Retry-After header. An inventory-sync team that talks to thousands of stores keeps a small Python client, rate_client.py. It holds a client-side token bucket sized to the same 2 req/s and burst of 40, plus a retry_call helper that every worker uses. The AI-enabled coding round built on this client runs 60 minutes in three phases, and the AI assistant becomes available from Phase 2 onward.

Phase 1 (Unaided Warm-Up): the starter bucket carries one planted refill bug. In a 60-second soak test where one worker polls try_acquire() every 250 ms, the client admits its 40-request opening burst and then nothing for the remaining 59 seconds. A sync job that wakes every 1.5 s and drains the bucket gets about 1.3 req/s instead of 2. Find and fix the bug by hand. Phase 2 (AI-Delegated Build): pick the one prompt out of three that pins the full retry contract below. Phase 3 (Audit): the assistant’s draft passes a 503-then-200 smoke test but violates the contract in three places. Find them, patch them in place, and prove every fix on a scripted clock.

Phase 2 Target Contract:
(1) Retryable Set: retry HTTP 429, any 5xx, and a raised ConnectionError or TimeoutError. Return every other status to the caller at once.
(2) Wait Source: wait the Retry-After value in seconds when the response carries one. Otherwise use exponential backoff d_n = \min(c, \beta 2^n) with full jitter, so that clients failing together spread across the whole window.
(3) Budget Bound: each call has a budget (default 60 s) on a monotonic clock and at most max_attempts attempts. If a wait would cross the deadline, give up and surface the last response or error instead of sleeping.

Phase 1 Starter (rate_client.py):

01  import time
02
03
04  class RateLimiter:
05      """Client-side token bucket: rate tokens/s, at most capacity held."""
06
07      def __init__(self, rate, capacity, clock=time.monotonic):
08          self.rate = float(rate)
09          self.capacity = float(capacity)
10          self.clock = clock
11          self.tokens = float(capacity)
12          self.last = clock()
13
14      def try_acquire(self):
15          now = self.clock()
16          elapsed = now - self.last
17          self.tokens = min(self.capacity, self.tokens + int(elapsed) * self.rate)
18          self.last = now
19          if self.tokens >= 1.0:
20              self.tokens -= 1.0
21              return True
22          return False
23
24
25  def retry_call(send, limiter, sleep=time.sleep, poll=0.05):
26      """Wait for a token, then send once. Phase 2 adds retries here."""
27      while not limiter.try_acquire():
28          sleep(poll)
29      return send()
Request lifecycle of the rate-limited client: caller, token bucket at 2 requests per second with burst 40, send to the Admin API, then two question-marked steps (classify outcome, choose wait) and a return-or-raise box, with a dashed retry arc back to the bucket; below, three contract boxes list the retryable set, the wait source, and the 60 second budget

Figure 1: the Phase 1 token bucket gates every attempt. The two question-marked steps are what the AI builds in Phase 2 and you audit in Phase 3, and the bottom row is the Phase 2 Target Contract every prompt must pin.

Interactive Python Workspace: Switch to the split-screen workspace to fix the starter, steer the simulated AI Copilot, and audit its draft against the hidden test suite.

Open in Colab ↗
Progressive Hints (Free · Zero Spoilers)
1Inspection Checklist (Where to Look)

(1) Refill Accounting: Replay one poller on a fake clock at 250 ms, 1 s, and 1.5 s cadences, and compare the admitted count with burst plus rate times duration.
(2) Contract Checklist: Score each Phase 2 prompt line by line against the retryable set, the wait source, the jitter form, and the budget bound. One contradicted line disqualifies a prompt.
(3) Hostile Inputs: Drive the draft with a scripted clock and a matrix of status codes, raised errors, and Retry-After values from 0 up to far beyond the budget, recording attempts and total sleep.
(4) Crowd Behavior: Start many seeded clients that fail at the same instant and measure how widely their later retries spread.

2Visual Review Map (Figure 2)
Review map with the same question mark on every region: three regions of the Phase 1 listing (init state, try_acquire, retry_call), the Phase 2 prompt choice, and three regions of the Phase 3 draft (backoff helper, attempt loop, wait selection)

Figure 2: Every region of the listing and the draft carries the same question mark. Walk each one with a scripted clock rather than guessing from the code which one hides a defect.

3Interviewer Nudge & Line Focus

Answer each phase’s Socratic check with numbers before editing:

Phase 1 (Token Crediting): A poller calls try_acquire() every 250 ms against a 2 req/s bucket. How many tokens should four consecutive calls credit in total, and how many does the starter credit? What should a 60-second run admit, counting the 40-token burst?
Phase 2 (Spotting Flawed Prompts): Turn the contract into four checkboxes: retryable set, wait source, jitter form, budget bound. Which prompt ticks all four, and which ones state a status rule, a jitter rule, or a sleep rule that sounds reasonable but contradicts a checkbox?
Phase 3 (Auditing the Retry Draft): With 60 s of budget left, how long does the draft sleep for a 429 carrying Retry-After: 3600? If 200 clients all fail at t = 0, how wide is the window in which their fourth attempt lands? How many requests does a single 404 cost the shared bucket?
Answer
Login to view more content
Log in to track your progress

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *