In a REST API, what is the main difference between applying rate limits per user and per IP address?
Think about what uniquely identifies a user versus what identifies a network location.
Per-user limits track requests by user identity (like a user ID), so each user has their own quota. Per-IP limits track requests by the IP address of the client, so all requests from that IP share the quota.
Given this Python function that checks rate limits, what will be the output when calling check_limit('user123', '192.168.1.10') if the user has made 5 requests and the IP has made 10 requests?
def check_limit(user_id, ip): user_limit = 5 ip_limit = 10 user_requests = {'user123': 5} ip_requests = {'192.168.1.10': 10} if user_requests.get(user_id, 0) >= user_limit: return 'User limit exceeded' if ip_requests.get(ip, 0) >= ip_limit: return 'IP limit exceeded' return 'Allowed'
Check which limit is reached first in the code.
The function first checks if the user has reached their limit. Since user123 has 5 requests which equals the limit, it returns 'User limit exceeded' before checking the IP.
What error will this code raise when calling increment_request('user1', '10.0.0.1') for the first time?
user_requests = {}
ip_requests = {}
user_limit = 3
ip_limit = 5
def increment_request(user_id, ip):
if user_requests[user_id] >= user_limit:
return 'User limit reached'
if ip_requests[ip] >= ip_limit:
return 'IP limit reached'
user_requests[user_id] += 1
ip_requests[ip] += 1
return 'Request allowed'Think about what happens when you try to access a dictionary key that does not exist.
Since the dictionaries are empty, trying to access user_requests[user_id] or ip_requests[ip] before initializing them causes a KeyError.
Which option contains the correct syntax for a Python decorator that limits API calls per user?
def rate_limit(func): def wrapper(user_id): # limit logic here return func(user_id) return wrapper
Remember what a decorator must return.
A decorator must return the inner wrapper function itself, not call it or return the original function.
You manage a public REST API used by many anonymous users behind shared IP addresses. Which rate limiting strategy is best to prevent abuse while minimizing false blocks?
Consider how anonymous users and shared IPs affect rate limiting.
Since many users share IPs, strict per-IP limits can block many legitimate users. Combining per-IP limits with higher thresholds and per-user limits for authenticated users balances protection and usability.