Bird
0
0

This code snippet is intended to enforce per-IP rate limits but has a bug:

medium📝 Debug Q14 of 15
Rest API - Rate Limiting and Throttling
This code snippet is intended to enforce per-IP rate limits but has a bug:
requests_per_ip = {"1.2.3.4": 8}
ip_limit = 10
ip = "1.2.3.4"

if requests_per_ip[ip] > ip_limit:
    print("Limit exceeded")
else:
    print("Allowed")

What is the bug and how to fix it?
ABug: Uses > instead of >=; fix by changing to >=.
BBug: ip variable is wrong type; fix by converting to string.
CBug: requests_per_ip key missing; fix by adding default value.
DBug: prints wrong message; fix by swapping print statements.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze condition logic

    The code blocks requests only if requests_per_ip[ip] > ip_limit, so if requests equal ip_limit, it allows the request.
  2. Step 2: Fix condition to include equal case

    Change > to >= so requests equal to ip_limit also get blocked.
  3. Final Answer:

    Bug: Uses > instead of >=; fix by changing to >=. -> Option A
  4. Quick Check:

    Use >= to block at limit [OK]
Quick Trick: Use >= to block requests at limit, not just above [OK]
Common Mistakes:
  • Ignoring equal case in condition
  • Assuming IP variable type is wrong
  • Thinking missing keys cause this bug

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Rest API Quizzes