JWT structure and flow in Rest API - Time & Space Complexity
Let's explore how the time needed to handle JWTs changes as more requests come in.
We want to know how the work grows when many tokens are created or checked.
Analyze the time complexity of the following code snippet.
// Pseudocode for JWT creation and verification
function createJWT(payload, secret) {
header = base64Encode({alg: 'HS256', typ: 'JWT'})
body = base64Encode(payload)
signature = HMAC_SHA256(header + '.' + body, secret)
return header + '.' + body + '.' + signature
}
function verifyJWT(token, secret) {
parts = token.split('.')
expectedSig = HMAC_SHA256(parts[0] + '.' + parts[1], secret)
return expectedSig === parts[2]
}
This code creates a JWT by encoding parts and signing them, then verifies by checking the signature.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Encoding and hashing the token parts.
- How many times: Each time a token is created or verified, these steps run once per request.
As the number of requests grows, the work grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 encoding and hashing operations |
| 100 | 100 encoding and hashing operations |
| 1000 | 1000 encoding and hashing operations |
Pattern observation: The work increases directly with the number of tokens processed.
Time Complexity: O(n)
This means the time needed grows directly with how many tokens you create or check.
[X] Wrong: "Verifying a JWT takes the same time no matter how many tokens are processed overall."
[OK] Correct: Each token verification is a separate operation, so more tokens mean more total work.
Understanding how token creation and verification scale helps you design APIs that stay fast as users grow.
"What if we cached verified tokens to skip repeated checks? How would the time complexity change?"