Skip to main content
🔒 Preview mode. The first 15 Foundations lessons are free; this one is Pro. Start a 7-day trial to unlock the editor, AI hints and the rest of the curriculum. Card required, cancel any time in Dashboard.Start 7-day trial →
← CoursesSystem Design for Python JuniorsModule 1 · System Design FundamentalsRate limitingpredict11 / 105
+100 XP
Task
📝 **Task:** Predict the allow/deny string. The snippet runs a token bucket with capacity 5 and refill rate 1/sec against a hand-rolled sequence of timestamped requests. 📋 Implement the function above. Tests run automatically. 💡 **Hint:** Re-read the theory if you get stuck.
Predict the output

Read the code carefully

class TokenBucket:
    def __init__(self, capacity, refill_rate):
        self.capacity = capacity
        self.refill_rate = refill_rate
        self.tokens = capacity      # start full
        self.last = 0.0             # seconds

    def consume(self, now):
        # Refill based on elapsed time, capped at capacity.
        delta = now - self.last
        self.tokens = min(self.capacity, self.tokens + delta * self.refill_rate)
        self.last = now
        # Try to spend 1 token.
        if self.tokens >= 1:
            self.tokens -= 1
            return "allow"
        return "deny"

bucket = TokenBucket(capacity=5, refill_rate=1)
# Burst of 7 requests at t=0 — bucket has 5 tokens.
out = "".join(bucket.consume(0)[0] for _ in range(7))   # 5 'a' then 2 'd'
print(out)
# Wait 3 seconds — bucket refills to 3 tokens.
print(bucket.consume(3.0))                              # allow (3 → 2)
print(bucket.consume(3.0))                              # allow (2 → 1)
print(bucket.consume(3.0))                              # allow (1 → 0)
print(bucket.consume(3.0))                              # deny  (0)

# What does this print? Type your prediction.

What will the program print? Write here:

💬 Discussion

Be the first to ask a question or share a tip.
Sign in to join the discussion. Reading is free.
Loading discussion…