Why API security is non-negotiable in Rest API - Performance Analysis
When we build APIs, security checks happen every time a request comes in.
We want to understand how the time these checks take grows as more requests or data come in.
Analyze the time complexity of the following API security check snippet.
// Pseudocode for API security check
function checkApiRequest(request) {
if (!validateToken(request.token)) {
return "Unauthorized";
}
for (let permission of request.user.permissions) {
if (!hasAccess(permission, request.resource)) {
return "Forbidden";
}
}
return "Access Granted";
}
This code checks if the request token is valid, then loops through user permissions to verify access.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through user permissions to check access.
- How many times: Once per permission in the user's list.
As the number of permissions grows, the time to check them grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 permissions | Up to 10 checks |
| 100 permissions | Up to 100 checks |
| 1000 permissions | Up to 1000 checks |
Pattern observation: The time grows directly with the number of permissions.
Time Complexity: O(n)
This means the time to check security grows in a straight line with the number of permissions.
[X] Wrong: "Security checks always take the same time no matter how many permissions there are."
[OK] Correct: Each permission must be checked, so more permissions mean more time spent.
Understanding how security checks scale helps you design APIs that stay fast and safe as they grow.
"What if we cached permission checks? How would that change the time complexity?"