Query parameter versioning in Rest API - Time & Space Complexity
When using query parameter versioning in REST APIs, it's important to understand how the time to handle requests changes as the number of versions grows.
We want to know how the server's work increases when it checks the version from the query parameter.
Analyze the time complexity of the following code snippet.
// Example of query parameter versioning
app.get('/api/resource', (req, res) => {
const version = req.query.v;
if (version === '1') {
// handle version 1
} else if (version === '2') {
// handle version 2
} else {
// default handler
}
res.send('response');
});
This code checks the version number from the query parameter and chooses the matching handler.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking the version value against each supported version in sequence.
- How many times: Once per request, but the number of checks grows with the number of versions.
As the number of supported versions increases, the server checks more conditions to find the right handler.
| Number of Versions (n) | Approx. Checks |
|---|---|
| 2 | 2 checks |
| 10 | 10 checks |
| 100 | 100 checks |
Pattern observation: The number of checks grows directly with the number of versions.
Time Complexity: O(n)
This means the time to find the correct version handler grows linearly as more versions are added.
[X] Wrong: "Checking the version is always constant time because it's just one query parameter."
[OK] Correct: When many versions exist, the server must check each version condition one by one, so time grows with the number of versions.
Understanding how version checks scale helps you design APIs that stay fast as they grow. This skill shows you can think about performance beyond just making code work.
"What if we replaced the if-else checks with a direct lookup in a dictionary mapping versions to handlers? How would the time complexity change?"