0
0
Rest APIprogramming~5 mins

Per-user vs per-IP limits in Rest API - Performance Comparison

Choose your learning style9 modes available
Time Complexity: Per-user vs per-IP limits
O(n)
Understanding Time Complexity

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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Each request triggers two quick lookups: one for the user and one for the IP.

Input Size (n)Approx. Operations
10 requests20 lookups (2 per request)
100 requests200 lookups
1000 requests2000 lookups

Pattern observation: Operations grow directly with the number of requests.

Final Time Complexity

Time Complexity: O(n)

This means the time to check limits grows linearly with the number of requests.

Common Mistake

[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.

Interview Connect

Understanding how per-user and per-IP checks scale helps you design fair and efficient APIs.

Self-Check

What if we added a nested loop to check all users' request counts on each request? How would the time complexity change?