401 Unauthorized vs 403 Forbidden in Rest API - Performance Comparison
When working with REST APIs, understanding how server responses behave helps us write better code. Here, we look at how the server decides to respond with 401 or 403 status codes.
We want to know how the server's decision process grows as it checks user credentials and permissions.
Analyze the time complexity of this simplified REST API authorization check.
function checkAccess(request) {
if (!request.hasValidToken()) {
return 401; // Unauthorized
}
if (!request.userHasPermission()) {
return 403; // Forbidden
}
return 200; // OK
}
This code checks if a request has a valid token, then checks if the user has permission to access the resource.
Look for repeated checks or loops in the code.
- Primary operation: Checking token validity and user permissions.
- How many times: Each check runs once per request; no loops or recursion.
The checks happen once per request regardless of input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 requests | 10 token checks + 10 permission checks |
| 100 requests | 100 token checks + 100 permission checks |
| 1000 requests | 1000 token checks + 1000 permission checks |
Pattern observation: The work grows linearly with the number of requests, but each request's checks stay constant.
Time Complexity: O(1)
This means each request is handled in constant time, no matter how complex the input data is.
[X] Wrong: "Checking permissions always takes longer as the number of users grows."
[OK] Correct: Permission checks here happen once per request and do not loop over all users, so time stays constant per request.
Understanding how authorization checks scale helps you design APIs that respond quickly and securely. This skill shows you can think about both correctness and performance.
"What if the permission check involved searching through a list of roles? How would the time complexity change?"