Header-based versioning in Rest API - Time & Space Complexity
When using header-based versioning in REST APIs, it's important to understand how the server handles requests as the number of clients grows.
We want to know how the time to process requests changes when more clients send requests with different version headers.
Analyze the time complexity of the following code snippet.
def handle_request(request):
version = request.headers.get('API-Version')
if version == '1':
return process_v1(request)
elif version == '2':
return process_v2(request)
else:
return default_response()
This code checks the API version from the request header and routes the request to the correct version handler.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking the header and selecting the matching version handler.
- How many times: Once per request received by the server.
Each request requires a simple check of the header and a call to the correct function.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 header checks and 10 function calls |
| 100 | 100 header checks and 100 function calls |
| 1000 | 1000 header checks and 1000 function calls |
Pattern observation: The work grows directly with the number of requests; each request is handled independently.
Time Complexity: O(n)
This means the time to handle requests grows linearly with the number of requests received.
[X] Wrong: "Checking the header for each request takes longer as more versions are added."
[OK] Correct: The header check is a simple conditional that runs once per request, so adding more versions only adds a few more checks, not a big increase in time per request.
Understanding how request handling scales with the number of clients and versions helps you design APIs that stay fast and reliable as they grow.
"What if we changed from simple if-else checks to searching a list of version handlers? How would the time complexity change?"