Bird
0
0

Consider this pseudocode snippet for token bucket check:

medium📝 Debug Q14 of 15
Rest API - Rate Limiting and Throttling

Consider this pseudocode snippet for token bucket check:
if tokens <= 0:
  reject_request()
else:
  tokens -= 1
  allow_request()

What is the bug in this logic?

AIt should check if tokens > 0 before allowing
BIt should increase tokens instead of decreasing
CIt should reject when tokens > 0
DIt should check if tokens < 1, not <= 0
Step-by-Step Solution
Solution:
  1. Step 1: Recall proper token bucket logic

    To consume 1 token, check if tokens >= 1 before decrementing (equivalent to reject if tokens < 1).
  2. Step 2: Identify the bug

    The code rejects only if tokens <= 0. For fractional tokens (common in real implementations), if 0 < tokens < 1, it allows the request, decrementing to negative, which is incorrect.
  3. Final Answer:

    It should check if tokens < 1, not <= 0 -> Option D
  4. Quick Check:

    Reject if tokens < 1 [OK]
Quick Trick: Allow only if tokens >= 1 [OK]
Common Mistakes:
  • Using <= 0 instead of < 1 causes off-by-one errors
  • Increasing tokens on request instead of decreasing
  • Rejecting requests when tokens are available

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Rest API Quizzes