Token refresh mechanism in Rest API - Time & Space Complexity
When working with token refresh mechanisms, it's important to understand how the time to process requests grows as more users or tokens are involved.
We want to know how the system's work changes when refreshing tokens for many users.
Analyze the time complexity of the following code snippet.
// Pseudocode for token refresh
POST /refresh-token
receive refreshToken
user = findUserByRefreshToken(refreshToken)
if user exists and token valid:
newAccessToken = generateAccessToken(user)
return newAccessToken
else:
return error
This code receives a refresh token, finds the user linked to it, checks validity, and returns a new access token.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Searching for the user by refresh token.
- How many times: Once per token refresh request.
As the number of users grows, finding the user by refresh token may take longer if not optimized.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 lookups |
| 100 | 100 lookups |
| 1000 | 1000 lookups |
Pattern observation: Without indexing, the search grows linearly with the number of users.
Time Complexity: O(n)
This means the time to find the user grows in direct proportion to the number of users.
[X] Wrong: "Finding a user by token always takes the same time no matter how many users exist."
[OK] Correct: If the system searches users one by one, more users mean more time. Without a fast lookup, time grows with user count.
Understanding how token refresh scales helps you design APIs that stay fast as users grow. This skill shows you can think about real system performance.
"What if we used a hash map to store refresh tokens instead of searching a list? How would the time complexity change?"