Per-user vs per-IP limits in Rest API - Performance Comparison
When setting limits on API requests, it's important to understand how the system handles these limits.
We want to see how the number of checks grows as more users or IPs make requests.
Analyze the time complexity of the following code snippet.
// Check if user has exceeded request limit
if (userRequests[userId] > userLimit) {
rejectRequest();
}
// Check if IP has exceeded request limit
if (ipRequests[ipAddress] > ipLimit) {
rejectRequest();
}
// Process request if limits not exceeded
processRequest();
This code checks request counts per user and per IP address before allowing the request.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking request counts in user and IP maps.
- How many times: Once per incoming request.
Each request triggers two quick lookups: one for the user and one for the IP.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 requests | 20 lookups (2 per request) |
| 100 requests | 200 lookups |
| 1000 requests | 2000 lookups |
Pattern observation: Operations grow directly with the number of requests.
Time Complexity: O(n)
This means the time to check limits grows linearly with the number of requests.
[X] Wrong: "Checking per-user and per-IP limits means the time grows with the number of users or IPs."
[OK] Correct: Each request only checks its own user and IP, so time depends on requests, not total users or IPs.
Understanding how per-user and per-IP checks scale helps you design fair and efficient APIs.
What if we added a nested loop to check all users' request counts on each request? How would the time complexity change?