Adding response headers (add_header) in Nginx - Time & Space Complexity
When nginx adds response headers, it processes each header line before sending the response.
We want to understand how the time to add headers grows as the number of headers increases.
Analyze the time complexity of the following nginx configuration snippet.
server {
listen 80;
location / {
add_header X-Custom-1 "Value1";
add_header X-Custom-2 "Value2";
add_header X-Custom-3 "Value3";
# ... more add_header directives ...
}
}
This snippet adds multiple custom headers to each HTTP response served by nginx.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding each header line to the response.
- How many times: Once per header configured with
add_header.
As the number of headers increases, nginx processes each header one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 headers | 10 operations |
| 100 headers | 100 operations |
| 1000 headers | 1000 operations |
Pattern observation: The work grows directly with the number of headers added.
Time Complexity: O(n)
This means the time to add headers grows linearly with the number of headers configured.
[X] Wrong: "Adding more headers does not affect response time because headers are small."
[OK] Correct: Even small headers require processing; more headers mean more work, so response time grows with header count.
Understanding how configuration directives like add_header scale helps you reason about server performance and response times in real projects.
What if nginx cached the headers once instead of adding them on every response? How would the time complexity change?