Response headers (Cache-Control, ETag) in Rest API - Time & Space Complexity
When working with response headers like Cache-Control and ETag, it's important to understand how their use affects the time your API takes to respond.
We want to know how the time to handle these headers changes as the number of requests or resources grows.
Analyze the time complexity of the following code snippet.
GET /resource HTTP/1.1
Host: example.com
Response:
Cache-Control: max-age=3600
ETag: "abc123"
Content-Type: application/json
{
"data": "..."
}
This snippet shows a server sending Cache-Control and ETag headers with a resource response to help clients cache data efficiently.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking and generating ETag for each resource requested.
- How many times: Once per request, but depends on resource size and number of requests.
As the number of requests or resource size grows, the server must generate or verify ETags and set Cache-Control headers for each response.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 requests | 10 ETag checks and header sets |
| 100 requests | 100 ETag checks and header sets |
| 1000 requests | 1000 ETag checks and header sets |
Pattern observation: The work grows linearly with the number of requests handled.
Time Complexity: O(n)
This means the time to handle response headers grows directly with the number of requests processed.
[X] Wrong: "ETag generation is free and does not affect response time."
[OK] Correct: Generating or verifying ETags requires reading or hashing resource data, which takes time proportional to resource size and request count.
Understanding how response headers affect performance shows you can think about real-world API efficiency and scalability, a valuable skill in software development.
"What if we cache ETag values instead of generating them on every request? How would the time complexity change?"